diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/nodebox/client/FileUtils.java b/src/nodebox/client/FileUtils.java index 5beb3d4a..141197fa 100644 --- a/src/nodebox/client/FileUtils.java +++ b/src/nodebox/client/FileUtils.java @@ -1,173 +1,184 @@ package nodebox.client; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.io.*; import java.util.Locale; import java.util.StringTokenizer; public class FileUtils { /** * Gets the extension of a file. * * @param f the file * @return the extension of the file. */ public static String getExtension(File f) { return getExtension(f.getName()); } /** * Gets the extension of a file. * * @param fileName the file name * @return the extension of the file. */ public static String getExtension(String fileName) { String ext = null; int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { ext = fileName.substring(i + 1).toLowerCase(Locale.US); } return ext; } public static File showOpenDialog(Frame owner, String pathName, String extensions, String description) { return showFileDialog(owner, pathName, extensions, description, FileDialog.LOAD); } public static File showSaveDialog(Frame owner, String pathName, String extensions, String description) { return showFileDialog(owner, pathName, extensions, description, FileDialog.SAVE); } private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) { FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType); if (pathName == null || pathName.trim().length() == 0) { NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); if (document != null) { File documentFile = document.getDocumentFile(); if (documentFile != null) { fileDialog.setDirectory(documentFile.getParentFile().getPath()); } } } else { File f = new File(pathName); if (f.isDirectory()) { fileDialog.setDirectory(pathName); } else { - fileDialog.setDirectory(f.getParentFile().getPath()); - fileDialog.setFile(f.getName()); + if (f.getParentFile() != null) { + fileDialog.setDirectory(f.getParentFile().getPath()); + fileDialog.setFile(f.getName()); + } else { + NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); + if (document != null) { + File documentFile = document.getDocumentFile(); + if (documentFile != null) { + fileDialog.setDirectory(documentFile.getParentFile().getPath()); + } + } + fileDialog.setFile(pathName); + } } } fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description)); fileDialog.setVisible(true); String chosenFile = fileDialog.getFile(); String dir = fileDialog.getDirectory(); if (chosenFile != null) { return new File(dir + chosenFile); } else { return null; } } public static String[] parseExtensions(String extensions) { StringTokenizer st = new StringTokenizer(extensions, ","); String[] ext = new String[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { ext[i++] = st.nextToken(); } return ext; } public static class FileExtensionFilter extends FileFilter implements FilenameFilter { String[] extensions; String description; public FileExtensionFilter(String extensions, String description) { this.extensions = parseExtensions(extensions); this.description = description; } public boolean accept(File f) { return f.isDirectory() || accept(null, f.getName()); } public boolean accept(File f, String s) { String extension = FileUtils.getExtension(s); if (extension != null) { for (String extension1 : extensions) { if (extension1.equals("*") || extension1.equalsIgnoreCase(extension)) { return true; } } } return false; } public String getDescription() { return description; } } public static String readFile(File file) { StringBuffer contents = new StringBuffer(); try { FileInputStream fstream = new FileInputStream(file); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { contents.append(line); contents.append("\n"); } in.close(); } catch (IOException e) { throw new RuntimeException("Could not read file " + file, e); } return contents.toString(); } public static void writeFile(File file, String s) { try { Writer out = new BufferedWriter(new FileWriter(file)); out.write(s); out.close(); } catch (IOException e) { throw new RuntimeException("Could not write file " + file, e); } } public static File createTemporaryDirectory(String prefix) { File tempDir = null; try { tempDir = File.createTempFile(prefix, ""); } catch (IOException e) { throw new RuntimeException("Could not create temporary file " + prefix); } boolean success = tempDir.delete(); if (!success) throw new RuntimeException("Could not delete temporary file " + tempDir); success = tempDir.mkdir(); if (!success) throw new RuntimeException("Could not create temporary directory " + tempDir); return tempDir; } public static boolean deleteDirectory(File directory) { if (directory.exists()) { File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { //noinspection ResultOfMethodCallIgnored file.delete(); } } } return (directory.delete()); } }
true
true
private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) { FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType); if (pathName == null || pathName.trim().length() == 0) { NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); if (document != null) { File documentFile = document.getDocumentFile(); if (documentFile != null) { fileDialog.setDirectory(documentFile.getParentFile().getPath()); } } } else { File f = new File(pathName); if (f.isDirectory()) { fileDialog.setDirectory(pathName); } else { fileDialog.setDirectory(f.getParentFile().getPath()); fileDialog.setFile(f.getName()); } } fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description)); fileDialog.setVisible(true); String chosenFile = fileDialog.getFile(); String dir = fileDialog.getDirectory(); if (chosenFile != null) { return new File(dir + chosenFile); } else { return null; } }
private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) { FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType); if (pathName == null || pathName.trim().length() == 0) { NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); if (document != null) { File documentFile = document.getDocumentFile(); if (documentFile != null) { fileDialog.setDirectory(documentFile.getParentFile().getPath()); } } } else { File f = new File(pathName); if (f.isDirectory()) { fileDialog.setDirectory(pathName); } else { if (f.getParentFile() != null) { fileDialog.setDirectory(f.getParentFile().getPath()); fileDialog.setFile(f.getName()); } else { NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); if (document != null) { File documentFile = document.getDocumentFile(); if (documentFile != null) { fileDialog.setDirectory(documentFile.getParentFile().getPath()); } } fileDialog.setFile(pathName); } } } fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description)); fileDialog.setVisible(true); String chosenFile = fileDialog.getFile(); String dir = fileDialog.getDirectory(); if (chosenFile != null) { return new File(dir + chosenFile); } else { return null; } }
diff --git a/src/main/java/de/beimax/spacealert/render/XmlRenderer.java b/src/main/java/de/beimax/spacealert/render/XmlRenderer.java index be5b965..08255b4 100644 --- a/src/main/java/de/beimax/spacealert/render/XmlRenderer.java +++ b/src/main/java/de/beimax/spacealert/render/XmlRenderer.java @@ -1,154 +1,155 @@ /** * This file is part of the JSpaceAlertMissionGenerator software. * Copyright (C) 2011 Maximilian Kalus * See http://www.beimax.de/ and https://github.com/mkalus/JSpaceAlertMissionGenerator * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ package de.beimax.spacealert.render; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import de.beimax.spacealert.mission.Event; import de.beimax.spacealert.mission.Mission; import de.beimax.spacealert.util.Options; /** * @author mkalus * */ public class XmlRenderer implements Renderer { /* (non-Javadoc) * @see de.beimax.spacealert.render.Renderer#print(de.beimax.spacealert.mission.Mission) */ public boolean print(Mission mission) { System.out.println(getMissionXML(mission)); return true; } /* (non-Javadoc) * @see de.beimax.spacealert.render.Renderer#output(de.beimax.spacealert.mission.Mission) */ public boolean output(Mission mission) { // get options Options options = Options.getOptions(); // check file name/size if (options.outPutfilePrefix == null || options.outPutfilePrefix.isEmpty()) { System.out.println("Error writing XML file: file prefix is empty."); } // write file try { FileWriter outFile = new FileWriter(options.outPutfilePrefix + ".xml"); outFile.write(getMissionXML(mission)); outFile.close(); } catch (IOException e) { System.out.println("Error writing XML file: " + e.getMessage()); } return true; } private String getMissionXML(Mission mission) { StringBuilder sb = new StringBuilder(); // some render statistics stuff int phaseLength = 0; int lastPhaseLength = 0; int phase = 1; // create XML beginning sb.append("<Mission>\n"); // get values for(Map.Entry<Integer,Event> entry : mission.getMissionEvents().getEntrySet()) { int time = entry.getKey(); // new phase? if (time >= phaseLength) { // calculate new phase length lastPhaseLength = phaseLength; phaseLength += mission.getMissionPhaseLength(phase); // output info sb.append("\t<Phase duration=\"" + mission.getMissionPhaseLength(phase) + "000\">\n"); // phase anouncements for secons and third phases - if (++phase >= 2) { + if (phase >= 2) { sb.append("\t\t<Element start=\"0\" type=\"Announcement\" message=\"Announce").append(phase==2?"Second":"Third").append("PhaseBegins\" />\n"); } + phase++; } sb.append("\t\t<Element start=\"").append((long)(time - lastPhaseLength) * 1000).append("\" ").append(entry.getValue().getXMLAttributes(time)).append(" />\n"); } // create XML end sb.append("\t</Phase>\n</Mission>"); return sb.toString(); } /* <Mission> <Phase duration="203000"> <Element start="0" type="Announcement" message="AnnounceBeginFirstPhase" /> <Element start="17848" type="Threat" confidence="Confirmed" threatLevel="NormalThreat" threatType="ExternalThreat" time="0" zone="Blue" /> <Element start="40943" type="DataTransfer" /> <Element start="68085" type="Threat" confidence="Unconfirmed" threatLevel="NormalThreat" threatType="InternalThreat" time="1" /> <Element start="140452" type="Announcement" message="AnnounceFirstPhaseEndsInOneMinute" /> <Element start="145638" type="CommFailure" duration="17000" /> <Element start="165712" type="Threat" confidence="Confirmed" threatLevel="SeriousThreat" threatType="InternalThreat" time="3" /> <Element start="177436" type="Announcement" message="AnnounceFirstPhaseEndsInTwentySeconds" /> <Element start="193198" type="Announcement" message="AnnounceFirstPhaseEnds" /> </Phase> <Phase duration="173000"> <Element start="0" type="Announcement" message="AnnounceSecondPhaseBegins" /> <Element start="10621" type="DataTransfer" /> <Element start="34353" type="IncomingData" /> <Element start="58479" type="Threat" confidence="Confirmed" threatLevel="NormalThreat" threatType="ExternalThreat" time="5" zone="White" /> <Element start="77687" type="CommFailure" duration="17000" /> <Element start="110634" type="Announcement" message="AnnounceSecondPhaseEndsInOneMinute" /> <Element start="119504" type="IncomingData" /> <Element start="127399" type="DataTransfer" /> <Element start="142821" type="IncomingData" /> <Element start="150114" type="Announcement" message="AnnounceSecondPhaseEndsInTwentySeconds" /> <Element start="163276" type="Announcement" message="AnnounceSecondPhaseEnds" /> </Phase> <Phase duration="125000"> <Element start="0" type="Announcement" message="AnnounceThirdPhaseBegins" /> <Element start="10190" type="DataTransfer" /> <Element start="31021" type="CommFailure" duration="14000" /> <Element start="62530" type="Announcement" message="AnnounceThirdPhaseEndsInOneMinute" /> <Element start="102218" type="Announcement" message="AnnounceThirdPhaseEndsInTwentySeconds" /> <Element start="118000" type="Announcement" message="AnnounceThirdPhaseEnds" /> </Phase> </Mission> */ @Override public String toString() { return "XML"; } }
false
true
private String getMissionXML(Mission mission) { StringBuilder sb = new StringBuilder(); // some render statistics stuff int phaseLength = 0; int lastPhaseLength = 0; int phase = 1; // create XML beginning sb.append("<Mission>\n"); // get values for(Map.Entry<Integer,Event> entry : mission.getMissionEvents().getEntrySet()) { int time = entry.getKey(); // new phase? if (time >= phaseLength) { // calculate new phase length lastPhaseLength = phaseLength; phaseLength += mission.getMissionPhaseLength(phase); // output info sb.append("\t<Phase duration=\"" + mission.getMissionPhaseLength(phase) + "000\">\n"); // phase anouncements for secons and third phases if (++phase >= 2) { sb.append("\t\t<Element start=\"0\" type=\"Announcement\" message=\"Announce").append(phase==2?"Second":"Third").append("PhaseBegins\" />\n"); } } sb.append("\t\t<Element start=\"").append((long)(time - lastPhaseLength) * 1000).append("\" ").append(entry.getValue().getXMLAttributes(time)).append(" />\n"); } // create XML end sb.append("\t</Phase>\n</Mission>"); return sb.toString(); }
private String getMissionXML(Mission mission) { StringBuilder sb = new StringBuilder(); // some render statistics stuff int phaseLength = 0; int lastPhaseLength = 0; int phase = 1; // create XML beginning sb.append("<Mission>\n"); // get values for(Map.Entry<Integer,Event> entry : mission.getMissionEvents().getEntrySet()) { int time = entry.getKey(); // new phase? if (time >= phaseLength) { // calculate new phase length lastPhaseLength = phaseLength; phaseLength += mission.getMissionPhaseLength(phase); // output info sb.append("\t<Phase duration=\"" + mission.getMissionPhaseLength(phase) + "000\">\n"); // phase anouncements for secons and third phases if (phase >= 2) { sb.append("\t\t<Element start=\"0\" type=\"Announcement\" message=\"Announce").append(phase==2?"Second":"Third").append("PhaseBegins\" />\n"); } phase++; } sb.append("\t\t<Element start=\"").append((long)(time - lastPhaseLength) * 1000).append("\" ").append(entry.getValue().getXMLAttributes(time)).append(" />\n"); } // create XML end sb.append("\t</Phase>\n</Mission>"); return sb.toString(); }
diff --git a/src/zz/utils/notification/NotificationManager.java b/src/zz/utils/notification/NotificationManager.java index 3be07fc..e046410 100644 --- a/src/zz/utils/notification/NotificationManager.java +++ b/src/zz/utils/notification/NotificationManager.java @@ -1,133 +1,138 @@ /* * Created by IntelliJ IDEA. * User: gpothier * Date: Feb 18, 2002 * Time: 2:15:59 PM * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package zz.utils.notification; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.List; import zz.utils.FailsafeLinkedList; import zz.utils.Utils; /** * Registers a set of {@link Notifiable notifiables} whose {@link Notifiable#processMessage(Message) } method * will be called when this {@link #notify(Message) } is invoked. */ public class NotificationManager { private List itsNotifiableReferences = new FailsafeLinkedList(); private boolean itsActive = true; public NotificationManager() { } /** * Activates or deactivates the notification manager. * When deactivated, it doesn't dispatch any message. */ public void setActive(boolean aActive) { itsActive = aActive; } public boolean isActive() { return itsActive; } /** * Removes all Notifiables from the notification manager */ public void clear() { itsNotifiableReferences.clear(); check(); } /** * Adds a notifiable to the list. * <p> * IMPORTANT: the notifiables are held in weak references, so constructs such as * <code> * theNotificationManager.addNotifiable (new Notifiable () * { * ... * }); * </code> * are incorrect, as the notifiable will be immediately garbage collected. */ public void addNotifiable(Notifiable aNotifiable) { itsNotifiableReferences.add(new NotifiableReference(aNotifiable)); check(); } public void removeNotifiable(Notifiable aNotifiable) { Utils.remove(aNotifiable, itsNotifiableReferences); check(); } private void check() { for (Iterator theIterator = itsNotifiableReferences.iterator(); theIterator.hasNext();) { NotifiableReference theNotifiableReference = (NotifiableReference) theIterator.next(); assert theNotifiableReference != null; } } public void notify(Message aMessage) { check(); if (!isActive()) return; for (Iterator theIterator = itsNotifiableReferences.iterator(); theIterator.hasNext();) { NotifiableReference theNotifiableReference = (NotifiableReference) theIterator.next(); + if (theNotifiableReference == null) + { + System.err.println("NotificationManager.notify(): null notifiable reference - investigate"); + continue; + } Notifiable theNotifiable = theNotifiableReference.getNotifiable(); if (theNotifiable == null) theIterator.remove(); else theNotifiable.processMessage(aMessage); } check(); } private static class NotifiableReference extends WeakReference { public NotifiableReference(Notifiable aNotifiable) { super(aNotifiable); } public Notifiable getNotifiable() { return (Notifiable) get(); } public boolean equals(Object obj) { if (obj == this) return true; if (obj instanceof Notifiable) { Notifiable theNotifiable = (Notifiable) obj; return theNotifiable == getNotifiable(); } return false; } } }
true
true
public void notify(Message aMessage) { check(); if (!isActive()) return; for (Iterator theIterator = itsNotifiableReferences.iterator(); theIterator.hasNext();) { NotifiableReference theNotifiableReference = (NotifiableReference) theIterator.next(); Notifiable theNotifiable = theNotifiableReference.getNotifiable(); if (theNotifiable == null) theIterator.remove(); else theNotifiable.processMessage(aMessage); } check(); }
public void notify(Message aMessage) { check(); if (!isActive()) return; for (Iterator theIterator = itsNotifiableReferences.iterator(); theIterator.hasNext();) { NotifiableReference theNotifiableReference = (NotifiableReference) theIterator.next(); if (theNotifiableReference == null) { System.err.println("NotificationManager.notify(): null notifiable reference - investigate"); continue; } Notifiable theNotifiable = theNotifiableReference.getNotifiable(); if (theNotifiable == null) theIterator.remove(); else theNotifiable.processMessage(aMessage); } check(); }
diff --git a/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java b/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java index 01569eff..3922b825 100644 --- a/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java +++ b/gwt-client/src/main/java/org/mule/galaxy/web/client/property/EditPropertyPanel.java @@ -1,252 +1,251 @@ package org.mule.galaxy.web.client.property; import com.google.gwt.user.client.ui.*; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Widget; import java.io.Serializable; import java.util.Collection; import org.mule.galaxy.web.client.AbstractComposite; import org.mule.galaxy.web.client.ErrorPanel; import org.mule.galaxy.web.client.Galaxy; import org.mule.galaxy.web.client.util.ConfirmDialog; import org.mule.galaxy.web.client.util.ConfirmDialogAdapter; import org.mule.galaxy.web.client.util.InlineFlowPanel; import org.mule.galaxy.web.client.util.LightBox; import org.mule.galaxy.web.rpc.AbstractCallback; import org.mule.galaxy.web.rpc.WProperty; /** * Encapsulates the rendering and editing of a property value. */ public class EditPropertyPanel extends AbstractComposite { private Button save; protected Button cancel; private AbstractPropertyRenderer renderer; protected InlineFlowPanel panel; protected ErrorPanel errorPanel; protected String itemId; protected WProperty property; protected Galaxy galaxy; protected ClickListener saveListener; protected ClickListener deleteListener; protected ClickListener cancelListener; public EditPropertyPanel(AbstractPropertyRenderer renderer) { super(); this.panel = new InlineFlowPanel(); initWidget(panel); this.renderer = renderer; } public void initialize() { initializeRenderer(); } public InlineFlowPanel createViewPanel() { Image editImg = new Image("images/page_edit.gif"); editImg.setStyleName("icon-baseline"); editImg.setTitle("Edit"); editImg.addClickListener(new ClickListener() { public void onClick(Widget widget) { showEdit(); } }); Image deleteImg = new Image("images/delete_config.gif"); deleteImg.setStyleName("icon-baseline"); deleteImg.setTitle("Delete"); deleteImg.addClickListener(new ClickListener() { public void onClick(Widget widget) { delete(); } }); InlineFlowPanel viewPanel = new InlineFlowPanel(); viewPanel.add(renderer.createViewWidget()); if (!property.isLocked()) { // interesting... spacer label has to be a new object ref, otherwise not honored... viewPanel.add(new Label(" ")); viewPanel.add(editImg); viewPanel.add(new Label(" ")); viewPanel.add(deleteImg); } return viewPanel; } protected FlowPanel createEditPanel() { FlowPanel editPanel = new FlowPanel(); editPanel.setStyleName("add-property-inline"); Widget editForm = renderer.createEditForm(); - editForm.setStyleName("add-property-inline"); editPanel.add(editForm); FlowPanel buttonPanel = new FlowPanel(); cancel = new Button("Cancel"); cancel.addClickListener(new ClickListener() { public void onClick(Widget arg0) { cancel(); } }); if (cancelListener != null) { cancel.addClickListener(cancelListener); } save = new Button("Save"); save.addClickListener(new ClickListener() { public void onClick(Widget arg0) { cancel.setEnabled(false); save.setEnabled(false); save(); } }); buttonPanel.add(save); buttonPanel.add(cancel); editPanel.add(buttonPanel); return editPanel; } protected void cancel() { initializeRenderer(); showView(); } public void showView() { panel.clear(); panel.add(createViewPanel()); } protected void delete() { final ConfirmDialog dialog = new ConfirmDialog(new ConfirmDialogAdapter() { public void onConfirm() { doDelete(); } }, "Are you sure you want to delete this property?"); new LightBox(dialog).show(); } protected void doDelete() { galaxy.getRegistryService().deleteProperty(itemId, property.getName(), new AbstractCallback(errorPanel) { public void onSuccess(Object arg0) { deleteListener.onClick(null); } }); } public void showEdit() { panel.clear(); FlowPanel editPanel = createEditPanel(); panel.add(editPanel); } protected void save() { final Serializable value = (Serializable) renderer.getValueToSave(); AbstractCallback saveCallback = getSaveCallback(value); setEnabled(false); renderer.save(itemId, property.getName(), value, saveCallback); } protected AbstractCallback getSaveCallback(final Serializable value) { AbstractCallback saveCallback = new AbstractCallback(errorPanel) { public void onFailure(Throwable caught) { onSaveFailure(caught, this); } public void onSuccess(Object response) { onSave(value, response); } }; return saveCallback; } protected void onSave(final Serializable value, Object response) { setEnabled(true); property.setValue(value); initializeRenderer(); showView(); if (saveListener != null) { saveListener.onClick(save); } } private void initializeRenderer() { renderer.initialize(galaxy, errorPanel, property.getValue(), false); } protected void onSaveFailure(Throwable caught, AbstractCallback saveCallback) { saveCallback.onFailureDirect(caught); } public WProperty getProperty() { return property; } public void setProperty(WProperty property) { this.property = property; } public void setGalaxy(Galaxy galaxy) { this.galaxy = galaxy; } public void setErrorPanel(ErrorPanel errorPanel) { this.errorPanel = errorPanel; } public void setItemId(String entryid) { this.itemId = entryid; } public void setEnabled(boolean b) { if (cancel != null) { cancel.setEnabled(b); } if (save != null) { save.setEnabled(b); } } public void setSaveListener(ClickListener saveListener) { this.saveListener = saveListener; } public void setDeleteListener(ClickListener deleteListener) { this.deleteListener = deleteListener; } public void setCancelListener(ClickListener cancelListener) { this.cancelListener = cancelListener; } }
true
true
protected FlowPanel createEditPanel() { FlowPanel editPanel = new FlowPanel(); editPanel.setStyleName("add-property-inline"); Widget editForm = renderer.createEditForm(); editForm.setStyleName("add-property-inline"); editPanel.add(editForm); FlowPanel buttonPanel = new FlowPanel(); cancel = new Button("Cancel"); cancel.addClickListener(new ClickListener() { public void onClick(Widget arg0) { cancel(); } }); if (cancelListener != null) { cancel.addClickListener(cancelListener); } save = new Button("Save"); save.addClickListener(new ClickListener() { public void onClick(Widget arg0) { cancel.setEnabled(false); save.setEnabled(false); save(); } }); buttonPanel.add(save); buttonPanel.add(cancel); editPanel.add(buttonPanel); return editPanel; }
protected FlowPanel createEditPanel() { FlowPanel editPanel = new FlowPanel(); editPanel.setStyleName("add-property-inline"); Widget editForm = renderer.createEditForm(); editPanel.add(editForm); FlowPanel buttonPanel = new FlowPanel(); cancel = new Button("Cancel"); cancel.addClickListener(new ClickListener() { public void onClick(Widget arg0) { cancel(); } }); if (cancelListener != null) { cancel.addClickListener(cancelListener); } save = new Button("Save"); save.addClickListener(new ClickListener() { public void onClick(Widget arg0) { cancel.setEnabled(false); save.setEnabled(false); save(); } }); buttonPanel.add(save); buttonPanel.add(cancel); editPanel.add(buttonPanel); return editPanel; }
diff --git a/ridiculousRPG/src/com/ridiculousRPG/movement/auto/MovePolygonAdapter.java b/ridiculousRPG/src/com/ridiculousRPG/movement/auto/MovePolygonAdapter.java index be57018..3d41867 100644 --- a/ridiculousRPG/src/com/ridiculousRPG/movement/auto/MovePolygonAdapter.java +++ b/ridiculousRPG/src/com/ridiculousRPG/movement/auto/MovePolygonAdapter.java @@ -1,177 +1,180 @@ /* * Copyright 2011 Alexander Baumgartner * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ridiculousRPG.movement.auto; import java.util.Map; import javax.script.ScriptEngine; import com.badlogic.gdx.Gdx; import com.ridiculousRPG.GameBase; import com.ridiculousRPG.event.EventObject; import com.ridiculousRPG.event.PolygonObject; import com.ridiculousRPG.event.handler.EventHandler; import com.ridiculousRPG.movement.Movable; import com.ridiculousRPG.movement.MovementHandler; import com.ridiculousRPG.util.ObjectState; /** * This {@link MovementHandler} tries to move an event along the given polygon. * The move waits if a blocking event exists on it's way.<br> * After succeeding the switch finished is set to true. * * @author Alexander Baumgartner */ public class MovePolygonAdapter extends MovementHandler { private static final long serialVersionUID = 1L; private PolygonObject polygon; private String execScript; private String polygonName; private boolean polygonChanged; private boolean rewind; private boolean crop; private static String NODE_TEMPLATE; public boolean isRewind() { return rewind; } public void setRewind(boolean rewind) { this.rewind = rewind; if (finished) polygonChanged = true; } public boolean isCrop() { return crop; } public void setCrop(boolean crop) { this.crop = crop; } public MovePolygonAdapter(PolygonObject polygon) { this(polygon, false); } public MovePolygonAdapter(PolygonObject polygon, boolean rewind) { this.rewind = rewind; setPolygon(polygon); } public MovePolygonAdapter(String polyName) { this(polyName, false); } public MovePolygonAdapter(String polyName, boolean rewind) { this.rewind = rewind; this.polygonName = polyName; } public PolygonObject getPolygon() { return polygon; } public void setPolygon(PolygonObject polygon) { this.polygon = polygon; this.polygonName = polygon.getName(); polygonChanged = true; } public String getPolygonName() { return polygonName; } public void setPolygonName(String polygonName) { this.polygonName = polygonName; } public boolean offerPolygons(Map<String, PolygonObject> polyMap) { if (polygonName == null) return false; PolygonObject newPoly = polyMap.get(polygonName); if (newPoly == null) return false; this.polygon = newPoly; polygonChanged = true; return true; } @Override public void tryMove(Movable event, float deltaTime) { if (execScript != null) { if (NODE_TEMPLATE == null) NODE_TEMPLATE = Gdx.files.internal( GameBase.$options().eventNodeTemplate).readString( GameBase.$options().encoding); try { String script = GameBase.$scriptFactory() .prepareScriptFunction(execScript, NODE_TEMPLATE); GameBase.$().getSharedEngine().put(ScriptEngine.FILENAME, "onNode-Event-" + polygonName); ObjectState state = null; if (event instanceof EventObject) { EventHandler h = ((EventObject) event).getEventHandler(); if (h != null) state = h.getActualState(); } GameBase.$().invokeFunction(script, "onNode", event, state, polygon, this); } catch (Exception e) { GameBase.$error("PolygonObject.onNode", "Could not execute " + "onNode script for " + event + " " + polygon, e); } execScript = null; } if (polygonChanged) { reset(); } else if (finished) { event.stop(); } if (!finished && polygon != null) { float distance = event.getMoveSpeed().computeStretch(deltaTime); if (distance > 0) { - execScript = polygon.moveAlong(distance, crop); + if (rewind) + execScript = polygon.moveAlong(-distance, crop); + else + execScript = polygon.moveAlong(distance, crop); event.offerMove(polygon.getRelativeX(), polygon.getRelativeY()); if (event instanceof EventObject) { ((EventObject) event).animate(polygon.getRelativeX(), polygon.getRelativeY(), deltaTime); } finished = polygon.isFinished(); } } } @Override public void moveBlocked(Movable event) { if (polygon != null) polygon.undoMove(); execScript = null; event.stop(); } @Override public void reset() { super.reset(); polygonChanged = false; execScript = null; if (polygon != null) polygon.start(rewind); } }
true
true
public void tryMove(Movable event, float deltaTime) { if (execScript != null) { if (NODE_TEMPLATE == null) NODE_TEMPLATE = Gdx.files.internal( GameBase.$options().eventNodeTemplate).readString( GameBase.$options().encoding); try { String script = GameBase.$scriptFactory() .prepareScriptFunction(execScript, NODE_TEMPLATE); GameBase.$().getSharedEngine().put(ScriptEngine.FILENAME, "onNode-Event-" + polygonName); ObjectState state = null; if (event instanceof EventObject) { EventHandler h = ((EventObject) event).getEventHandler(); if (h != null) state = h.getActualState(); } GameBase.$().invokeFunction(script, "onNode", event, state, polygon, this); } catch (Exception e) { GameBase.$error("PolygonObject.onNode", "Could not execute " + "onNode script for " + event + " " + polygon, e); } execScript = null; } if (polygonChanged) { reset(); } else if (finished) { event.stop(); } if (!finished && polygon != null) { float distance = event.getMoveSpeed().computeStretch(deltaTime); if (distance > 0) { execScript = polygon.moveAlong(distance, crop); event.offerMove(polygon.getRelativeX(), polygon.getRelativeY()); if (event instanceof EventObject) { ((EventObject) event).animate(polygon.getRelativeX(), polygon.getRelativeY(), deltaTime); } finished = polygon.isFinished(); } } }
public void tryMove(Movable event, float deltaTime) { if (execScript != null) { if (NODE_TEMPLATE == null) NODE_TEMPLATE = Gdx.files.internal( GameBase.$options().eventNodeTemplate).readString( GameBase.$options().encoding); try { String script = GameBase.$scriptFactory() .prepareScriptFunction(execScript, NODE_TEMPLATE); GameBase.$().getSharedEngine().put(ScriptEngine.FILENAME, "onNode-Event-" + polygonName); ObjectState state = null; if (event instanceof EventObject) { EventHandler h = ((EventObject) event).getEventHandler(); if (h != null) state = h.getActualState(); } GameBase.$().invokeFunction(script, "onNode", event, state, polygon, this); } catch (Exception e) { GameBase.$error("PolygonObject.onNode", "Could not execute " + "onNode script for " + event + " " + polygon, e); } execScript = null; } if (polygonChanged) { reset(); } else if (finished) { event.stop(); } if (!finished && polygon != null) { float distance = event.getMoveSpeed().computeStretch(deltaTime); if (distance > 0) { if (rewind) execScript = polygon.moveAlong(-distance, crop); else execScript = polygon.moveAlong(distance, crop); event.offerMove(polygon.getRelativeX(), polygon.getRelativeY()); if (event instanceof EventObject) { ((EventObject) event).animate(polygon.getRelativeX(), polygon.getRelativeY(), deltaTime); } finished = polygon.isFinished(); } } }
diff --git a/srcj/com/sun/electric/tool/io/input/DELIB.java b/srcj/com/sun/electric/tool/io/input/DELIB.java index 6f6d5aab1..e5e42db2b 100644 --- a/srcj/com/sun/electric/tool/io/input/DELIB.java +++ b/srcj/com/sun/electric/tool/io/input/DELIB.java @@ -1,109 +1,109 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: DELIB.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.io.input; import com.sun.electric.database.text.Version; import com.sun.electric.tool.io.FileType; import java.io.*; /** * Created by IntelliJ IDEA. * User: gainsley * Date: Mar 8, 2006 * Time: 4:24:47 PM * To change this template use File | Settings | File Templates. */ public class DELIB extends JELIB { // private static String[] revisions = // { // // revision 1 // "8.04f" // }; private LineNumberReader headerReader; DELIB() {} /** * Method to read a Library in new library file (.jelib) format. * @return true on error. */ protected boolean readLib() { String header = filePath + File.separator + "header"; try { FileInputStream fin = new FileInputStream(header); InputStreamReader is = new InputStreamReader(fin); headerReader = new LineNumberReader(is); } catch (IOException e) { System.out.println("Error opening file "+header+": "+e.getMessage()); return true; } lineReader = headerReader; return super.readLib(); } protected void readCell(String line) throws IOException { if (lineReader != headerReader) { // already reading a separate cell file super.readCell(line); return; } // get the file location; remove 'C' at start String cellFile = line.substring(1, line.length()); - File cellFD = new File(filePath + File.separator + cellFile); + File cellFD = new File(filePath, cellFile); LineNumberReader cellReader; try { FileInputStream fin = new FileInputStream(cellFD); InputStreamReader is = new InputStreamReader(fin); cellReader = new LineNumberReader(is); } catch (IOException e) { System.out.println("Error opening file "+cellFD+": "+e.getMessage()); return; } Version savedVersion = version; int savedRevision = revision; char savedEscapeChar = escapeChar; String savedCurLibName = curLibName; lineReader = cellReader; try { readFromFile(true); } finally { version = savedVersion; revision = savedRevision; escapeChar = savedEscapeChar; curLibName = savedCurLibName; lineReader.close(); lineReader = headerReader; } } protected FileType getPreferredFileType() { return FileType.DELIB; } }
true
true
protected void readCell(String line) throws IOException { if (lineReader != headerReader) { // already reading a separate cell file super.readCell(line); return; } // get the file location; remove 'C' at start String cellFile = line.substring(1, line.length()); File cellFD = new File(filePath + File.separator + cellFile); LineNumberReader cellReader; try { FileInputStream fin = new FileInputStream(cellFD); InputStreamReader is = new InputStreamReader(fin); cellReader = new LineNumberReader(is); } catch (IOException e) { System.out.println("Error opening file "+cellFD+": "+e.getMessage()); return; } Version savedVersion = version; int savedRevision = revision; char savedEscapeChar = escapeChar; String savedCurLibName = curLibName; lineReader = cellReader; try { readFromFile(true); } finally { version = savedVersion; revision = savedRevision; escapeChar = savedEscapeChar; curLibName = savedCurLibName; lineReader.close(); lineReader = headerReader; } }
protected void readCell(String line) throws IOException { if (lineReader != headerReader) { // already reading a separate cell file super.readCell(line); return; } // get the file location; remove 'C' at start String cellFile = line.substring(1, line.length()); File cellFD = new File(filePath, cellFile); LineNumberReader cellReader; try { FileInputStream fin = new FileInputStream(cellFD); InputStreamReader is = new InputStreamReader(fin); cellReader = new LineNumberReader(is); } catch (IOException e) { System.out.println("Error opening file "+cellFD+": "+e.getMessage()); return; } Version savedVersion = version; int savedRevision = revision; char savedEscapeChar = escapeChar; String savedCurLibName = curLibName; lineReader = cellReader; try { readFromFile(true); } finally { version = savedVersion; revision = savedRevision; escapeChar = savedEscapeChar; curLibName = savedCurLibName; lineReader.close(); lineReader = headerReader; } }
diff --git a/fr.mvanbesien.calendars/src/main/java/fr/mvanbesien/calendars/calendars/DarianCalendar.java b/fr.mvanbesien.calendars/src/main/java/fr/mvanbesien/calendars/calendars/DarianCalendar.java index 04637a8..af81dd9 100644 --- a/fr.mvanbesien.calendars/src/main/java/fr/mvanbesien/calendars/calendars/DarianCalendar.java +++ b/fr.mvanbesien.calendars/src/main/java/fr/mvanbesien/calendars/calendars/DarianCalendar.java @@ -1,83 +1,83 @@ package fr.mvanbesien.calendars.calendars; import java.util.Calendar; import fr.mvanbesien.calendars.dates.DarianDate; /** * Displays a Mars Darian Calendar Date. * * @author mvanbesien * */ public class DarianCalendar { /** * Days difference with Unix Epoch */ private static final float UNIX_EPOCH = 719527; /** * Ration between days length on mars and on earth */ private static final float DAY_RATIO = 1.027491251f; /** * Epoch since beginning of Darian calendar. */ private static final float DARIAN_EPOCH = 587744.77817f; /** * @return Darian Date corresponding to now. */ public static DarianDate getDate() { return getDate(Calendar.getInstance()); } /** * @return Darian Date corresponding to calendar passed as parameter.. */ public static DarianDate getDate(Calendar calendar) { // Computation of Sols double elapsedDays = new Double(calendar.getTimeInMillis()) / 86400000 + UNIX_EPOCH; double elapsedSols = (elapsedDays - DARIAN_EPOCH) / DAY_RATIO; // First decomposition, based on 500yr basis int halfMilleniums = (int) (elapsedSols / 334296); int halfMilleniumReminder = (int) (elapsedSols - halfMilleniums * 334296); // Second decomposition, based on 100yr basis int centuries = halfMilleniumReminder != 0 ? (halfMilleniumReminder - 1) / 66859 : 0; int centuryReminder = halfMilleniumReminder - (centuries != 0 ? centuries * 66859 + 1 : 0); // Third decomposition, based on 10yr basis int decadeLeapDayValue = centuries == 0 ? 0 : 1; int decades = (centuryReminder + decadeLeapDayValue) / 6686; int decadeReminder = centuryReminder - (decades != 0 ? decades * 6686 - decadeLeapDayValue : 0); // Fourth decomposition, based on 2yr basis int twoYrsLeapDayValue = centuries != 0 && decades == 0 ? 0 : 1; int twoYrsPeriod = (decadeReminder - twoYrsLeapDayValue) / 1337; int twoYrsPeriodReminder = decadeReminder - (twoYrsPeriod != 0 ? twoYrsPeriod * 1337 + twoYrsLeapDayValue : 0); // Fifth and last decomposition, based on yearly basis int yearLeapDayValue = twoYrsPeriod == 0 && (decades != 0 || (decades == 0 && centuries == 0)) ? 0 : 1; int year = (twoYrsPeriodReminder + yearLeapDayValue) / 669; int yearReminder = twoYrsPeriodReminder - (year != 0 ? 669 - yearLeapDayValue : 0); // Now, we put all together to compute the date... int years = 500 * halfMilleniums + 100 * centuries + 10 * decades + 2 * twoYrsPeriod + year; int quarter = yearReminder / 167 < 4 ? yearReminder / 167 : 3; int solInQuarter = yearReminder - 167 * quarter; int monthInQuarter = solInQuarter / 28; int month = monthInQuarter + 6 * quarter; - int sol = yearReminder - monthInQuarter * 28 - quarter + 1; + int sol = yearReminder - ((month - 1) * 28 - quarter) + 1; DarianDate date = new DarianDate(); date.setOrdinaryDate(0, sol, month, years); return date; } }
true
true
public static DarianDate getDate(Calendar calendar) { // Computation of Sols double elapsedDays = new Double(calendar.getTimeInMillis()) / 86400000 + UNIX_EPOCH; double elapsedSols = (elapsedDays - DARIAN_EPOCH) / DAY_RATIO; // First decomposition, based on 500yr basis int halfMilleniums = (int) (elapsedSols / 334296); int halfMilleniumReminder = (int) (elapsedSols - halfMilleniums * 334296); // Second decomposition, based on 100yr basis int centuries = halfMilleniumReminder != 0 ? (halfMilleniumReminder - 1) / 66859 : 0; int centuryReminder = halfMilleniumReminder - (centuries != 0 ? centuries * 66859 + 1 : 0); // Third decomposition, based on 10yr basis int decadeLeapDayValue = centuries == 0 ? 0 : 1; int decades = (centuryReminder + decadeLeapDayValue) / 6686; int decadeReminder = centuryReminder - (decades != 0 ? decades * 6686 - decadeLeapDayValue : 0); // Fourth decomposition, based on 2yr basis int twoYrsLeapDayValue = centuries != 0 && decades == 0 ? 0 : 1; int twoYrsPeriod = (decadeReminder - twoYrsLeapDayValue) / 1337; int twoYrsPeriodReminder = decadeReminder - (twoYrsPeriod != 0 ? twoYrsPeriod * 1337 + twoYrsLeapDayValue : 0); // Fifth and last decomposition, based on yearly basis int yearLeapDayValue = twoYrsPeriod == 0 && (decades != 0 || (decades == 0 && centuries == 0)) ? 0 : 1; int year = (twoYrsPeriodReminder + yearLeapDayValue) / 669; int yearReminder = twoYrsPeriodReminder - (year != 0 ? 669 - yearLeapDayValue : 0); // Now, we put all together to compute the date... int years = 500 * halfMilleniums + 100 * centuries + 10 * decades + 2 * twoYrsPeriod + year; int quarter = yearReminder / 167 < 4 ? yearReminder / 167 : 3; int solInQuarter = yearReminder - 167 * quarter; int monthInQuarter = solInQuarter / 28; int month = monthInQuarter + 6 * quarter; int sol = yearReminder - monthInQuarter * 28 - quarter + 1; DarianDate date = new DarianDate(); date.setOrdinaryDate(0, sol, month, years); return date; }
public static DarianDate getDate(Calendar calendar) { // Computation of Sols double elapsedDays = new Double(calendar.getTimeInMillis()) / 86400000 + UNIX_EPOCH; double elapsedSols = (elapsedDays - DARIAN_EPOCH) / DAY_RATIO; // First decomposition, based on 500yr basis int halfMilleniums = (int) (elapsedSols / 334296); int halfMilleniumReminder = (int) (elapsedSols - halfMilleniums * 334296); // Second decomposition, based on 100yr basis int centuries = halfMilleniumReminder != 0 ? (halfMilleniumReminder - 1) / 66859 : 0; int centuryReminder = halfMilleniumReminder - (centuries != 0 ? centuries * 66859 + 1 : 0); // Third decomposition, based on 10yr basis int decadeLeapDayValue = centuries == 0 ? 0 : 1; int decades = (centuryReminder + decadeLeapDayValue) / 6686; int decadeReminder = centuryReminder - (decades != 0 ? decades * 6686 - decadeLeapDayValue : 0); // Fourth decomposition, based on 2yr basis int twoYrsLeapDayValue = centuries != 0 && decades == 0 ? 0 : 1; int twoYrsPeriod = (decadeReminder - twoYrsLeapDayValue) / 1337; int twoYrsPeriodReminder = decadeReminder - (twoYrsPeriod != 0 ? twoYrsPeriod * 1337 + twoYrsLeapDayValue : 0); // Fifth and last decomposition, based on yearly basis int yearLeapDayValue = twoYrsPeriod == 0 && (decades != 0 || (decades == 0 && centuries == 0)) ? 0 : 1; int year = (twoYrsPeriodReminder + yearLeapDayValue) / 669; int yearReminder = twoYrsPeriodReminder - (year != 0 ? 669 - yearLeapDayValue : 0); // Now, we put all together to compute the date... int years = 500 * halfMilleniums + 100 * centuries + 10 * decades + 2 * twoYrsPeriod + year; int quarter = yearReminder / 167 < 4 ? yearReminder / 167 : 3; int solInQuarter = yearReminder - 167 * quarter; int monthInQuarter = solInQuarter / 28; int month = monthInQuarter + 6 * quarter; int sol = yearReminder - ((month - 1) * 28 - quarter) + 1; DarianDate date = new DarianDate(); date.setOrdinaryDate(0, sol, month, years); return date; }
diff --git a/x10.compiler/src/x10cpp/debug/LineNumberMap.java b/x10.compiler/src/x10cpp/debug/LineNumberMap.java index 96c16be98..1cfac68fa 100644 --- a/x10.compiler/src/x10cpp/debug/LineNumberMap.java +++ b/x10.compiler/src/x10cpp/debug/LineNumberMap.java @@ -1,1067 +1,1067 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.opensource.org/licenses/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10cpp.debug; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.TreeSet; import polyglot.types.Context; import polyglot.types.MemberDef; import polyglot.types.MethodDef; import polyglot.types.ProcedureDef; import polyglot.types.Ref; import polyglot.types.Type; import polyglot.util.QuotedStringTokenizer; import polyglot.util.StringUtil; import x10.util.ClassifiedStream; import x10cpp.visit.Emitter; /** * Map from generated filename and line to source filename and line. * (C++ filename (String), C++ line number range (int, int)) -> * (X10 filename (String), X10 line number (int)). * Also stores the method mapping. * * @author igor */ public class LineNumberMap extends StringTable { /** A map key representing a C++ source file/line range combination. */ private static class Key { public final int fileId; public final int start_line; public final int end_line; public Key(int f, int s, int e) { fileId = f; start_line = s; end_line = e; } public String toString() { return fileId + ":" + start_line + "-" + end_line; } public int hashCode() { return fileId + start_line + end_line; } public boolean equals(Object o) { if (getClass() != o.getClass()) return false; Key k = (Key) o; return fileId == k.fileId && start_line == k.start_line && end_line == k.end_line; } } /** A map entry representing an X10 source file/line combination. */ private static class Entry { public final int fileId; public final int line; public final int column; public Entry(int f, int l, int c) { fileId = f; line = l; column = c; } public String toString() { return fileId + ":" + line; } } private final HashMap<Key, Entry> map; private static class MethodDescriptor { public final int returnType; public final int container; public final int name; public final int[] args; public final Key lines; public MethodDescriptor(int returnType, int container, int name, int[] args, Key lines) { this.returnType = returnType; this.container = container; this.name = name; this.args = args; this.lines = lines; } public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) return false; MethodDescriptor md = (MethodDescriptor) obj; if (md.name != name || md.container != container || md.returnType != returnType || md.args.length != args.length) { return false; } for (int i = 0; i < args.length; i++) { if (args[i] != md.args[i]) return false; } return true; } public int hashCode() { int h = name; h = 31*h + container; h = 31*h + returnType; for (int arg : args) { h = 31*h + arg; } return h; } public String toString() { StringBuilder res = new StringBuilder(); res.append(returnType).append(" "); res.append(container).append("."); res.append(name).append("("); boolean first = true; for (int arg : args) { if (!first) res.append(","); first = false; res.append(arg); } res.append(")"); res.append("{").append(lines.fileId); res.append(",").append(lines.start_line); res.append(",").append(lines.end_line); res.append("}"); return res.toString(); } public static MethodDescriptor parse(String str) { StringTokenizer st = new StringTokenizer(str, ". (),", true); String s = st.nextToken(" "); int r = Integer.parseInt(s); s = st.nextToken(); assert (s.equals(" ")); s = st.nextToken("."); int c = Integer.parseInt(s); s = st.nextToken(); assert (s.equals(".")); s = st.nextToken("("); int n = Integer.parseInt(s); s = st.nextToken(); assert (s.equals("(")); ArrayList<String> al = new ArrayList<String>(); while (st.hasMoreTokens()) { String t = st.nextToken(",)"); if (t.equals(")")) break; al.add(t); t = st.nextToken(); if (t.equals(")")) break; assert (t.equals(",")); } int[] a = new int[al.size()]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(al.get(i)); } s = st.nextToken("{,}"); assert (s.equals("{")); s = st.nextToken(); int f = Integer.parseInt(s); s = st.nextToken(); int l = Integer.parseInt(s); s = st.nextToken(); int e = Integer.parseInt(s); s = st.nextToken(); assert (s.equals("}")); Key k = new Key(f, l, e); assert (!st.hasMoreTokens()); return new MethodDescriptor(r, c, n, a, k); } public String toPrettyString(LineNumberMap map) { return toPrettyString(map, true); } public String toPrettyString(LineNumberMap map, boolean includeReturnType) { StringBuilder res = new StringBuilder(); if (includeReturnType) res.append(map.lookupString(returnType)).append(" "); res.append(map.lookupString(container)).append("::"); res.append(map.lookupString(name)).append("("); boolean first = true; for (int arg : args) { if (!first) res.append(","); first = false; res.append(map.lookupString(arg)); } res.append(")"); return res.toString(); } } private final HashMap<MethodDescriptor, MethodDescriptor> methods; /** */ public LineNumberMap() { this(new ArrayList<String>()); } private LineNumberMap(ArrayList<String> strings) { super(strings); this.map = new HashMap<Key, Entry>(); this.methods = new HashMap<MethodDescriptor, MethodDescriptor>(); } /** * @param cppFile C++ filename * @param startLine C++ start line number * @param endLine C++ end line number * @param sourceFile X10 filename * @param sourceLine X10 line number */ public void put(String cppFile, int startLine, int endLine, String sourceFile, int sourceLine, int sourceColumn) { map.put(new Key(stringId(cppFile), startLine, endLine), new Entry(stringId(sourceFile), sourceLine, sourceColumn)); } private MethodDescriptor createMethodDescriptor(String container, String name, String returnType, String[] args, Key l) { int c = stringId(container); int n = stringId(name); int r = stringId(returnType); int[] a = new int[args.length]; for (int i = 0; i < a.length; i++) { a[i] = stringId(args[i]); } return new MethodDescriptor(r, c, n, a, l); } /** * @param def X10 method or constructor signature * @param cppFile generated file containing the method body * @param startLine first generated line of the method body * @param endLine last generated line of the method body */ public void addMethodMapping(MemberDef def, String cppFile, int startLine, int endLine, int lastX10Line) { Key tk = new Key(stringId(cppFile), startLine, endLine); Type container = def.container().get(); assert (def instanceof ProcedureDef); String name = (def instanceof MethodDef) ? ((MethodDef) def).name().toString() : null; Type returnType = (def instanceof MethodDef) ? ((MethodDef) def).returnType().get() : null; List<Ref<? extends Type>> formalTypes = ((ProcedureDef) def).formalTypes(); addMethodMapping(container, name, returnType, formalTypes, tk, lastX10Line); } private void addMethodMapping(Type c, String n, Type r, List<Ref<? extends Type>> f, Key tk, int lastX10Line) { assert (c != null); assert (f != null); String sc = c.toString(); String sn = n == null ? "this" : n; String sr = r == null ? "" : r.toString(); String[] sa = new String[f.size()]; for (int i = 0; i < sa.length; i++) { sa[i] = f.get(i).get().toString(); } MethodDescriptor src = createMethodDescriptor(sc, sn, sr, sa, new Key(-1, -1, lastX10Line)); String tc = Emitter.translateType(c); String tn = n == null ? "_constructor" : Emitter.mangled_method_name(n); String tr = r == null ? "void" : Emitter.translateType(r, true); String[] ta = new String[sa.length]; for (int i = 0; i < ta.length; i++) { ta[i] = Emitter.translateType(f.get(i).get(), true); } MethodDescriptor tgt = createMethodDescriptor(tc, tn, tr, ta, tk); // TODO: This line below causes the X10 standard library to fail to compile with the -DEBUG flag. Why? // assert (methods.get(tgt) == null); methods.put(tgt, src); } private class LocalVariableMapInfo { int _x10name; // Index of the X10 variable name in _X10strings int _x10type; // Classification of this type int _x10typeIndex; // Index of the X10 type into appropriate _X10ClassMap, _X10ClosureMap (if applicable) int _cppName; // Index of the C++ variable name in _X10strings String _x10index; // Index of X10 file name in _X10sourceList int _x10startLine; // First line number of X10 line range int _x10endLine; // Last line number of X10 line range } private class MemberVariableMapInfo { int _x10type; // Classification of this type int _x10typeIndex; // Index of the X10 type into appropriate _X10typeMap int _x10memberName; // Index of the X10 member name in _X10strings int _cppMemberName; // Index of the C++ member name in _X10strings int _cppClass; // Index of the C++ containing struct/class name in _X10strings } private static ArrayList<Integer> arrayMap = new ArrayList<Integer>(); private static ArrayList<Integer> refMap = new ArrayList<Integer>(); private static ArrayList<LocalVariableMapInfo> localVariables; private static Hashtable<String, ArrayList<MemberVariableMapInfo>> memberVariables; private static Hashtable<String, ArrayList<MemberVariableMapInfo>> closureMembers; // the type numbers were provided by Steve Cooper in "x10dbg_types.h" static int determineTypeId(String type) { //System.out.println("looking up type \""+type+"\""); if (type.equals("x10.lang.Int") || type.startsWith("x10.lang.Int{")) return 6; if (type.startsWith("x10.array.Array")) return 200; if (type.startsWith("x10.lang.PlaceLocalHandle")) return 203; if (type.equals("x10.lang.Boolean") || type.startsWith("x10.lang.Boolean{")) return 1; if (type.equals("x10.lang.Byte") || type.startsWith("x10.lang.Byte{")) return 2; if (type.equals("x10.lang.Char") || type.startsWith("x10.lang.Char{")) return 3; if (type.equals("x10.lang.Double") || type.startsWith("x10.lang.Double{")) return 4; if (type.equals("x10.lang.Float") || type.startsWith("x10.lang.Float{")) return 5; if (type.equals("x10.lang.Long") || type.startsWith("x10.lang.Long{")) return 7; if (type.equals("x10.lang.Short") || type.startsWith("x10.lang.Short{")) return 8; if (type.equals("x10.lang.UByte") || type.startsWith("x10.lang.UByte{")) return 9; if (type.equals("x10.lang.UInt") || type.startsWith("x10.lang.UInt{")) return 10; if (type.equals("x10.lang.ULong") || type.startsWith("x10.lang.ULong{")) return 11; if (type.equals("x10.lang.UShort") || type.startsWith("x10.lang.UShort{")) return 12; if (type.startsWith("x10.array.DistArray")) return 202; if (type.startsWith("x10.array.Dist")) return 201; if (type.startsWith("x10.lang.Rail")) return 204; if (type.startsWith("x10.util.Random")) return 205; if (type.startsWith("x10.lang.String")) return 206; if (type.startsWith("x10.array.Point")) return 208; if (type.startsWith("x10.array.Region")) return 300; return 101; // generic class } static int determineSubtypeId(String type, ArrayList<Integer> list) { int bracketStart = type.indexOf('['); int bracketEnd = type.lastIndexOf(']'); if (bracketStart != -1 && bracketEnd != -1) { String subtype = type.substring(bracketStart+1, bracketEnd); int subtypeId = determineTypeId(subtype); int position = list.size(); list.add(subtypeId); list.add(determineSubtypeId(subtype, list)); return position/2; } else return -1; } public void addLocalVariableMapping(String name, String type, int startline, int endline, String file, boolean noMangle) { if (name == null || name.startsWith(Context.MAGIC_VAR_PREFIX)) return; // skip variables with compiler-generated names. if (localVariables == null) localVariables = new ArrayList<LineNumberMap.LocalVariableMapInfo>(); LocalVariableMapInfo v = new LocalVariableMapInfo(); v._x10name = stringId(name); v._x10type = determineTypeId(type); if (v._x10type == 203) v._x10typeIndex = determineSubtypeId(type, refMap); else if (v._x10type == 200 || v._x10type == 202 || v._x10type == 204 || v._x10type == 207) v._x10typeIndex = determineSubtypeId(type, arrayMap); else if (v._x10type == 101) { int b = type.indexOf('{'); if (b == -1) v._x10typeIndex = stringId(Emitter.mangled_non_method_name(type)); else v._x10typeIndex = stringId(Emitter.mangled_non_method_name(type.substring(0, b))); } else v._x10typeIndex = -1; if (noMangle) v._cppName = v._x10name; else v._cppName = stringId(Emitter.mangled_non_method_name(name)); v._x10index = file; v._x10startLine = startline; v._x10endLine = endline; localVariables.add(v); } public void addClassMemberVariable(String name, String type, String containingClass) { if (memberVariables == null) memberVariables = new Hashtable<String, ArrayList<LineNumberMap.MemberVariableMapInfo>>(); ArrayList<MemberVariableMapInfo> members = memberVariables.get(containingClass); if (members == null) { members = new ArrayList<LineNumberMap.MemberVariableMapInfo>(); memberVariables.put(containingClass, members); } MemberVariableMapInfo v = new MemberVariableMapInfo(); v._x10type = determineTypeId(type); if (v._x10type == 203) v._x10typeIndex = determineSubtypeId(type, refMap); else if (v._x10type == 200 || v._x10type == 202 || v._x10type == 204 || v._x10type == 207) v._x10typeIndex = determineSubtypeId(type, arrayMap); else v._x10typeIndex = -1; v._x10memberName = stringId(name); v._cppMemberName = stringId("x10__"+Emitter.mangled_non_method_name(name)); v._cppClass = stringId(containingClass); members.add(v); } public void addClosureMember(String name, String type, String containingClass) { if (closureMembers == null) closureMembers = new Hashtable<String, ArrayList<LineNumberMap.MemberVariableMapInfo>>(); ArrayList<MemberVariableMapInfo> members = closureMembers.get(containingClass); if (members == null) { members = new ArrayList<LineNumberMap.MemberVariableMapInfo>(); closureMembers.put(containingClass, members); } MemberVariableMapInfo v = new MemberVariableMapInfo(); v._x10type = determineTypeId(type); if (v._x10type == 203) v._x10typeIndex = determineSubtypeId(type, refMap); else if (v._x10type == 200 || v._x10type == 202 || v._x10type == 204 || v._x10type == 207) v._x10typeIndex = determineSubtypeId(type, arrayMap); else v._x10typeIndex = -1; v._x10memberName = stringId(name); v._cppMemberName = stringId("x10__"+Emitter.mangled_non_method_name(name)); v._cppClass = stringId(containingClass); members.add(v); } /** * @param method target method signature * @return source method signature */ public String getMappedMethod(String method) { for (MethodDescriptor m : methods.keySet()) { String mm = m.toPrettyString(this, false); if (mm.equals(method)) return methods.get(m).toPrettyString(this, false); } return null; } public String toString() { final StringBuilder sb = new StringBuilder(); for (Key pos : map.keySet()) { Entry entry = map.get(pos); sb.append(lookupString(pos.fileId)).append(":").append(pos.start_line).append("->"); sb.append(lookupString(entry.fileId)).append(":").append(entry.line).append("\n"); } sb.append("\n"); for (MethodDescriptor md : methods.keySet()) { MethodDescriptor sm = methods.get(md); sb.append(md.toPrettyString(this, true)).append("->"); sb.append(sm.toPrettyString(this, true)).append("\n"); } return sb.toString(); } /** * Is the map empty? * @return true if the map is empty. */ public boolean isEmpty() { return map.isEmpty(); } /** * Produces a string suitable for initializing a field in the generated file. * The resulting string can be parsed by {@link #importMap(String)}. */ public String exportMap() { final StringBuilder sb = new StringBuilder(); sb.append("F"); exportStringMap(sb); sb.append(" L{"); for (Key pos : map.keySet()) { Entry entry = map.get(pos); sb.append(pos.fileId).append(":"); sb.append(pos.start_line).append("-").append(pos.end_line).append("->"); sb.append(entry.fileId).append(":").append(entry.line).append(","); } sb.append("} M{"); for (MethodDescriptor md : methods.keySet()) { MethodDescriptor sm = methods.get(md); sb.append(md.toString()).append("->").append(sm.toString()).append(";"); } sb.append("}"); return sb.toString(); } /** * Parses a string into a {@link LineNumberMap}. * The string is produced by {@link #exportMap()}. * @param input the input string */ public static LineNumberMap importMap(String input) { StringTokenizer st = new QuotedStringTokenizer(input, " ", "\"\'", '\\', true); String s = st.nextToken("{}"); assert (s.equals("F")); ArrayList<String> strings = importStringMap(st); LineNumberMap res = new LineNumberMap(strings); if (!st.hasMoreTokens()) return res; s = st.nextToken("{}"); assert (s.equals(" L")); s = st.nextToken(); assert (s.equals("{")); while (st.hasMoreTokens()) { String t = st.nextToken(":}"); if (t.equals("}")) break; int n = Integer.parseInt(t); t = st.nextToken(); assert (t.equals(":")); int i = Integer.parseInt(st.nextToken("-")); t = st.nextToken(); assert (t.equals("-")); int e = Integer.parseInt(st.nextToken("-")); t = st.nextToken(">"); assert (t.equals("-")); t = st.nextToken(">"); assert (t.equals(">")); int f = Integer.parseInt(st.nextToken(":")); t = st.nextToken(); assert (t.equals(":")); int l = Integer.parseInt(st.nextToken(",")); res.map.put(new Key(n, i, e), new Entry(f, l, -1)); t = st.nextToken(); assert (t.equals(",")); } if (!st.hasMoreTokens()) return res; s = st.nextToken("{}"); assert (s.equals(" M")); s = st.nextToken(); assert (s.equals("{")); while (st.hasMoreTokens()) { String t = st.nextToken("-}"); if (t.equals("}")) break; MethodDescriptor md = MethodDescriptor.parse(t); t = st.nextToken(">"); assert (t.equals("-")); t = st.nextToken(">"); assert (t.equals(">")); MethodDescriptor sm = MethodDescriptor.parse(st.nextToken(";")); res.methods.put(md, sm); t = st.nextToken(); assert (t.equals(";")); } assert (!st.hasMoreTokens()); return res; } /** * Merges a set of new entries into a given map. Changes the map in place! * @param map the target map (changed in place!) * @param newEntries the set of new entries */ private static void mergeMap(LineNumberMap map, LineNumberMap newEntries) { assert (map != null); final LineNumberMap m = map; final LineNumberMap n = newEntries; for (Key p : n.map.keySet()) { // assert (!m.map.containsKey(p)); Entry e = n.map.get(p); m.put(n.lookupString(p.fileId), p.start_line, p.end_line, n.lookupString(e.fileId), e.line, e.column); } for (MethodDescriptor d : n.methods.keySet()) { // if (m.methods.containsKey(d)) // assert (false) : d.toPrettyString(n)+" already present"; assert (!m.methods.containsKey(d)) : d.toPrettyString(n)+" already present"; MethodDescriptor e = n.methods.get(d); assert (e.lines == null); Key dk = new Key(m.stringId(n.lookupString(d.lines.fileId)), d.lines.start_line, d.lines.end_line); MethodDescriptor dp = m.createMethodDescriptor(n.lookupString(d.container), n.lookupString(d.name), n.lookupString(d.returnType), n.lookupStrings(d.args), dk); MethodDescriptor ep = m.createMethodDescriptor(n.lookupString(e.container), n.lookupString(e.name), n.lookupString(e.returnType), n.lookupStrings(e.args), null); m.methods.put(dp, ep); } } /** * Merges a set of maps into a new map. Returns the new map. * @param maps the set of maps to merge * @return the newly-created map containing merged entries from maps */ public static LineNumberMap mergeMaps(LineNumberMap[] maps) { LineNumberMap map = new LineNumberMap(); for (int i = 0; i < maps.length; i++) { mergeMap(map, maps[i]); } return map; } private String[] allFiles() { TreeSet<String> files = new TreeSet<String>(); for (Entry e : map.values()) { files.add(lookupString(e.fileId)); } return files.toArray(new String[files.size()]); } private static int findFile(String name, String[] files) { // files is assumed sorted alphanumerically return Arrays.binarySearch(files, name); } private static class CPPLineInfo { public final int x10index; public final int x10method; public final int cppindex; public final int x10line; public final int x10column; public final int cppfromline; public final int cpptoline; public final int fileId; public CPPLineInfo(int x10index, int x10method, int cppindex, int x10line, int cppfromline, int cpptoline, int fileId, int x10column) { this.x10index = x10index; this.x10method = x10method; this.cppindex = cppindex; this.x10line = x10line; this.x10column = x10column; this.cppfromline = cppfromline; this.cpptoline = cpptoline; this.fileId = fileId; } public static Comparator<CPPLineInfo> byX10info() { return new Comparator<CPPLineInfo>() { public int compare(CPPLineInfo o1, CPPLineInfo o2) { int index_d = o1.x10index - o2.x10index; if (index_d != 0) return index_d; return o1.x10line - o2.x10line; } }; } public static Comparator<CPPLineInfo> byCPPinfo() { return new Comparator<CPPLineInfo>() { public int compare(CPPLineInfo o1, CPPLineInfo o2) { int index_d = o1.cppindex - o2.cppindex; if (index_d != 0) return index_d; return o1.cppfromline - o2.cppfromline; } }; } } private class CPPMethodInfo implements Comparable<CPPMethodInfo> { public final int x10class; public final int x10method; public final int x10rettype; public final int[] x10args; public final int cppclass; public int cpplineindex; public int lastX10Line; public CPPMethodInfo(int x10class, int x10method, int x10rettype, int[] x10args, int cppclass, int lastX10Line) { this.x10class = x10class; this.x10method = x10method; this.x10rettype = x10rettype; this.x10args = x10args; this.cppclass = cppclass; this.lastX10Line = lastX10Line; } private String concatArgs() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < x10args.length; i++) { sb.append(lookupString(x10args[i])); } return sb.toString(); } public int compareTo(CPPMethodInfo o) { int class_d = lookupString(x10class).compareTo(lookupString(o.x10class)); if (class_d != 0) return class_d; int name_d = lookupString(x10method).compareTo(lookupString(o.x10method)); if (name_d != 0) return name_d; return concatArgs().compareTo(o.concatArgs()); } } /** * Generates code for the line number map as required by the Toronto C++ * Debugger backend into the specified stream. * @param w the output stream * @param m the map to export */ public static void exportForCPPDebugger(ClassifiedStream w, LineNumberMap m) { String debugSectionAttr = "__attribute__((_X10_DEBUG_SECTION))"; String debugDataSectionAttr = "__attribute__((_X10_DEBUG_DATA_SECTION))"; int size = m.size(); int offset = 0; int[] offsets = new int[size]; // All strings, concatenated, with intervening nulls. w.writeln("static const char _X10strings[] __attribute__((used)) "+debugDataSectionAttr+" ="); for (int i = 0; i < size; i++) { offsets[i] = offset; String s = m.lookupString(i); w.writeln(" \""+StringUtil.escape(s)+"\\0\" //"+offsets[i]); offset += s.length()+1; } w.writeln(" \"\";"); w.forceNewline(); if (!m.isEmpty()) { String[] files = m.allFiles(); // A list of X10 source files that contributed to the generation of the current C++ file. w.writeln("static const struct _X10sourceFile _X10sourceList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (int i = 0; i < files.length; i++) { w.write(" { "); w.write(""+0+", "); // FIXME: _numLines w.write(""+offsets[m.stringId(files[i])]); // _stringIndex w.writeln(" },"); } w.writeln("};"); w.forceNewline(); // // A cross reference of X10 statements to the first C++ statement. // // Sorted by X10 file index and X10 source file line. ArrayList<CPPLineInfo> x10toCPPlist = new ArrayList<CPPLineInfo>(m.map.size()); for (Key p : m.map.keySet()) { Entry e = m.map.get(p); x10toCPPlist.add( new CPPLineInfo(findFile(m.lookupString(e.fileId), files), // _X10index 0, // FIXME: _X10method offsets[p.fileId], // _CPPindex e.line, // _X10line p.start_line, // _CPPline p.end_line, p.fileId, e.column)); // _X10column } Collections.sort(x10toCPPlist, CPPLineInfo.byX10info()); // remove itens that have duplicate lines, leaving only the one with the earlier column int previousLine=-1, previousColumn=-1; for (int i=0; i<x10toCPPlist.size();) { CPPLineInfo cppDebugInfo = x10toCPPlist.get(i); if (cppDebugInfo.x10line == previousLine) { if (cppDebugInfo.x10column >= previousColumn) x10toCPPlist.remove(i); // keep the previous one, delete this one else { // keep this one, delete the previous one x10toCPPlist.remove(i-1); previousLine = cppDebugInfo.x10line; previousColumn = cppDebugInfo.x10column; } } else { previousLine = cppDebugInfo.x10line; previousColumn = cppDebugInfo.x10column; i++; } } w.writeln("static const struct _X10toCPPxref _X10toCPPlist[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (CPPLineInfo cppDebugInfo : x10toCPPlist) { w.write(" { "); w.write(""+cppDebugInfo.x10index+", "); // _X10index // w.write(""+cppDebugInfo.x10method+", "); // _X10method w.write(""+cppDebugInfo.cppindex+", "); // _CPPindex w.write(""+cppDebugInfo.x10line+", "); // _X10line w.write(""+cppDebugInfo.cppfromline+", "); // _CPPFromLine w.write(""+cppDebugInfo.cpptoline); // _CPPtoLine w.writeln(" },"); } w.writeln("};"); w.forceNewline(); // A list of the X10 method names. // Sorted by X10 method name. ArrayList<CPPMethodInfo> x10MethodList = new ArrayList<CPPMethodInfo>(m.methods.size()); HashMap<Key, CPPMethodInfo> keyToMethod = new HashMap<Key, CPPMethodInfo>(); for (MethodDescriptor md : m.methods.keySet()) { MethodDescriptor sm = m.methods.get(md); final CPPMethodInfo cmi = m.new CPPMethodInfo(sm.container, // _x10class sm.name, // _x10method sm.returnType, // _x10returnType sm.args, // _x10args md.container, // _cppClass sm.lines.end_line); // _lastX10Line x10MethodList.add(cmi); keyToMethod.put(md.lines, cmi); } // A cross reference of C++ statements to X10 statements. // Sorted by C++ file index and C++ source file line. // A line range is used to minimize the storage required. ArrayList<CPPLineInfo> cpptoX10xrefList = new ArrayList<CPPLineInfo>(m.map.size()); for (Key p : m.map.keySet()) { Entry e = m.map.get(p); cpptoX10xrefList.add( new CPPLineInfo(findFile(m.lookupString(e.fileId), files), // _X10index 0, // FIXME: _X10method offsets[p.fileId], // _CPPindex e.line, // _X10line p.start_line, // _CPPfromline p.end_line, // _CPPtoline p.fileId, e.column)); } Collections.sort(cpptoX10xrefList, CPPLineInfo.byCPPinfo()); w.writeln("static const struct _CPPtoX10xref _CPPtoX10xrefList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); int i = 0; for (CPPLineInfo cppDebugInfo : cpptoX10xrefList) { w.write(" { "); w.write(""+cppDebugInfo.x10index+", "); // _X10index // w.write(""+cppDebugInfo.x10method+", "); // _X10method w.write(""+cppDebugInfo.cppindex+", "); // _CPPindex w.write(""+cppDebugInfo.x10line+", "); // _X10line w.write(""+cppDebugInfo.cppfromline+", "); // _CPPfromline w.write(""+cppDebugInfo.cpptoline); // _CPPtoline w.writeln(" },"); Key k = new Key(cppDebugInfo.fileId, cppDebugInfo.cppfromline, cppDebugInfo.cpptoline); CPPMethodInfo methodInfo = keyToMethod.get(k); if (methodInfo != null) { methodInfo.cpplineindex = i; // _lineIndex } i++; } w.writeln("};"); w.forceNewline(); if (!m.methods.isEmpty()) { Collections.sort(x10MethodList); // FIXME: Cannot put _X10methodNameList in debugDataSectionAttr, because it's not constant // (the strings cause static initialization for some reason) w.writeln("static const struct _X10methodName _X10methodNameList[] __attribute__((used)) = {"); w.writeln("#if defined(__xlC__)"); for (CPPMethodInfo cppMethodInfo : x10MethodList) { w.write(" { "); w.write(""+offsets[cppMethodInfo.x10class]+", "); // _x10class w.write(""+offsets[cppMethodInfo.x10method]+", "); // _x10method w.write(""+offsets[cppMethodInfo.x10rettype]+", "); // _x10returnType w.write(""+offsets[cppMethodInfo.cppclass]+", "); // _cppClass w.write("(uint64_t) 0, "); // TODO - this needs to be re-designed, with the debugger team w.write(""+cppMethodInfo.x10args.length+", "); // _x10argCount w.write(""+cppMethodInfo.cpplineindex+", "); // _lineIndex w.write(""+cppMethodInfo.lastX10Line); // _lastX10Line w.writeln(" },"); } w.writeln("#else"); for (CPPMethodInfo cppMethodInfo : x10MethodList) { w.write(" { "); w.write(""+offsets[cppMethodInfo.x10class]+", "); // _x10class w.write(""+offsets[cppMethodInfo.x10method]+", "); // _x10method w.write(""+offsets[cppMethodInfo.x10rettype]+", "); // _x10returnType w.write(""+offsets[cppMethodInfo.cppclass]+", "); // _cppClass w.write("(uint64_t) "); for (i = 0; i < cppMethodInfo.x10args.length; i++) { int a = cppMethodInfo.x10args[i]; w.write("\""+encodeIntAsChars(offsets[a])+"\" "); // _x10args } w.write("\"\", "); w.write(""+cppMethodInfo.x10args.length+", "); // _x10argCount w.write(""+cppMethodInfo.cpplineindex+", "); // _lineIndex w.write(""+cppMethodInfo.lastX10Line); // _lastX10Line w.writeln(" },"); } w.writeln("#endif"); w.writeln("};"); w.forceNewline(); } // variable map stuff if (localVariables != null) { w.writeln("static const struct _X10LocalVarMap _X10variableNameList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (LocalVariableMapInfo v : localVariables) w.writeln(" { "+offsets[v._x10name]+", "+v._x10type+", "+(v._x10type==101?offsets[v._x10typeIndex]:v._x10typeIndex)+", "+offsets[v._cppName]+", "+findFile(v._x10index, files)+", "+v._x10startLine+", "+v._x10endLine+" }, // "+m.lookupString(v._x10name)); w.writeln("};"); w.forceNewline(); } } if (memberVariables != null) { for (String classname : memberVariables.keySet()) { w.writeln("static const struct _X10TypeMember _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (MemberVariableMapInfo v : memberVariables.get(classname)) w.writeln(" { "+v._x10type+", "+v._x10typeIndex+", "+offsets[v._x10memberName]+", "+offsets[v._cppMemberName]+", "+offsets[v._cppClass]+" }, // "+m.lookupString(v._x10memberName)); w.writeln("};"); w.forceNewline(); } w.writeln("static const struct _X10ClassMap _X10ClassMapList[] __attribute__((used)) = {"); for (String classname : memberVariables.keySet()) w.writeln(" { 101, "+offsets[memberVariables.get(classname).get(0)._cppClass]+", sizeof("+classname.replace(".", "::")+"), "+memberVariables.get(classname).size()+", _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members },"); w.writeln("};"); w.forceNewline(); } if (closureMembers != null) { for (String classname : closureMembers.keySet()) { w.writeln("static const struct _X10TypeMember _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (MemberVariableMapInfo v : closureMembers.get(classname)) w.writeln(" { "+v._x10type+", "+v._x10typeIndex+", "+offsets[v._x10memberName]+", "+offsets[v._cppMemberName]+", "+offsets[v._cppClass]+" }, // "+m.lookupString(v._x10memberName)); w.writeln("};"); w.forceNewline(); } - w.writeln("static const struct _X10ClosureMap _X10ClosureMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); + w.writeln("static const struct _X10ClosureMap _X10ClosureMapList[] __attribute__((used)) = {"); // inclusion of debugDataSectionAttr causes issues on Macos. See XTENLANG-2318. for (String classname : closureMembers.keySet()) w.writeln(" { 100, "+offsets[closureMembers.get(classname).get(0)._cppClass]+", sizeof("+classname.replace(".", "::")+"), "+closureMembers.get(classname).size()+", 0, 0, 0, _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members },"); w.writeln("};"); w.forceNewline(); } if (!arrayMap.isEmpty()) { w.writeln("static const struct _X10ArrayMap _X10ArrayMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); Iterator<Integer> iterator = arrayMap.iterator(); while(iterator.hasNext()) w.writeln(" { "+iterator.next()+", "+iterator.next()+" },"); w.writeln("};"); w.forceNewline(); } if (!refMap.isEmpty()) { w.writeln("static const struct _X10RefMap _X10RefMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); Iterator<Integer> iterator = refMap.iterator(); while(iterator.hasNext()) w.writeln(" { "+iterator.next()+", "+iterator.next()+" },"); w.writeln("};"); w.forceNewline(); } // A meta-structure that refers to all of the above w.write("static const struct _MetaDebugInfo_t _MetaDebugInfo __attribute__((used)) "+debugSectionAttr+" = {"); w.newline(4); w.begin(0); w.writeln("sizeof(struct _MetaDebugInfo_t),"); w.writeln("X10_META_LANG,"); w.writeln("0,"); w.writeln("sizeof(_X10strings),"); if (!m.isEmpty()) { w.writeln("sizeof(_X10sourceList),"); w.writeln("sizeof(_X10toCPPlist),"); // w.writeln("0,"); w.writeln("sizeof(_CPPtoX10xrefList),"); } else { w.writeln("0,"); w.writeln("0,"); w.writeln("0,"); } if (!m.methods.isEmpty()) { w.writeln("sizeof(_X10methodNameList),"); } else { w.writeln("0, // no member variable mappings"); } if (!m.isEmpty() && localVariables != null) w.writeln("sizeof(_X10variableNameList),"); else w.writeln("0, // no local variable mappings"); if (memberVariables != null) w.writeln("sizeof(_X10ClassMapList),"); else w.writeln("0, // no class mappings"); if (closureMembers != null) w.writeln("sizeof(_X10ClosureMapList),"); else w.writeln("0, // no closure mappings"); if (!arrayMap.isEmpty()) w.writeln("sizeof(_X10ArrayMapList),"); else w.writeln("0, // no array mappings"); if (!refMap.isEmpty()) w.writeln("sizeof(_X10RefMapList),"); else w.writeln("0, // no reference mappings"); w.writeln("_X10strings,"); if (!m.isEmpty()) { w.writeln("_X10sourceList,"); w.writeln("_X10toCPPlist,"); // w.writeln("NULL,"); w.writeln("_CPPtoX10xrefList,"); } else { w.writeln("NULL,"); w.writeln("NULL,"); w.writeln("NULL,"); } if (!m.methods.isEmpty()) { w.writeln("_X10methodNameList,"); m.methods.clear(); } else { w.writeln("NULL,"); } if (localVariables != null) { if (!m.isEmpty()) w.writeln("_X10variableNameList,"); else w.writeln("NULL,"); localVariables.clear(); localVariables = null; } else w.writeln("NULL,"); if (memberVariables != null) { w.writeln("_X10ClassMapList,"); memberVariables.clear(); memberVariables = null; } else w.writeln("NULL,"); if (closureMembers != null) { w.writeln("_X10ClosureMapList,"); closureMembers.clear(); closureMembers = null; } else w.writeln("NULL,"); if (!arrayMap.isEmpty()) { arrayMap.clear(); w.writeln("_X10ArrayMapList,"); } else w.writeln("NULL,"); if (!refMap.isEmpty()) { refMap.clear(); w.write("_X10RefMapList"); } else w.write("NULL"); w.end(); w.newline(); w.writeln("};"); } private static String encodeIntAsChars(int i) { String b1 = "\\"+Integer.toOctalString((i >> 24) & 0xFF); String b2 = "\\"+Integer.toOctalString((i >> 16) & 0xFF); String b3 = "\\"+Integer.toOctalString((i >> 8) & 0xFF); String b4 = "\\"+Integer.toOctalString((i >> 0) & 0xFF); return b1+b2+b3+b4; } }
true
true
public static void exportForCPPDebugger(ClassifiedStream w, LineNumberMap m) { String debugSectionAttr = "__attribute__((_X10_DEBUG_SECTION))"; String debugDataSectionAttr = "__attribute__((_X10_DEBUG_DATA_SECTION))"; int size = m.size(); int offset = 0; int[] offsets = new int[size]; // All strings, concatenated, with intervening nulls. w.writeln("static const char _X10strings[] __attribute__((used)) "+debugDataSectionAttr+" ="); for (int i = 0; i < size; i++) { offsets[i] = offset; String s = m.lookupString(i); w.writeln(" \""+StringUtil.escape(s)+"\\0\" //"+offsets[i]); offset += s.length()+1; } w.writeln(" \"\";"); w.forceNewline(); if (!m.isEmpty()) { String[] files = m.allFiles(); // A list of X10 source files that contributed to the generation of the current C++ file. w.writeln("static const struct _X10sourceFile _X10sourceList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (int i = 0; i < files.length; i++) { w.write(" { "); w.write(""+0+", "); // FIXME: _numLines w.write(""+offsets[m.stringId(files[i])]); // _stringIndex w.writeln(" },"); } w.writeln("};"); w.forceNewline(); // // A cross reference of X10 statements to the first C++ statement. // // Sorted by X10 file index and X10 source file line. ArrayList<CPPLineInfo> x10toCPPlist = new ArrayList<CPPLineInfo>(m.map.size()); for (Key p : m.map.keySet()) { Entry e = m.map.get(p); x10toCPPlist.add( new CPPLineInfo(findFile(m.lookupString(e.fileId), files), // _X10index 0, // FIXME: _X10method offsets[p.fileId], // _CPPindex e.line, // _X10line p.start_line, // _CPPline p.end_line, p.fileId, e.column)); // _X10column } Collections.sort(x10toCPPlist, CPPLineInfo.byX10info()); // remove itens that have duplicate lines, leaving only the one with the earlier column int previousLine=-1, previousColumn=-1; for (int i=0; i<x10toCPPlist.size();) { CPPLineInfo cppDebugInfo = x10toCPPlist.get(i); if (cppDebugInfo.x10line == previousLine) { if (cppDebugInfo.x10column >= previousColumn) x10toCPPlist.remove(i); // keep the previous one, delete this one else { // keep this one, delete the previous one x10toCPPlist.remove(i-1); previousLine = cppDebugInfo.x10line; previousColumn = cppDebugInfo.x10column; } } else { previousLine = cppDebugInfo.x10line; previousColumn = cppDebugInfo.x10column; i++; } } w.writeln("static const struct _X10toCPPxref _X10toCPPlist[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (CPPLineInfo cppDebugInfo : x10toCPPlist) { w.write(" { "); w.write(""+cppDebugInfo.x10index+", "); // _X10index // w.write(""+cppDebugInfo.x10method+", "); // _X10method w.write(""+cppDebugInfo.cppindex+", "); // _CPPindex w.write(""+cppDebugInfo.x10line+", "); // _X10line w.write(""+cppDebugInfo.cppfromline+", "); // _CPPFromLine w.write(""+cppDebugInfo.cpptoline); // _CPPtoLine w.writeln(" },"); } w.writeln("};"); w.forceNewline(); // A list of the X10 method names. // Sorted by X10 method name. ArrayList<CPPMethodInfo> x10MethodList = new ArrayList<CPPMethodInfo>(m.methods.size()); HashMap<Key, CPPMethodInfo> keyToMethod = new HashMap<Key, CPPMethodInfo>(); for (MethodDescriptor md : m.methods.keySet()) { MethodDescriptor sm = m.methods.get(md); final CPPMethodInfo cmi = m.new CPPMethodInfo(sm.container, // _x10class sm.name, // _x10method sm.returnType, // _x10returnType sm.args, // _x10args md.container, // _cppClass sm.lines.end_line); // _lastX10Line x10MethodList.add(cmi); keyToMethod.put(md.lines, cmi); } // A cross reference of C++ statements to X10 statements. // Sorted by C++ file index and C++ source file line. // A line range is used to minimize the storage required. ArrayList<CPPLineInfo> cpptoX10xrefList = new ArrayList<CPPLineInfo>(m.map.size()); for (Key p : m.map.keySet()) { Entry e = m.map.get(p); cpptoX10xrefList.add( new CPPLineInfo(findFile(m.lookupString(e.fileId), files), // _X10index 0, // FIXME: _X10method offsets[p.fileId], // _CPPindex e.line, // _X10line p.start_line, // _CPPfromline p.end_line, // _CPPtoline p.fileId, e.column)); } Collections.sort(cpptoX10xrefList, CPPLineInfo.byCPPinfo()); w.writeln("static const struct _CPPtoX10xref _CPPtoX10xrefList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); int i = 0; for (CPPLineInfo cppDebugInfo : cpptoX10xrefList) { w.write(" { "); w.write(""+cppDebugInfo.x10index+", "); // _X10index // w.write(""+cppDebugInfo.x10method+", "); // _X10method w.write(""+cppDebugInfo.cppindex+", "); // _CPPindex w.write(""+cppDebugInfo.x10line+", "); // _X10line w.write(""+cppDebugInfo.cppfromline+", "); // _CPPfromline w.write(""+cppDebugInfo.cpptoline); // _CPPtoline w.writeln(" },"); Key k = new Key(cppDebugInfo.fileId, cppDebugInfo.cppfromline, cppDebugInfo.cpptoline); CPPMethodInfo methodInfo = keyToMethod.get(k); if (methodInfo != null) { methodInfo.cpplineindex = i; // _lineIndex } i++; } w.writeln("};"); w.forceNewline(); if (!m.methods.isEmpty()) { Collections.sort(x10MethodList); // FIXME: Cannot put _X10methodNameList in debugDataSectionAttr, because it's not constant // (the strings cause static initialization for some reason) w.writeln("static const struct _X10methodName _X10methodNameList[] __attribute__((used)) = {"); w.writeln("#if defined(__xlC__)"); for (CPPMethodInfo cppMethodInfo : x10MethodList) { w.write(" { "); w.write(""+offsets[cppMethodInfo.x10class]+", "); // _x10class w.write(""+offsets[cppMethodInfo.x10method]+", "); // _x10method w.write(""+offsets[cppMethodInfo.x10rettype]+", "); // _x10returnType w.write(""+offsets[cppMethodInfo.cppclass]+", "); // _cppClass w.write("(uint64_t) 0, "); // TODO - this needs to be re-designed, with the debugger team w.write(""+cppMethodInfo.x10args.length+", "); // _x10argCount w.write(""+cppMethodInfo.cpplineindex+", "); // _lineIndex w.write(""+cppMethodInfo.lastX10Line); // _lastX10Line w.writeln(" },"); } w.writeln("#else"); for (CPPMethodInfo cppMethodInfo : x10MethodList) { w.write(" { "); w.write(""+offsets[cppMethodInfo.x10class]+", "); // _x10class w.write(""+offsets[cppMethodInfo.x10method]+", "); // _x10method w.write(""+offsets[cppMethodInfo.x10rettype]+", "); // _x10returnType w.write(""+offsets[cppMethodInfo.cppclass]+", "); // _cppClass w.write("(uint64_t) "); for (i = 0; i < cppMethodInfo.x10args.length; i++) { int a = cppMethodInfo.x10args[i]; w.write("\""+encodeIntAsChars(offsets[a])+"\" "); // _x10args } w.write("\"\", "); w.write(""+cppMethodInfo.x10args.length+", "); // _x10argCount w.write(""+cppMethodInfo.cpplineindex+", "); // _lineIndex w.write(""+cppMethodInfo.lastX10Line); // _lastX10Line w.writeln(" },"); } w.writeln("#endif"); w.writeln("};"); w.forceNewline(); } // variable map stuff if (localVariables != null) { w.writeln("static const struct _X10LocalVarMap _X10variableNameList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (LocalVariableMapInfo v : localVariables) w.writeln(" { "+offsets[v._x10name]+", "+v._x10type+", "+(v._x10type==101?offsets[v._x10typeIndex]:v._x10typeIndex)+", "+offsets[v._cppName]+", "+findFile(v._x10index, files)+", "+v._x10startLine+", "+v._x10endLine+" }, // "+m.lookupString(v._x10name)); w.writeln("};"); w.forceNewline(); } } if (memberVariables != null) { for (String classname : memberVariables.keySet()) { w.writeln("static const struct _X10TypeMember _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (MemberVariableMapInfo v : memberVariables.get(classname)) w.writeln(" { "+v._x10type+", "+v._x10typeIndex+", "+offsets[v._x10memberName]+", "+offsets[v._cppMemberName]+", "+offsets[v._cppClass]+" }, // "+m.lookupString(v._x10memberName)); w.writeln("};"); w.forceNewline(); } w.writeln("static const struct _X10ClassMap _X10ClassMapList[] __attribute__((used)) = {"); for (String classname : memberVariables.keySet()) w.writeln(" { 101, "+offsets[memberVariables.get(classname).get(0)._cppClass]+", sizeof("+classname.replace(".", "::")+"), "+memberVariables.get(classname).size()+", _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members },"); w.writeln("};"); w.forceNewline(); } if (closureMembers != null) { for (String classname : closureMembers.keySet()) { w.writeln("static const struct _X10TypeMember _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (MemberVariableMapInfo v : closureMembers.get(classname)) w.writeln(" { "+v._x10type+", "+v._x10typeIndex+", "+offsets[v._x10memberName]+", "+offsets[v._cppMemberName]+", "+offsets[v._cppClass]+" }, // "+m.lookupString(v._x10memberName)); w.writeln("};"); w.forceNewline(); } w.writeln("static const struct _X10ClosureMap _X10ClosureMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (String classname : closureMembers.keySet()) w.writeln(" { 100, "+offsets[closureMembers.get(classname).get(0)._cppClass]+", sizeof("+classname.replace(".", "::")+"), "+closureMembers.get(classname).size()+", 0, 0, 0, _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members },"); w.writeln("};"); w.forceNewline(); } if (!arrayMap.isEmpty()) { w.writeln("static const struct _X10ArrayMap _X10ArrayMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); Iterator<Integer> iterator = arrayMap.iterator(); while(iterator.hasNext()) w.writeln(" { "+iterator.next()+", "+iterator.next()+" },"); w.writeln("};"); w.forceNewline(); } if (!refMap.isEmpty()) { w.writeln("static const struct _X10RefMap _X10RefMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); Iterator<Integer> iterator = refMap.iterator(); while(iterator.hasNext()) w.writeln(" { "+iterator.next()+", "+iterator.next()+" },"); w.writeln("};"); w.forceNewline(); } // A meta-structure that refers to all of the above w.write("static const struct _MetaDebugInfo_t _MetaDebugInfo __attribute__((used)) "+debugSectionAttr+" = {"); w.newline(4); w.begin(0); w.writeln("sizeof(struct _MetaDebugInfo_t),"); w.writeln("X10_META_LANG,"); w.writeln("0,"); w.writeln("sizeof(_X10strings),"); if (!m.isEmpty()) { w.writeln("sizeof(_X10sourceList),"); w.writeln("sizeof(_X10toCPPlist),"); // w.writeln("0,"); w.writeln("sizeof(_CPPtoX10xrefList),"); } else { w.writeln("0,"); w.writeln("0,"); w.writeln("0,"); } if (!m.methods.isEmpty()) { w.writeln("sizeof(_X10methodNameList),"); } else { w.writeln("0, // no member variable mappings"); } if (!m.isEmpty() && localVariables != null) w.writeln("sizeof(_X10variableNameList),"); else w.writeln("0, // no local variable mappings"); if (memberVariables != null) w.writeln("sizeof(_X10ClassMapList),"); else w.writeln("0, // no class mappings"); if (closureMembers != null) w.writeln("sizeof(_X10ClosureMapList),"); else w.writeln("0, // no closure mappings"); if (!arrayMap.isEmpty()) w.writeln("sizeof(_X10ArrayMapList),"); else w.writeln("0, // no array mappings"); if (!refMap.isEmpty()) w.writeln("sizeof(_X10RefMapList),"); else w.writeln("0, // no reference mappings"); w.writeln("_X10strings,"); if (!m.isEmpty()) { w.writeln("_X10sourceList,"); w.writeln("_X10toCPPlist,"); // w.writeln("NULL,"); w.writeln("_CPPtoX10xrefList,"); } else { w.writeln("NULL,"); w.writeln("NULL,"); w.writeln("NULL,"); } if (!m.methods.isEmpty()) { w.writeln("_X10methodNameList,"); m.methods.clear(); } else { w.writeln("NULL,"); } if (localVariables != null) { if (!m.isEmpty()) w.writeln("_X10variableNameList,"); else w.writeln("NULL,"); localVariables.clear(); localVariables = null; } else w.writeln("NULL,"); if (memberVariables != null) { w.writeln("_X10ClassMapList,"); memberVariables.clear(); memberVariables = null; } else w.writeln("NULL,"); if (closureMembers != null) { w.writeln("_X10ClosureMapList,"); closureMembers.clear(); closureMembers = null; } else w.writeln("NULL,"); if (!arrayMap.isEmpty()) { arrayMap.clear(); w.writeln("_X10ArrayMapList,"); } else w.writeln("NULL,"); if (!refMap.isEmpty()) { refMap.clear(); w.write("_X10RefMapList"); } else w.write("NULL"); w.end(); w.newline(); w.writeln("};"); }
public static void exportForCPPDebugger(ClassifiedStream w, LineNumberMap m) { String debugSectionAttr = "__attribute__((_X10_DEBUG_SECTION))"; String debugDataSectionAttr = "__attribute__((_X10_DEBUG_DATA_SECTION))"; int size = m.size(); int offset = 0; int[] offsets = new int[size]; // All strings, concatenated, with intervening nulls. w.writeln("static const char _X10strings[] __attribute__((used)) "+debugDataSectionAttr+" ="); for (int i = 0; i < size; i++) { offsets[i] = offset; String s = m.lookupString(i); w.writeln(" \""+StringUtil.escape(s)+"\\0\" //"+offsets[i]); offset += s.length()+1; } w.writeln(" \"\";"); w.forceNewline(); if (!m.isEmpty()) { String[] files = m.allFiles(); // A list of X10 source files that contributed to the generation of the current C++ file. w.writeln("static const struct _X10sourceFile _X10sourceList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (int i = 0; i < files.length; i++) { w.write(" { "); w.write(""+0+", "); // FIXME: _numLines w.write(""+offsets[m.stringId(files[i])]); // _stringIndex w.writeln(" },"); } w.writeln("};"); w.forceNewline(); // // A cross reference of X10 statements to the first C++ statement. // // Sorted by X10 file index and X10 source file line. ArrayList<CPPLineInfo> x10toCPPlist = new ArrayList<CPPLineInfo>(m.map.size()); for (Key p : m.map.keySet()) { Entry e = m.map.get(p); x10toCPPlist.add( new CPPLineInfo(findFile(m.lookupString(e.fileId), files), // _X10index 0, // FIXME: _X10method offsets[p.fileId], // _CPPindex e.line, // _X10line p.start_line, // _CPPline p.end_line, p.fileId, e.column)); // _X10column } Collections.sort(x10toCPPlist, CPPLineInfo.byX10info()); // remove itens that have duplicate lines, leaving only the one with the earlier column int previousLine=-1, previousColumn=-1; for (int i=0; i<x10toCPPlist.size();) { CPPLineInfo cppDebugInfo = x10toCPPlist.get(i); if (cppDebugInfo.x10line == previousLine) { if (cppDebugInfo.x10column >= previousColumn) x10toCPPlist.remove(i); // keep the previous one, delete this one else { // keep this one, delete the previous one x10toCPPlist.remove(i-1); previousLine = cppDebugInfo.x10line; previousColumn = cppDebugInfo.x10column; } } else { previousLine = cppDebugInfo.x10line; previousColumn = cppDebugInfo.x10column; i++; } } w.writeln("static const struct _X10toCPPxref _X10toCPPlist[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (CPPLineInfo cppDebugInfo : x10toCPPlist) { w.write(" { "); w.write(""+cppDebugInfo.x10index+", "); // _X10index // w.write(""+cppDebugInfo.x10method+", "); // _X10method w.write(""+cppDebugInfo.cppindex+", "); // _CPPindex w.write(""+cppDebugInfo.x10line+", "); // _X10line w.write(""+cppDebugInfo.cppfromline+", "); // _CPPFromLine w.write(""+cppDebugInfo.cpptoline); // _CPPtoLine w.writeln(" },"); } w.writeln("};"); w.forceNewline(); // A list of the X10 method names. // Sorted by X10 method name. ArrayList<CPPMethodInfo> x10MethodList = new ArrayList<CPPMethodInfo>(m.methods.size()); HashMap<Key, CPPMethodInfo> keyToMethod = new HashMap<Key, CPPMethodInfo>(); for (MethodDescriptor md : m.methods.keySet()) { MethodDescriptor sm = m.methods.get(md); final CPPMethodInfo cmi = m.new CPPMethodInfo(sm.container, // _x10class sm.name, // _x10method sm.returnType, // _x10returnType sm.args, // _x10args md.container, // _cppClass sm.lines.end_line); // _lastX10Line x10MethodList.add(cmi); keyToMethod.put(md.lines, cmi); } // A cross reference of C++ statements to X10 statements. // Sorted by C++ file index and C++ source file line. // A line range is used to minimize the storage required. ArrayList<CPPLineInfo> cpptoX10xrefList = new ArrayList<CPPLineInfo>(m.map.size()); for (Key p : m.map.keySet()) { Entry e = m.map.get(p); cpptoX10xrefList.add( new CPPLineInfo(findFile(m.lookupString(e.fileId), files), // _X10index 0, // FIXME: _X10method offsets[p.fileId], // _CPPindex e.line, // _X10line p.start_line, // _CPPfromline p.end_line, // _CPPtoline p.fileId, e.column)); } Collections.sort(cpptoX10xrefList, CPPLineInfo.byCPPinfo()); w.writeln("static const struct _CPPtoX10xref _CPPtoX10xrefList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); int i = 0; for (CPPLineInfo cppDebugInfo : cpptoX10xrefList) { w.write(" { "); w.write(""+cppDebugInfo.x10index+", "); // _X10index // w.write(""+cppDebugInfo.x10method+", "); // _X10method w.write(""+cppDebugInfo.cppindex+", "); // _CPPindex w.write(""+cppDebugInfo.x10line+", "); // _X10line w.write(""+cppDebugInfo.cppfromline+", "); // _CPPfromline w.write(""+cppDebugInfo.cpptoline); // _CPPtoline w.writeln(" },"); Key k = new Key(cppDebugInfo.fileId, cppDebugInfo.cppfromline, cppDebugInfo.cpptoline); CPPMethodInfo methodInfo = keyToMethod.get(k); if (methodInfo != null) { methodInfo.cpplineindex = i; // _lineIndex } i++; } w.writeln("};"); w.forceNewline(); if (!m.methods.isEmpty()) { Collections.sort(x10MethodList); // FIXME: Cannot put _X10methodNameList in debugDataSectionAttr, because it's not constant // (the strings cause static initialization for some reason) w.writeln("static const struct _X10methodName _X10methodNameList[] __attribute__((used)) = {"); w.writeln("#if defined(__xlC__)"); for (CPPMethodInfo cppMethodInfo : x10MethodList) { w.write(" { "); w.write(""+offsets[cppMethodInfo.x10class]+", "); // _x10class w.write(""+offsets[cppMethodInfo.x10method]+", "); // _x10method w.write(""+offsets[cppMethodInfo.x10rettype]+", "); // _x10returnType w.write(""+offsets[cppMethodInfo.cppclass]+", "); // _cppClass w.write("(uint64_t) 0, "); // TODO - this needs to be re-designed, with the debugger team w.write(""+cppMethodInfo.x10args.length+", "); // _x10argCount w.write(""+cppMethodInfo.cpplineindex+", "); // _lineIndex w.write(""+cppMethodInfo.lastX10Line); // _lastX10Line w.writeln(" },"); } w.writeln("#else"); for (CPPMethodInfo cppMethodInfo : x10MethodList) { w.write(" { "); w.write(""+offsets[cppMethodInfo.x10class]+", "); // _x10class w.write(""+offsets[cppMethodInfo.x10method]+", "); // _x10method w.write(""+offsets[cppMethodInfo.x10rettype]+", "); // _x10returnType w.write(""+offsets[cppMethodInfo.cppclass]+", "); // _cppClass w.write("(uint64_t) "); for (i = 0; i < cppMethodInfo.x10args.length; i++) { int a = cppMethodInfo.x10args[i]; w.write("\""+encodeIntAsChars(offsets[a])+"\" "); // _x10args } w.write("\"\", "); w.write(""+cppMethodInfo.x10args.length+", "); // _x10argCount w.write(""+cppMethodInfo.cpplineindex+", "); // _lineIndex w.write(""+cppMethodInfo.lastX10Line); // _lastX10Line w.writeln(" },"); } w.writeln("#endif"); w.writeln("};"); w.forceNewline(); } // variable map stuff if (localVariables != null) { w.writeln("static const struct _X10LocalVarMap _X10variableNameList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (LocalVariableMapInfo v : localVariables) w.writeln(" { "+offsets[v._x10name]+", "+v._x10type+", "+(v._x10type==101?offsets[v._x10typeIndex]:v._x10typeIndex)+", "+offsets[v._cppName]+", "+findFile(v._x10index, files)+", "+v._x10startLine+", "+v._x10endLine+" }, // "+m.lookupString(v._x10name)); w.writeln("};"); w.forceNewline(); } } if (memberVariables != null) { for (String classname : memberVariables.keySet()) { w.writeln("static const struct _X10TypeMember _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (MemberVariableMapInfo v : memberVariables.get(classname)) w.writeln(" { "+v._x10type+", "+v._x10typeIndex+", "+offsets[v._x10memberName]+", "+offsets[v._cppMemberName]+", "+offsets[v._cppClass]+" }, // "+m.lookupString(v._x10memberName)); w.writeln("};"); w.forceNewline(); } w.writeln("static const struct _X10ClassMap _X10ClassMapList[] __attribute__((used)) = {"); for (String classname : memberVariables.keySet()) w.writeln(" { 101, "+offsets[memberVariables.get(classname).get(0)._cppClass]+", sizeof("+classname.replace(".", "::")+"), "+memberVariables.get(classname).size()+", _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members },"); w.writeln("};"); w.forceNewline(); } if (closureMembers != null) { for (String classname : closureMembers.keySet()) { w.writeln("static const struct _X10TypeMember _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members[] __attribute__((used)) "+debugDataSectionAttr+" = {"); for (MemberVariableMapInfo v : closureMembers.get(classname)) w.writeln(" { "+v._x10type+", "+v._x10typeIndex+", "+offsets[v._x10memberName]+", "+offsets[v._cppMemberName]+", "+offsets[v._cppClass]+" }, // "+m.lookupString(v._x10memberName)); w.writeln("};"); w.forceNewline(); } w.writeln("static const struct _X10ClosureMap _X10ClosureMapList[] __attribute__((used)) = {"); // inclusion of debugDataSectionAttr causes issues on Macos. See XTENLANG-2318. for (String classname : closureMembers.keySet()) w.writeln(" { 100, "+offsets[closureMembers.get(classname).get(0)._cppClass]+", sizeof("+classname.replace(".", "::")+"), "+closureMembers.get(classname).size()+", 0, 0, 0, _X10"+classname.substring(classname.lastIndexOf('.')+1)+"Members },"); w.writeln("};"); w.forceNewline(); } if (!arrayMap.isEmpty()) { w.writeln("static const struct _X10ArrayMap _X10ArrayMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); Iterator<Integer> iterator = arrayMap.iterator(); while(iterator.hasNext()) w.writeln(" { "+iterator.next()+", "+iterator.next()+" },"); w.writeln("};"); w.forceNewline(); } if (!refMap.isEmpty()) { w.writeln("static const struct _X10RefMap _X10RefMapList[] __attribute__((used)) "+debugDataSectionAttr+" = {"); Iterator<Integer> iterator = refMap.iterator(); while(iterator.hasNext()) w.writeln(" { "+iterator.next()+", "+iterator.next()+" },"); w.writeln("};"); w.forceNewline(); } // A meta-structure that refers to all of the above w.write("static const struct _MetaDebugInfo_t _MetaDebugInfo __attribute__((used)) "+debugSectionAttr+" = {"); w.newline(4); w.begin(0); w.writeln("sizeof(struct _MetaDebugInfo_t),"); w.writeln("X10_META_LANG,"); w.writeln("0,"); w.writeln("sizeof(_X10strings),"); if (!m.isEmpty()) { w.writeln("sizeof(_X10sourceList),"); w.writeln("sizeof(_X10toCPPlist),"); // w.writeln("0,"); w.writeln("sizeof(_CPPtoX10xrefList),"); } else { w.writeln("0,"); w.writeln("0,"); w.writeln("0,"); } if (!m.methods.isEmpty()) { w.writeln("sizeof(_X10methodNameList),"); } else { w.writeln("0, // no member variable mappings"); } if (!m.isEmpty() && localVariables != null) w.writeln("sizeof(_X10variableNameList),"); else w.writeln("0, // no local variable mappings"); if (memberVariables != null) w.writeln("sizeof(_X10ClassMapList),"); else w.writeln("0, // no class mappings"); if (closureMembers != null) w.writeln("sizeof(_X10ClosureMapList),"); else w.writeln("0, // no closure mappings"); if (!arrayMap.isEmpty()) w.writeln("sizeof(_X10ArrayMapList),"); else w.writeln("0, // no array mappings"); if (!refMap.isEmpty()) w.writeln("sizeof(_X10RefMapList),"); else w.writeln("0, // no reference mappings"); w.writeln("_X10strings,"); if (!m.isEmpty()) { w.writeln("_X10sourceList,"); w.writeln("_X10toCPPlist,"); // w.writeln("NULL,"); w.writeln("_CPPtoX10xrefList,"); } else { w.writeln("NULL,"); w.writeln("NULL,"); w.writeln("NULL,"); } if (!m.methods.isEmpty()) { w.writeln("_X10methodNameList,"); m.methods.clear(); } else { w.writeln("NULL,"); } if (localVariables != null) { if (!m.isEmpty()) w.writeln("_X10variableNameList,"); else w.writeln("NULL,"); localVariables.clear(); localVariables = null; } else w.writeln("NULL,"); if (memberVariables != null) { w.writeln("_X10ClassMapList,"); memberVariables.clear(); memberVariables = null; } else w.writeln("NULL,"); if (closureMembers != null) { w.writeln("_X10ClosureMapList,"); closureMembers.clear(); closureMembers = null; } else w.writeln("NULL,"); if (!arrayMap.isEmpty()) { arrayMap.clear(); w.writeln("_X10ArrayMapList,"); } else w.writeln("NULL,"); if (!refMap.isEmpty()) { refMap.clear(); w.write("_X10RefMapList"); } else w.write("NULL"); w.end(); w.newline(); w.writeln("};"); }
diff --git a/src/org/red5/server/net/rtmp/RTMPConnection.java b/src/org/red5/server/net/rtmp/RTMPConnection.java index df5189b6..ea7c8f19 100644 --- a/src/org/red5/server/net/rtmp/RTMPConnection.java +++ b/src/org/red5/server/net/rtmp/RTMPConnection.java @@ -1,345 +1,345 @@ package org.red5.server.net.rtmp; import static org.red5.server.api.ScopeUtils.getScopeService; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.mina.common.ByteBuffer; import org.red5.server.BaseConnection; import org.red5.server.api.IBandwidthConfigure; import org.red5.server.api.IContext; import org.red5.server.api.IFlowControllable; import org.red5.server.api.IScope; import org.red5.server.api.service.IPendingServiceCall; import org.red5.server.api.service.IPendingServiceCallback; import org.red5.server.api.service.IServiceCall; import org.red5.server.api.service.IServiceCapableConnection; import org.red5.server.api.so.ISharedObject; import org.red5.server.api.so.ISharedObjectCapableConnection; import org.red5.server.api.so.ISharedObjectService; import org.red5.server.api.stream.IClientBroadcastStream; import org.red5.server.api.stream.IClientStream; import org.red5.server.api.stream.IPlaylistSubscriberStream; import org.red5.server.api.stream.ISingleItemSubscriberStream; import org.red5.server.api.stream.IStreamCapableConnection; import org.red5.server.api.stream.IStreamService; import org.red5.server.net.rtmp.event.Invoke; import org.red5.server.net.rtmp.event.Ping; import org.red5.server.net.rtmp.message.Packet; import org.red5.server.service.PendingCall; import org.red5.server.so.SharedObjectService; import org.red5.server.stream.ClientBroadcastStream; import org.red5.server.stream.IFlowControlService; import org.red5.server.stream.OutputStream; import org.red5.server.stream.PlaylistSubscriberStream; import org.red5.server.stream.StreamService; import org.red5.server.stream.VideoCodecFactory; import org.springframework.context.ApplicationContext; public abstract class RTMPConnection extends BaseConnection implements IStreamCapableConnection, IServiceCapableConnection { protected static Log log = LogFactory.getLog(RTMPConnection.class.getName()); private final static int MAX_STREAMS = 12; private final static String VIDEO_CODEC_FACTORY = "videoCodecFactory"; //private Context context; private Channel[] channels = new Channel[64]; private IClientStream[] streams = new IClientStream[MAX_STREAMS]; private boolean[] reservedStreams = new boolean[MAX_STREAMS]; protected Integer invokeId = new Integer(1); protected HashMap<Integer,IPendingServiceCall> pendingCalls = new HashMap<Integer,IPendingServiceCall>(); protected int lastPingTime = -1; private IBandwidthConfigure bandwidthConfig; public RTMPConnection(String type) { // We start with an anonymous connection without a scope. // These parameters will be set during the call of "connect" later. //super(null, ""); temp fix to get things to compile super(type,null,null,null,null,null); } public void setup(String host, String path, String sessionId, Map<String, String> params){ this.host = host; this.path = path; this.sessionId = sessionId; this.params = params; } public int getNextAvailableChannelId(){ int result = -1; for(byte i=4; i<channels.length; i++){ if(!isChannelUsed(i)){ result = i; break; } } return result; } public boolean isChannelUsed(byte channelId){ return (channels[channelId] != null); } public Channel getChannel(byte channelId){ if(!isChannelUsed(channelId)) channels[channelId] = new Channel(this, channelId); return channels[channelId]; } public void closeChannel(byte channelId){ channels[channelId] = null; } public int reserveStreamId() { int result = -1; synchronized (reservedStreams) { for (int i=0; i<reservedStreams.length; i++) { if (!reservedStreams[i]) { reservedStreams[i] = true; result = i; break; } } } return result + 1; } public OutputStream createOutputStream(int streamId) { byte channelId = (byte) (4 + ((streamId - 1) * 5)); final Channel data = getChannel(channelId++); final Channel video = getChannel(channelId++); final Channel audio = getChannel(channelId++); //final Channel unknown = getChannel(channelId++); //final Channel ctrl = getChannel(channelId++); return new OutputStream(video, audio, data); } public VideoCodecFactory getVideoCodecFactory() { final IContext context = scope.getContext(); ApplicationContext appCtx = context.getApplicationContext(); if (!appCtx.containsBean(VIDEO_CODEC_FACTORY)) return null; return (VideoCodecFactory) appCtx.getBean(VIDEO_CODEC_FACTORY); } public IClientBroadcastStream newBroadcastStream(int streamId) { if (!reservedStreams[streamId - 1]) // StreamId has not been reserved before return null; if (streams[streamId - 1] != null) // Another stream already exists with this id return null; ClientBroadcastStream cbs = new ClientBroadcastStream(); cbs.setStreamId(streamId); cbs.setConnection(this); cbs.setName(createStreamName()); cbs.setScope(this.getScope()); streams[streamId - 1] = cbs; return cbs; } public ISingleItemSubscriberStream newSingleItemSubscriberStream(int streamId) { // TODO implement it return null; } public IPlaylistSubscriberStream newPlaylistSubscriberStream(int streamId) { if (!reservedStreams[streamId - 1]) // StreamId has not been reserved before return null; if (streams[streamId - 1] != null) // Another stream already exists with this id return null; PlaylistSubscriberStream pss = new PlaylistSubscriberStream(); pss.setName(createStreamName()); pss.setConnection(this); pss.setScope(this.getScope()); pss.setStreamId(streamId); streams[streamId - 1] = pss; return pss; } public IClientStream getStreamById(int id){ if (id <= 0 || id > MAX_STREAMS-1) return null; return streams[id-1]; } public IClientStream getStreamByChannelId(byte channelId){ if (channelId < 4) return null; //log.debug("Channel id: "+channelId); int id = (int) Math.floor((channelId-4)/5); //log.debug("Stream: "+streamId); return streams[id]; } public void close(){ IStreamService streamService = (IStreamService) getScopeService(scope, IStreamService.STREAM_SERVICE, StreamService.class); if (streamService != null) { synchronized (streams) { for(int i=0; i<streams.length; i++){ IClientStream stream = streams[i]; if(stream != null) { log.debug("Closing stream: "+ stream.getStreamId()); streamService.deleteStream(this, stream.getStreamId()); streams[i] = null; } } } } - super.close(); IFlowControlService fcs = (IFlowControlService) getScope().getContext().getBean( IFlowControlService.KEY); fcs.unregisterFlowControllable(this); + super.close(); } public void unreserveStreamId(int streamId) { if (streamId >= 0 && streamId < MAX_STREAMS-1) { streams[streamId-1] = null; reservedStreams[streamId-1] = false; } } public void ping(Ping ping){ getChannel((byte)2).write(ping); } public abstract void rawWrite(ByteBuffer out); public abstract void write(Packet out); public void invoke(IServiceCall call) { // We need to use Invoke for all calls to the client Invoke invoke = new Invoke(); invoke.setCall(call); synchronized (invokeId) { invoke.setInvokeId(invokeId); if (call instanceof IPendingServiceCall) { synchronized (pendingCalls) { pendingCalls.put(invokeId, (IPendingServiceCall) call); } } invokeId += 1; } getChannel((byte) 3).write(invoke); } public void invoke(String method) { invoke(method, null, null); } public void invoke(String method, Object[] params) { invoke(method, params, null); } public void invoke(String method, IPendingServiceCallback callback) { invoke(method, null, callback); } public void invoke(String method, Object[] params, IPendingServiceCallback callback) { IPendingServiceCall call = new PendingCall(method, params); if (callback != null) call.registerCallback(callback); invoke(call); } public IBandwidthConfigure getBandwidthConfigure() { return bandwidthConfig; } public IFlowControllable getParentFlowControllable() { return this.getClient(); } public void setBandwidthConfigure(IBandwidthConfigure config) { IFlowControlService fcs = (IFlowControlService) getScope().getContext().getBean( IFlowControlService.KEY); boolean needRegister = false; if (this.bandwidthConfig == null) { if (config != null) { needRegister = true; } else return; } this.bandwidthConfig = config; if (needRegister) { fcs.registerFlowControllable(this); } else { fcs.updateBWConfigure(this); } } @Override public long getReadBytes() { // TODO Auto-generated method stub return 0; } @Override public long getWrittenBytes() { // TODO Auto-generated method stub return 0; } protected IPendingServiceCall getPendingCall(int invokeId) { IPendingServiceCall result; synchronized (pendingCalls) { result = pendingCalls.get(invokeId); if (result != null) pendingCalls.remove(invokeId); } return result; } protected String createStreamName() { return UUID.randomUUID().toString(); } protected void messageReceived() { readMessages++; } protected void messageSent() { writtenMessages++; } protected void messageDropped() { droppedMessages++; } public void ping() { Ping pingRequest = new Ping(); pingRequest.setValue1((short) 6); int now = (int) (System.currentTimeMillis() & 0xffffffff); pingRequest.setValue2(now); pingRequest.setValue3(Ping.UNDEFINED); ping(pingRequest); } protected void pingReceived(Ping pong) { int now = (int) (System.currentTimeMillis() & 0xffffffff); lastPingTime = now - pong.getValue2(); } public int getLastPingTime() { return lastPingTime; } }
false
true
public void close(){ IStreamService streamService = (IStreamService) getScopeService(scope, IStreamService.STREAM_SERVICE, StreamService.class); if (streamService != null) { synchronized (streams) { for(int i=0; i<streams.length; i++){ IClientStream stream = streams[i]; if(stream != null) { log.debug("Closing stream: "+ stream.getStreamId()); streamService.deleteStream(this, stream.getStreamId()); streams[i] = null; } } } } super.close(); IFlowControlService fcs = (IFlowControlService) getScope().getContext().getBean( IFlowControlService.KEY); fcs.unregisterFlowControllable(this); }
public void close(){ IStreamService streamService = (IStreamService) getScopeService(scope, IStreamService.STREAM_SERVICE, StreamService.class); if (streamService != null) { synchronized (streams) { for(int i=0; i<streams.length; i++){ IClientStream stream = streams[i]; if(stream != null) { log.debug("Closing stream: "+ stream.getStreamId()); streamService.deleteStream(this, stream.getStreamId()); streams[i] = null; } } } } IFlowControlService fcs = (IFlowControlService) getScope().getContext().getBean( IFlowControlService.KEY); fcs.unregisterFlowControllable(this); super.close(); }
diff --git a/safe-online-sdk/src/main/java/net/link/safeonline/sdk/auth/servlet/AbstractLogoutServlet.java b/safe-online-sdk/src/main/java/net/link/safeonline/sdk/auth/servlet/AbstractLogoutServlet.java index 2d96fc4ec..2373645a9 100644 --- a/safe-online-sdk/src/main/java/net/link/safeonline/sdk/auth/servlet/AbstractLogoutServlet.java +++ b/safe-online-sdk/src/main/java/net/link/safeonline/sdk/auth/servlet/AbstractLogoutServlet.java @@ -1,137 +1,137 @@ /* * SafeOnline project. * * Copyright 2006-2007 Lin.k N.V. All rights reserved. * Lin.k N.V. proprietary/confidential. Use is subject to license terms. */ package net.link.safeonline.sdk.auth.servlet; import com.google.common.base.Function; import com.lyndir.lhunath.opal.system.logging.Logger; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import net.link.safeonline.sdk.auth.filter.LoginManager; import net.link.safeonline.sdk.auth.protocol.*; import net.link.safeonline.sdk.configuration.LogoutContext; import net.link.safeonline.sdk.servlet.AbstractConfidentialLinkIDInjectionServlet; import net.link.util.error.ValidationFailedException; import net.link.util.servlet.ErrorMessage; import net.link.util.servlet.ServletUtils; import net.link.util.servlet.annotation.Init; /** * Abstract Logout Servlet. This servlet contains the landing page to finalize the logout process initiated by the web application. This * servlet also removes the {@code userId} attribute and redirects to the specified target when the logout request was made. * <p/> * This servlet also handles a logout request sent by the link ID authentication web application due to a single logout request sent by an * linkID application. After handling the request, it will redirect to {@code LogoutPath}. To finalize this, the web application should * redirect back to this page using Http GET, which will trigger this landing page to send back a logout response to the link ID * authentication web application. * * @author wvdhaute */ public abstract class AbstractLogoutServlet extends AbstractConfidentialLinkIDInjectionServlet { private static final Logger logger = Logger.get( AbstractLogoutServlet.class ); public static final String ERROR_PAGE_PARAM = "ErrorPage"; @Init(name = ERROR_PAGE_PARAM, optional = true) private String errorPage; @Override protected void invokePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.dbg( "POST: %s", request.getParameterMap().keySet() ); try { // Check for a linkID logout response (response to the application's logout request). LogoutProtocolResponseContext logoutResponse = ProtocolManager.findAndValidateLogoutResponse( request ); if (logoutResponse != null) { // There is a logout response, handle it: Log out and redirect back to the application. if (logout( request.getSession(), logoutResponse )) // Logout allowed by application, clean up credentials. LoginManager.cleanup( request.getSession() ); String target = logoutResponse.getRequest().getTarget(); response.sendRedirect( target == null? "/": target ); return; } // Check for a linkID logout request (request as a result of another pool application's logout request to linkID). LogoutProtocolRequestContext logoutRequest = ProtocolManager.findAndValidateLogoutRequest( request, getContextFunction() ); if (logoutRequest != null) { boolean logoutAllowed = logout( request.getSession(), logoutRequest ); if (logoutAllowed && logoutRequest.getUserId().equals( LoginManager.findUserId( request.getSession() ) )) // Logout allowed by application and requests logout for current session user: clean up credentials. LoginManager.cleanup( request.getSession() ); logoutRequest.getProtocolHandler().sendLogoutResponse( response, logoutRequest, !logoutAllowed ); return; } } catch (ValidationFailedException e) { logger.err( e, ServletUtils.redirectToErrorPage( request, response, errorPage, null, new ErrorMessage( e ) ) ); return; } - throw new UnsupportedOperationException( "No logout request or response in the request." ); + ServletUtils.redirectToErrorPage( request, response, errorPage, null, new ErrorMessage( "Invalid logout request" ) ); } /** * Override this method if you want to create a custom context for logout responses depending on the logout request. * <p/> * The standard implementation uses {@link LogoutContext#LogoutContext()}. * * @return A function that provides the context for validating and creating a logout response to a given logout request. */ protected Function<LogoutProtocolRequestContext, LogoutContext> getContextFunction() { return new Function<LogoutProtocolRequestContext, LogoutContext>() { @Override public LogoutContext apply(LogoutProtocolRequestContext from) { return new LogoutContext(); } }; } /** * Invoked when a logout request is received from linkID as a result of another application in the pool requesting a single logout. * <p/> * Implement this to log the application user out of the session and perform any other possible user session cleanup. * <p/> * A successful logout will also cause the SDK to remove its credentials from the HTTP session. Return false here if the application * state requires the user is not logged out. The SDK will leave its credentials on the HTTP session and the single logout process * initiated by the other pool application will be marked as 'partial'. * <p/> * You are allowed to invalidate the HTTP session from here for a quick and thorough logout; if that makes sense in your application * logic. * * @param logoutRequest linkID's logout request. * * @return true if the application allowed the user to log out. */ protected abstract boolean logout(HttpSession session, LogoutProtocolRequestContext logoutRequest); /** * Invoked after a logout request from this application has been handled by linkID and a logout response from linkID is received. * <p/> * Implement this to log the application user out of the session and perform any other possible user session cleanup. * <p/> * A successful logout will also cause the SDK to remove its credentials from the HTTP session. Return false here if the application * state requires the user is not logged out. The SDK will leave its credentials on the HTTP session. * <p/> * You are allowed to invalidate the HTTP session from here for a quick and thorough logout; if that makes sense in your application * logic. * * @param logoutResponse linkID's response to our logout request. * * @return true if the application allowed the user to log out. */ protected abstract boolean logout(HttpSession session, LogoutProtocolResponseContext logoutResponse); }
true
true
protected void invokePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.dbg( "POST: %s", request.getParameterMap().keySet() ); try { // Check for a linkID logout response (response to the application's logout request). LogoutProtocolResponseContext logoutResponse = ProtocolManager.findAndValidateLogoutResponse( request ); if (logoutResponse != null) { // There is a logout response, handle it: Log out and redirect back to the application. if (logout( request.getSession(), logoutResponse )) // Logout allowed by application, clean up credentials. LoginManager.cleanup( request.getSession() ); String target = logoutResponse.getRequest().getTarget(); response.sendRedirect( target == null? "/": target ); return; } // Check for a linkID logout request (request as a result of another pool application's logout request to linkID). LogoutProtocolRequestContext logoutRequest = ProtocolManager.findAndValidateLogoutRequest( request, getContextFunction() ); if (logoutRequest != null) { boolean logoutAllowed = logout( request.getSession(), logoutRequest ); if (logoutAllowed && logoutRequest.getUserId().equals( LoginManager.findUserId( request.getSession() ) )) // Logout allowed by application and requests logout for current session user: clean up credentials. LoginManager.cleanup( request.getSession() ); logoutRequest.getProtocolHandler().sendLogoutResponse( response, logoutRequest, !logoutAllowed ); return; } } catch (ValidationFailedException e) { logger.err( e, ServletUtils.redirectToErrorPage( request, response, errorPage, null, new ErrorMessage( e ) ) ); return; } throw new UnsupportedOperationException( "No logout request or response in the request." ); }
protected void invokePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.dbg( "POST: %s", request.getParameterMap().keySet() ); try { // Check for a linkID logout response (response to the application's logout request). LogoutProtocolResponseContext logoutResponse = ProtocolManager.findAndValidateLogoutResponse( request ); if (logoutResponse != null) { // There is a logout response, handle it: Log out and redirect back to the application. if (logout( request.getSession(), logoutResponse )) // Logout allowed by application, clean up credentials. LoginManager.cleanup( request.getSession() ); String target = logoutResponse.getRequest().getTarget(); response.sendRedirect( target == null? "/": target ); return; } // Check for a linkID logout request (request as a result of another pool application's logout request to linkID). LogoutProtocolRequestContext logoutRequest = ProtocolManager.findAndValidateLogoutRequest( request, getContextFunction() ); if (logoutRequest != null) { boolean logoutAllowed = logout( request.getSession(), logoutRequest ); if (logoutAllowed && logoutRequest.getUserId().equals( LoginManager.findUserId( request.getSession() ) )) // Logout allowed by application and requests logout for current session user: clean up credentials. LoginManager.cleanup( request.getSession() ); logoutRequest.getProtocolHandler().sendLogoutResponse( response, logoutRequest, !logoutAllowed ); return; } } catch (ValidationFailedException e) { logger.err( e, ServletUtils.redirectToErrorPage( request, response, errorPage, null, new ErrorMessage( e ) ) ); return; } ServletUtils.redirectToErrorPage( request, response, errorPage, null, new ErrorMessage( "Invalid logout request" ) ); }
diff --git a/src/org/hystudio/android/dosbox/DOSBoxSettings.java b/src/org/hystudio/android/dosbox/DOSBoxSettings.java index 48a4856..834d1c2 100644 --- a/src/org/hystudio/android/dosbox/DOSBoxSettings.java +++ b/src/org/hystudio/android/dosbox/DOSBoxSettings.java @@ -1,274 +1,275 @@ /** * */ package org.hystudio.android.dosbox; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnShowListener; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; /** * @author zhguo * */ public class DOSBoxSettings { // TODO this should be user configurable // Read function CPU_CycleIncrease for details. // If cpu cycle is set to "auto", 5% is increased/decreased each time. // Otherwise, if step is smaller than 100, it is considered as a percentage. // if step is not smaller than 100, it is considered as an absolute vlaue. private static int cpucycle_change = 200; private static AlertDialog dialog = null; protected static void showConfigMainMenu(final MainActivity p) { if (dialog != null) { dialog.show(); return; } AlertDialog.Builder builder = new AlertDialog.Builder(p); builder.setTitle(p.getResources().getString(R.string.dosbox_settings)); LayoutInflater inflater = (LayoutInflater) p .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ViewGroup dosboxSettingView = (ViewGroup) inflater.inflate( R.layout.dosbox_settings, null); final LinearLayout cpuIncLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cpucycle_inc_ll); cpuIncLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { increaseCPUCycles(p); updateView(dosboxSettingView); } }); final LinearLayout cpuDecLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cpucycle_dec_ll); cpuDecLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { decreaseCPUCycles(p); updateView(dosboxSettingView); } }); final LinearLayout frameskipIncLL = (LinearLayout) dosboxSettingView .findViewById(R.id.frameskip_inc_ll); frameskipIncLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { increaseFrameskip(p); updateView(dosboxSettingView); } }); final LinearLayout frameskipDecLL = (LinearLayout) dosboxSettingView .findViewById(R.id.frameskip_dec_ll); frameskipDecLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { decreaseFrameskip(p); updateView(dosboxSettingView); } }); // CPU cycle change final LinearLayout cpuCycleUpLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cyclechange_up_ll); cpuCycleUpLL.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { AlertDialog.Builder builder = new AlertDialog.Builder(p); LinearLayout ll = new LinearLayout(p); ll.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.setOrientation(LinearLayout.VERTICAL); final EditText cycleChangeET = new EditText(p); cycleChangeET.setSingleLine(); cycleChangeET.setWidth(200); ll.addView(cycleChangeET); TextView helpView = new TextView(p); helpView.setText("hint: >= 100, absolute value; < 100, percentage"); helpView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); + ll.addView(helpView); builder.setView(ll); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { String strCycleChange = cycleChangeET.getText().toString(); try { int cycleChange = Integer.valueOf(strCycleChange); int max = 1000, min = 5; if (cycleChange > max || cycleChange < min) { Toast.makeText(p, String.format("Entered value is not correct [%d-%d]", min, max), 2000).show(); return; } nativeSetCPUCycleUp(cycleChange); updateView(dosboxSettingView); } catch (Exception e) { Log.e("aDOSBox", e.getMessage()); } } }); dialog.show(); return true; } }); final LinearLayout cpuCycleDownLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cyclechange_down_ll); cpuCycleDownLL.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { AlertDialog.Builder builder = new AlertDialog.Builder(p); LinearLayout ll = new LinearLayout(p); ll.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.setOrientation(LinearLayout.VERTICAL); final EditText cycleChangeET = new EditText(p); cycleChangeET.setSingleLine(); cycleChangeET.setWidth(200); ll.addView(cycleChangeET); TextView helpView = new TextView(p); helpView.setText("hint: >= 100, absolute value; < 100, percentage"); helpView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); ll.addView(helpView); builder.setView(ll); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { String strCycleChange = cycleChangeET.getText().toString(); try { int cycleChange = Integer.valueOf(strCycleChange); int max = 1000, min = 5; if (cycleChange > max || cycleChange < min) { Toast.makeText(p, String.format("Entered value is not correct [%d-%d]", min, max), 2000).show(); return; } nativeSetCPUCycleDown(cycleChange); updateView(dosboxSettingView); } catch (Exception e) { Log.e("aDOSBox", e.getMessage()); } } }); dialog.show(); return true; } }); builder.setView(dosboxSettingView); dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface paramDialogInterface) { updateView(dosboxSettingView); } }); dialog.show(); } private static void updateView(ViewGroup dosboxSettingView) { TextView incTV = (TextView) dosboxSettingView .findViewById(R.id.cpucycleshow_inc_tv); TextView decTV = (TextView) dosboxSettingView .findViewById(R.id.cpucycleshow_dec_tv); TextView cycleUpTV = (TextView) dosboxSettingView .findViewById(R.id.cpucycleup_show_tv); TextView cycleDownTV = (TextView) dosboxSettingView .findViewById(R.id.cpucycledown_show_tv); TextView frameskipIncTV = (TextView) dosboxSettingView .findViewById(R.id.frameskip_show_inc_tv); TextView frameskipDecTV = (TextView) dosboxSettingView .findViewById(R.id.frameskip_show_dec_tv); int cycles = nativeGetCPUCycle(); int cycleUp = nativeGetCPUCycleUp(); int cycleDown = nativeGetCPUCycleDown(); int frameskip = nativeGetFrameskip(); incTV.setText(cycles + ""); decTV.setText(cycles + ""); cycleUpTV.setText(cycleUp + ""); cycleDownTV.setText(cycleDown + ""); frameskipIncTV.setText(frameskip + ""); frameskipDecTV.setText(frameskip + ""); } private static void increaseCPUCycles(Context p) { nativeCPUCycleIncrease(); } private static void decreaseCPUCycles(Context p) { nativeCPUCycleDecrease(); } private static void increaseFrameskip(Context p) { nativeFrameskipIncrease(); } private static void decreaseFrameskip(Context p) { nativeFrameskipDecrease(); } static { String libs[] = { "application", "sdl_main" }; try { for (String l : libs) { System.loadLibrary(l); } } catch (UnsatisfiedLinkError e) { e.printStackTrace(); Log.e("aDOSBox", e.getMessage()); } } private static native void nativeCPUCycleIncrease(); private static native void nativeCPUCycleDecrease(); private static native void nativeFrameskipIncrease(); private static native void nativeFrameskipDecrease(); private static native int nativeGetCPUCycle(); private static native int nativeGetCPUCycleUp(); private static native int nativeGetCPUCycleDown(); private static native void nativeSetCPUCycleUp(int cycleup); private static native void nativeSetCPUCycleDown(int cycledown); private static native int nativeGetFrameskip(); }
true
true
protected static void showConfigMainMenu(final MainActivity p) { if (dialog != null) { dialog.show(); return; } AlertDialog.Builder builder = new AlertDialog.Builder(p); builder.setTitle(p.getResources().getString(R.string.dosbox_settings)); LayoutInflater inflater = (LayoutInflater) p .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ViewGroup dosboxSettingView = (ViewGroup) inflater.inflate( R.layout.dosbox_settings, null); final LinearLayout cpuIncLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cpucycle_inc_ll); cpuIncLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { increaseCPUCycles(p); updateView(dosboxSettingView); } }); final LinearLayout cpuDecLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cpucycle_dec_ll); cpuDecLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { decreaseCPUCycles(p); updateView(dosboxSettingView); } }); final LinearLayout frameskipIncLL = (LinearLayout) dosboxSettingView .findViewById(R.id.frameskip_inc_ll); frameskipIncLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { increaseFrameskip(p); updateView(dosboxSettingView); } }); final LinearLayout frameskipDecLL = (LinearLayout) dosboxSettingView .findViewById(R.id.frameskip_dec_ll); frameskipDecLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { decreaseFrameskip(p); updateView(dosboxSettingView); } }); // CPU cycle change final LinearLayout cpuCycleUpLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cyclechange_up_ll); cpuCycleUpLL.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { AlertDialog.Builder builder = new AlertDialog.Builder(p); LinearLayout ll = new LinearLayout(p); ll.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.setOrientation(LinearLayout.VERTICAL); final EditText cycleChangeET = new EditText(p); cycleChangeET.setSingleLine(); cycleChangeET.setWidth(200); ll.addView(cycleChangeET); TextView helpView = new TextView(p); helpView.setText("hint: >= 100, absolute value; < 100, percentage"); helpView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); builder.setView(ll); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { String strCycleChange = cycleChangeET.getText().toString(); try { int cycleChange = Integer.valueOf(strCycleChange); int max = 1000, min = 5; if (cycleChange > max || cycleChange < min) { Toast.makeText(p, String.format("Entered value is not correct [%d-%d]", min, max), 2000).show(); return; } nativeSetCPUCycleUp(cycleChange); updateView(dosboxSettingView); } catch (Exception e) { Log.e("aDOSBox", e.getMessage()); } } }); dialog.show(); return true; } }); final LinearLayout cpuCycleDownLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cyclechange_down_ll); cpuCycleDownLL.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { AlertDialog.Builder builder = new AlertDialog.Builder(p); LinearLayout ll = new LinearLayout(p); ll.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.setOrientation(LinearLayout.VERTICAL); final EditText cycleChangeET = new EditText(p); cycleChangeET.setSingleLine(); cycleChangeET.setWidth(200); ll.addView(cycleChangeET); TextView helpView = new TextView(p); helpView.setText("hint: >= 100, absolute value; < 100, percentage"); helpView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); ll.addView(helpView); builder.setView(ll); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { String strCycleChange = cycleChangeET.getText().toString(); try { int cycleChange = Integer.valueOf(strCycleChange); int max = 1000, min = 5; if (cycleChange > max || cycleChange < min) { Toast.makeText(p, String.format("Entered value is not correct [%d-%d]", min, max), 2000).show(); return; } nativeSetCPUCycleDown(cycleChange); updateView(dosboxSettingView); } catch (Exception e) { Log.e("aDOSBox", e.getMessage()); } } }); dialog.show(); return true; } }); builder.setView(dosboxSettingView); dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface paramDialogInterface) { updateView(dosboxSettingView); } }); dialog.show(); }
protected static void showConfigMainMenu(final MainActivity p) { if (dialog != null) { dialog.show(); return; } AlertDialog.Builder builder = new AlertDialog.Builder(p); builder.setTitle(p.getResources().getString(R.string.dosbox_settings)); LayoutInflater inflater = (LayoutInflater) p .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ViewGroup dosboxSettingView = (ViewGroup) inflater.inflate( R.layout.dosbox_settings, null); final LinearLayout cpuIncLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cpucycle_inc_ll); cpuIncLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { increaseCPUCycles(p); updateView(dosboxSettingView); } }); final LinearLayout cpuDecLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cpucycle_dec_ll); cpuDecLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { decreaseCPUCycles(p); updateView(dosboxSettingView); } }); final LinearLayout frameskipIncLL = (LinearLayout) dosboxSettingView .findViewById(R.id.frameskip_inc_ll); frameskipIncLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { increaseFrameskip(p); updateView(dosboxSettingView); } }); final LinearLayout frameskipDecLL = (LinearLayout) dosboxSettingView .findViewById(R.id.frameskip_dec_ll); frameskipDecLL.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { decreaseFrameskip(p); updateView(dosboxSettingView); } }); // CPU cycle change final LinearLayout cpuCycleUpLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cyclechange_up_ll); cpuCycleUpLL.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { AlertDialog.Builder builder = new AlertDialog.Builder(p); LinearLayout ll = new LinearLayout(p); ll.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.setOrientation(LinearLayout.VERTICAL); final EditText cycleChangeET = new EditText(p); cycleChangeET.setSingleLine(); cycleChangeET.setWidth(200); ll.addView(cycleChangeET); TextView helpView = new TextView(p); helpView.setText("hint: >= 100, absolute value; < 100, percentage"); helpView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); ll.addView(helpView); builder.setView(ll); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { String strCycleChange = cycleChangeET.getText().toString(); try { int cycleChange = Integer.valueOf(strCycleChange); int max = 1000, min = 5; if (cycleChange > max || cycleChange < min) { Toast.makeText(p, String.format("Entered value is not correct [%d-%d]", min, max), 2000).show(); return; } nativeSetCPUCycleUp(cycleChange); updateView(dosboxSettingView); } catch (Exception e) { Log.e("aDOSBox", e.getMessage()); } } }); dialog.show(); return true; } }); final LinearLayout cpuCycleDownLL = (LinearLayout) dosboxSettingView .findViewById(R.id.cyclechange_down_ll); cpuCycleDownLL.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View paramView) { AlertDialog.Builder builder = new AlertDialog.Builder(p); LinearLayout ll = new LinearLayout(p); ll.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.setOrientation(LinearLayout.VERTICAL); final EditText cycleChangeET = new EditText(p); cycleChangeET.setSingleLine(); cycleChangeET.setWidth(200); ll.addView(cycleChangeET); TextView helpView = new TextView(p); helpView.setText("hint: >= 100, absolute value; < 100, percentage"); helpView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); ll.addView(helpView); builder.setView(ll); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { String strCycleChange = cycleChangeET.getText().toString(); try { int cycleChange = Integer.valueOf(strCycleChange); int max = 1000, min = 5; if (cycleChange > max || cycleChange < min) { Toast.makeText(p, String.format("Entered value is not correct [%d-%d]", min, max), 2000).show(); return; } nativeSetCPUCycleDown(cycleChange); updateView(dosboxSettingView); } catch (Exception e) { Log.e("aDOSBox", e.getMessage()); } } }); dialog.show(); return true; } }); builder.setView(dosboxSettingView); dialog = builder.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface paramDialogInterface) { updateView(dosboxSettingView); } }); dialog.show(); }
diff --git a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java index 62974ffe8..500ed9968 100644 --- a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java +++ b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java @@ -1,80 +1,80 @@ package org.jboss.resteasy.util; import javax.ws.rs.HttpMethod; import javax.ws.rs.Path; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class GetRestful { /** * Given a class, search itself and implemented interfaces for jax-rs annotations. * * @param clazz * @return list of class and intertfaces that have jax-rs annotations */ public static Class getRootResourceClass(Class clazz) { return AnnotationResolver.getClassWithAnnotation(clazz, Path.class); } /** * Given a class, search itself and implemented interfaces for jax-rs annotations. * * @param clazz * @return list of class and interfaces that have jax-rs annotations */ public static Class getSubResourceClass(Class clazz) { // check class & superclasses for JAX-RS annotations for(Class<?> actualClass = clazz; isTopObject(actualClass); actualClass = actualClass.getSuperclass()) { if( hasJAXRSAnnotations(actualClass)) return actualClass; } // ok, no @Path or @HttpMethods so look in interfaces. for (Class intf : clazz.getInterfaces()) { if( hasJAXRSAnnotations(intf)) return intf; } return null; } private static boolean isTopObject(Class<?> actualClass) { return actualClass != null && actualClass != Object.class; } private static boolean hasJAXRSAnnotations(Class<?> c){ if (c.isAnnotationPresent(Path.class)) { return true; } - for (Method method : c.getDeclaredMethods()) + for (Method method : c.isInterface() ? c.getMethods() : c.getDeclaredMethods()) { if (method.isAnnotationPresent(Path.class)) { return true; } for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().isAnnotationPresent(HttpMethod.class)) { return true; } } } return false; } public static boolean isRootResource(Class clazz) { return getRootResourceClass(clazz) != null; } }
true
true
private static boolean hasJAXRSAnnotations(Class<?> c){ if (c.isAnnotationPresent(Path.class)) { return true; } for (Method method : c.getDeclaredMethods()) { if (method.isAnnotationPresent(Path.class)) { return true; } for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().isAnnotationPresent(HttpMethod.class)) { return true; } } } return false; }
private static boolean hasJAXRSAnnotations(Class<?> c){ if (c.isAnnotationPresent(Path.class)) { return true; } for (Method method : c.isInterface() ? c.getMethods() : c.getDeclaredMethods()) { if (method.isAnnotationPresent(Path.class)) { return true; } for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().isAnnotationPresent(HttpMethod.class)) { return true; } } } return false; }
diff --git a/src/java/org/concord/otrunk/navigation/OTNavigationHistoryService.java b/src/java/org/concord/otrunk/navigation/OTNavigationHistoryService.java index bd31161..07134d6 100644 --- a/src/java/org/concord/otrunk/navigation/OTNavigationHistoryService.java +++ b/src/java/org/concord/otrunk/navigation/OTNavigationHistoryService.java @@ -1,87 +1,89 @@ package org.concord.otrunk.navigation; import java.util.HashMap; import java.util.logging.Logger; import org.concord.framework.otrunk.DefaultOTObject; import org.concord.framework.otrunk.OTBundle; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.OTResourceSchema; import org.concord.framework.otrunk.OTServiceContext; import org.concord.framework.otrunk.OTUser; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.wrapper.OTObjectSet; import org.concord.otrunk.OTrunkImpl; public class OTNavigationHistoryService extends DefaultOTObject implements OTBundle { private static final Logger logger = Logger.getLogger(OTNavigationHistoryService.class.getCanonicalName()); private OTrunkImpl otrunk; private HashMap<OTUser, OTObjectSet> navigationHistories = new HashMap<OTUser, OTObjectSet>(); public static interface ResourceSchema extends OTResourceSchema { // sequence of OTNavigationEvents OTObjectSet getNavigationHistory(); void setNavigationHistory(OTObjectSet history); } private ResourceSchema resources; public OTNavigationHistoryService(ResourceSchema resources) { super(resources); this.resources = resources; this.otrunk = (OTrunkImpl) resources.getOTObjectService().getOTrunkService(OTrunk.class); } public void initializeBundle(OTServiceContext serviceContext) { } public void registerServices(OTServiceContext serviceContext) { serviceContext.addService(OTNavigationHistoryService.class, this); } private OTObjectSet getUserNavigationHistory(OTUser user) throws Exception { if (user == null) { - user = otrunk.getUsers().get(0); + user = otrunk.getUsers().size() > 0 ? otrunk.getUsers().get(0) : null; } if (navigationHistories.containsKey(user)) { return navigationHistories.get(user); } - OTObjectSet set = resources.getNavigationHistory(); - if (set == null) { - set = otrunk.createObject(OTObjectSet.class); - resources.setNavigationHistory(set); + OTObjectSet defaultUserNavigationHistory = resources.getNavigationHistory(); + if (defaultUserNavigationHistory == null) { + defaultUserNavigationHistory = otrunk.createObject(OTObjectSet.class); + resources.setNavigationHistory(defaultUserNavigationHistory); + } + if (user != null) { + defaultUserNavigationHistory = (OTObjectSet) otrunk.getUserRuntimeObject(defaultUserNavigationHistory, user); } - OTObjectSet defaultUserNavigationHistory = (OTObjectSet) otrunk.getUserRuntimeObject(set, user); navigationHistories.put(user, defaultUserNavigationHistory); return defaultUserNavigationHistory; } public void logNavigationEvent(String type, OTObject obj) throws Exception { logNavigationEvent(type, obj, null); } public void logNavigationEvent(String type, OTObject obj, OTUser user) throws Exception { logger.fine((user == null ? "null user" : user.getName()) + " " + type + ": " + obj); OTObjectSet history = getUserNavigationHistory(user); OTNavigationEvent event = history.getOTObjectService().createObject(OTNavigationEvent.class); event.setTimestamp(System.currentTimeMillis()); event.setObject(obj); event.setType(type); history.getObjects().add(event); } public OTObjectList getNavigationHistory() throws Exception { return getUserNavigationHistory(null).getObjects(); } public OTObjectList getNavigationHistory(OTUser user) throws Exception { return getUserNavigationHistory(user).getObjects(); } }
false
true
private OTObjectSet getUserNavigationHistory(OTUser user) throws Exception { if (user == null) { user = otrunk.getUsers().get(0); } if (navigationHistories.containsKey(user)) { return navigationHistories.get(user); } OTObjectSet set = resources.getNavigationHistory(); if (set == null) { set = otrunk.createObject(OTObjectSet.class); resources.setNavigationHistory(set); } OTObjectSet defaultUserNavigationHistory = (OTObjectSet) otrunk.getUserRuntimeObject(set, user); navigationHistories.put(user, defaultUserNavigationHistory); return defaultUserNavigationHistory; }
private OTObjectSet getUserNavigationHistory(OTUser user) throws Exception { if (user == null) { user = otrunk.getUsers().size() > 0 ? otrunk.getUsers().get(0) : null; } if (navigationHistories.containsKey(user)) { return navigationHistories.get(user); } OTObjectSet defaultUserNavigationHistory = resources.getNavigationHistory(); if (defaultUserNavigationHistory == null) { defaultUserNavigationHistory = otrunk.createObject(OTObjectSet.class); resources.setNavigationHistory(defaultUserNavigationHistory); } if (user != null) { defaultUserNavigationHistory = (OTObjectSet) otrunk.getUserRuntimeObject(defaultUserNavigationHistory, user); } navigationHistories.put(user, defaultUserNavigationHistory); return defaultUserNavigationHistory; }
diff --git a/src/minecraft/org/getspout/spout/gui/ScreenUtil.java b/src/minecraft/org/getspout/spout/gui/ScreenUtil.java index 2ffc5085..38994e22 100644 --- a/src/minecraft/org/getspout/spout/gui/ScreenUtil.java +++ b/src/minecraft/org/getspout/spout/gui/ScreenUtil.java @@ -1,118 +1,121 @@ package org.getspout.spout.gui; import org.getspout.spout.client.SpoutClient; import org.getspout.spout.gui.settings.VideoSettings; import net.minecraft.src.GameSettings; import net.minecraft.src.GuiAchievements; import net.minecraft.src.GuiChat; import net.minecraft.src.GuiChest; import net.minecraft.src.GuiControls; import net.minecraft.src.GuiCrafting; import net.minecraft.src.GuiDispenser; import net.minecraft.src.GuiEditSign; import net.minecraft.src.GuiFurnace; import net.minecraft.src.GuiGameOver; import net.minecraft.src.GuiIngameMenu; import net.minecraft.src.GuiInventory; import net.minecraft.src.GuiOptions; import net.minecraft.src.GuiScreen; import net.minecraft.src.GuiSleepMP; import net.minecraft.src.GuiStats; import net.minecraft.src.StatFileWriter; import org.spoutcraft.spoutcraftapi.gui.*; public class ScreenUtil { public static void open(ScreenType type){ GuiScreen toOpen = null; GameSettings settings = SpoutClient.getHandle().gameSettings; StatFileWriter statfile = SpoutClient.getHandle().statFileWriter; switch(type) { case CHAT_SCREEN: toOpen = new GuiChat(); break; case SLEEP_SCREEN: toOpen = new GuiSleepMP(); break; case PLAYER_INVENTORY: toOpen = new GuiInventory(SpoutClient.getHandle().thePlayer); break; case INGAME_MENU: toOpen = new GuiIngameMenu(); break; case OPTIONS_MENU: toOpen = new GuiOptions(new GuiIngameMenu(), settings); break; case VIDEO_SETTINGS_MENU: toOpen = new VideoSettings(new GuiIngameMenu()); break; case CONTROLS_MENU: toOpen = new GuiControls(new GuiOptions(new GuiIngameMenu(), settings), settings); break; case ACHIEVEMENTS_SCREEN: toOpen = new GuiAchievements(statfile); break; case STATISTICS_SCREEN: toOpen = new GuiStats(new GuiIngameMenu(), statfile); break; case GAME_OVER_SCREEN: toOpen = new GuiGameOver(); break; } SpoutClient.getHandle().displayGuiScreen(toOpen); } public static ScreenType getType(GuiScreen gui) { ScreenType screen = ScreenType.UNKNOWN; + if(gui == null) { + screen = ScreenType.GAME_SCREEN; + } if (gui instanceof GuiChat) { screen = ScreenType.CHAT_SCREEN; } else if (gui instanceof GuiSleepMP) { screen = ScreenType.SLEEP_SCREEN; } else if (gui instanceof CustomScreen) { screen = ScreenType.CUSTOM_SCREEN; } else if (gui instanceof GuiInventory) { screen = ScreenType.PLAYER_INVENTORY; } else if (gui instanceof GuiChest) { screen = ScreenType.CHEST_INVENTORY; } else if (gui instanceof GuiDispenser) { screen = ScreenType.DISPENSER_INVENTORY; } else if (gui instanceof GuiFurnace) { screen = ScreenType.FURNACE_INVENTORY; } else if (gui instanceof GuiIngameMenu) { screen = ScreenType.INGAME_MENU; } else if (gui instanceof GuiOptions) { screen = ScreenType.OPTIONS_MENU; } else if (gui instanceof VideoSettings) { screen = ScreenType.VIDEO_SETTINGS_MENU; } else if (gui instanceof GuiControls) { screen = ScreenType.CONTROLS_MENU; } else if (gui instanceof GuiAchievements) { screen = ScreenType.ACHIEVEMENTS_SCREEN; } else if (gui instanceof GuiCrafting) { screen = ScreenType.WORKBENCH_INVENTORY; } else if (gui instanceof GuiGameOver) { screen = ScreenType.GAME_OVER_SCREEN; } else if (gui instanceof GuiEditSign) { screen = ScreenType.SIGN_SCREEN; } else if (gui instanceof GuiStats) { screen = ScreenType.STATISTICS_SCREEN; } return screen; } }
true
true
public static ScreenType getType(GuiScreen gui) { ScreenType screen = ScreenType.UNKNOWN; if (gui instanceof GuiChat) { screen = ScreenType.CHAT_SCREEN; } else if (gui instanceof GuiSleepMP) { screen = ScreenType.SLEEP_SCREEN; } else if (gui instanceof CustomScreen) { screen = ScreenType.CUSTOM_SCREEN; } else if (gui instanceof GuiInventory) { screen = ScreenType.PLAYER_INVENTORY; } else if (gui instanceof GuiChest) { screen = ScreenType.CHEST_INVENTORY; } else if (gui instanceof GuiDispenser) { screen = ScreenType.DISPENSER_INVENTORY; } else if (gui instanceof GuiFurnace) { screen = ScreenType.FURNACE_INVENTORY; } else if (gui instanceof GuiIngameMenu) { screen = ScreenType.INGAME_MENU; } else if (gui instanceof GuiOptions) { screen = ScreenType.OPTIONS_MENU; } else if (gui instanceof VideoSettings) { screen = ScreenType.VIDEO_SETTINGS_MENU; } else if (gui instanceof GuiControls) { screen = ScreenType.CONTROLS_MENU; } else if (gui instanceof GuiAchievements) { screen = ScreenType.ACHIEVEMENTS_SCREEN; } else if (gui instanceof GuiCrafting) { screen = ScreenType.WORKBENCH_INVENTORY; } else if (gui instanceof GuiGameOver) { screen = ScreenType.GAME_OVER_SCREEN; } else if (gui instanceof GuiEditSign) { screen = ScreenType.SIGN_SCREEN; } else if (gui instanceof GuiStats) { screen = ScreenType.STATISTICS_SCREEN; } return screen; }
public static ScreenType getType(GuiScreen gui) { ScreenType screen = ScreenType.UNKNOWN; if(gui == null) { screen = ScreenType.GAME_SCREEN; } if (gui instanceof GuiChat) { screen = ScreenType.CHAT_SCREEN; } else if (gui instanceof GuiSleepMP) { screen = ScreenType.SLEEP_SCREEN; } else if (gui instanceof CustomScreen) { screen = ScreenType.CUSTOM_SCREEN; } else if (gui instanceof GuiInventory) { screen = ScreenType.PLAYER_INVENTORY; } else if (gui instanceof GuiChest) { screen = ScreenType.CHEST_INVENTORY; } else if (gui instanceof GuiDispenser) { screen = ScreenType.DISPENSER_INVENTORY; } else if (gui instanceof GuiFurnace) { screen = ScreenType.FURNACE_INVENTORY; } else if (gui instanceof GuiIngameMenu) { screen = ScreenType.INGAME_MENU; } else if (gui instanceof GuiOptions) { screen = ScreenType.OPTIONS_MENU; } else if (gui instanceof VideoSettings) { screen = ScreenType.VIDEO_SETTINGS_MENU; } else if (gui instanceof GuiControls) { screen = ScreenType.CONTROLS_MENU; } else if (gui instanceof GuiAchievements) { screen = ScreenType.ACHIEVEMENTS_SCREEN; } else if (gui instanceof GuiCrafting) { screen = ScreenType.WORKBENCH_INVENTORY; } else if (gui instanceof GuiGameOver) { screen = ScreenType.GAME_OVER_SCREEN; } else if (gui instanceof GuiEditSign) { screen = ScreenType.SIGN_SCREEN; } else if (gui instanceof GuiStats) { screen = ScreenType.STATISTICS_SCREEN; } return screen; }
diff --git a/src/driver/GUIDriver.java b/src/driver/GUIDriver.java index 0852eef..b0dff77 100644 --- a/src/driver/GUIDriver.java +++ b/src/driver/GUIDriver.java @@ -1,375 +1,376 @@ package driver; import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.HashMap; import javax.swing.JFrame; import world.Character; import world.Enemy; import world.Grid; import world.GridSpace; import world.LivingThing; import world.RangedWeapon; import world.Terrain; import world.Thing; import world.Weapon; import world.World; public class GUIDriver { private static Grid g; private static long gravityRate; private static int lastKey; private static long hangTime; private static long value; private static int stage = 1; private static boolean keepGoing; public static void main(String[] args) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create canvas for painting... Canvas canvas = new Canvas(); canvas.setIgnoreRepaint(true); canvas.setSize(1200, 480); // Add canvas to game window... app.add(canvas); app.pack(); app.setVisible(true); // Create BackBuffer... canvas.createBufferStrategy(2); BufferStrategy buffer = canvas.getBufferStrategy(); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage(1200, 480); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long gravityTime = 0; long enemyDamageTime = 0; hangTime = 500; gravityRate = 300; value = gravityRate + hangTime; long curTime = System.currentTimeMillis(); long lastTime = curTime; keepGoing = true; g = new Grid(0); g.makeDefaultGrid(); Character casdfasdfasd = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(casdfasdfasd.getRangedStore()); System.out.println(casdfasdfasd.getCloseStore()); stage = 1; app.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid() .get(new Point((int) g.getCharacterLocation().getX(), (int) g.getCharacterLocation().getY() + 1)).hasSolid()) { g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); value = gravityRate + hangTime; } } else if (keyCode == KeyEvent.VK_LEFT) { g.moveCharacter(-1, 0, lastKey); lastKey = KeyEvent.VK_LEFT; } else if (keyCode == KeyEvent.VK_DOWN) { g.moveCharacter(0, 1, lastKey); } else if (keyCode == KeyEvent.VK_RIGHT) { g.moveCharacter(1, 0, lastKey); lastKey = KeyEvent.VK_RIGHT; } else if (keyCode == KeyEvent.VK_A) { lastKey = KeyEvent.VK_A; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_D) { lastKey = KeyEvent.VK_D; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_P) { String name = "Yo Mama"; Color c = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10)); } else { System.out.println("Could not spawn a new enemy."); } } else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon() instanceof RangedWeapon) { g.getGrid().get(g.getCharacterLocation()).returnCharacter() .setWeapon(g.getGrid().get(g.getCharacterLocation()).returnCharacter().getCloseStore()); } else { g.getGrid() .get(g.getCharacterLocation()) .returnCharacter() .setWeapon(g.getGrid().get(g.getCharacterLocation()).returnCharacter().getRangedStore()); } } else if (keyCode == KeyEvent.VK_SLASH) { g.killAllEnemies(); } else if (keyCode == KeyEvent.VK_SEMICOLON) { g.placeTerrain(keyCode); } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); } } }); while (keepGoing) { try { lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; gravityTime += curTime - lastTime; enemyDamageTime += curTime - lastTime; if (keepGoing) { if (gravityTime > value) { value += gravityRate; g.moveCharacter(0, 1, lastKey); for (int a = 0; a < 2; a++) { g.moveRangedWeapon(); } Point charLoc = g.getCharacterLocation(); ArrayList<Point> enemyLocs = g.getEnemyLocation(); for (int j = 0; j < enemyLocs.size(); j++) { if (charLoc.distance(enemyLocs.get(j)) <= 1) { keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy()); if (!keepGoing) { // System.exit(0); } } } if (keepGoing) { // check every instance of p for (int i = 0; i < g.getEnemyLocation().size(); i++) { Point p = g.getEnemyLocation().get(i); Point q = new Point((int) p.getX(), (int) p.getY() + 1); GridSpace gs = g.getGrid().get(q); if (p.getX() - g.getCharacterLocation().getX() > 0) { g.moveEnemy(-1, 0, p); } else { g.moveEnemy(1, 0, p); } if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() + 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() - 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } g.moveEnemy(0, 1, p); } if (gravityTime > 4 * gravityRate + hangTime) { gravityTime = 0; value = gravityRate + hangTime; } if (enemyDamageTime > 500) { } // clear back buffer... if (g.getCharacterLocation().getX() >= 100) { HashMap<Point, GridSpace> grid = g.getGrid(); Point oldLocation = g.getCharacterLocation(); Character c = grid.get(oldLocation).returnCharacter(); - c.setHp(20); + c.setHp(c.getMaxHp()); World w = new World(); int killed = g.getNumKilled(); g = w.drawWorld(1, killed); stage++; grid = g.getGrid(); g.setNumKilled(killed); ArrayList<Thing> t = new ArrayList<Thing>(); t.add(c); GridSpace gs = new GridSpace(t); gs.sortArrayOfThings(); grid.put(new Point(0, (int) oldLocation.getY()), gs); g.setCharacterLocation(new Point(0, (int) oldLocation.getY())); } } } } if (totalTime > 1000) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, 639, 479); HashMap<Point, GridSpace> grid = g.getGrid(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 25; j++) { g2d.setColor(grid.get(new Point(i, j)).getColor()); g2d.fillRect(i * 10, j * 10, 10, 10); } } // display frames per second... g2d.setFont(new Font("Courier New", Font.PLAIN, 12)); g2d.setColor(Color.GREEN); g2d.drawString(String.format("FPS: %s", fps), 20, 20); g2d.drawString(String.format("Stage: %s", stage), 100, 20); g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20); if (keepGoing) { try { if ((g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon()) instanceof RangedWeapon) { g2d.drawString("Current weapon: Bow", 640, 20); } else if ((g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon()) instanceof Weapon) { g2d.drawString("Current weapon: Sword", 640, 20); } } catch (NullPointerException e) { System.out.println("Caught null pointer error on HUD for weapon."); } catch (ConcurrentModificationException c) { System.out.println("Caught concurrent modification exception."); } try { Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); + g2d.drawString("Current level: " + c.getLevel(), 840, 20); String healthString = ""; for (int i = 0; i < c.getMaxHp(); i += 5) { if (c.getHp() > i) { healthString += "* "; } else { healthString += "_ "; } } g2d.drawString(healthString, 320, 20); } catch (NullPointerException e) { System.out.println("Caught that error"); g2d.drawString("Health: Dead", 320, 20); } } // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!buffer.contentsLost()) { buffer.show(); } // Let the OS have a little time... Thread.yield(); } finally { // release resources if (graphics != null) graphics.dispose(); if (g2d != null) g2d.dispose(); } } } }
false
true
public static void main(String[] args) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create canvas for painting... Canvas canvas = new Canvas(); canvas.setIgnoreRepaint(true); canvas.setSize(1200, 480); // Add canvas to game window... app.add(canvas); app.pack(); app.setVisible(true); // Create BackBuffer... canvas.createBufferStrategy(2); BufferStrategy buffer = canvas.getBufferStrategy(); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage(1200, 480); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long gravityTime = 0; long enemyDamageTime = 0; hangTime = 500; gravityRate = 300; value = gravityRate + hangTime; long curTime = System.currentTimeMillis(); long lastTime = curTime; keepGoing = true; g = new Grid(0); g.makeDefaultGrid(); Character casdfasdfasd = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(casdfasdfasd.getRangedStore()); System.out.println(casdfasdfasd.getCloseStore()); stage = 1; app.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid() .get(new Point((int) g.getCharacterLocation().getX(), (int) g.getCharacterLocation().getY() + 1)).hasSolid()) { g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); value = gravityRate + hangTime; } } else if (keyCode == KeyEvent.VK_LEFT) { g.moveCharacter(-1, 0, lastKey); lastKey = KeyEvent.VK_LEFT; } else if (keyCode == KeyEvent.VK_DOWN) { g.moveCharacter(0, 1, lastKey); } else if (keyCode == KeyEvent.VK_RIGHT) { g.moveCharacter(1, 0, lastKey); lastKey = KeyEvent.VK_RIGHT; } else if (keyCode == KeyEvent.VK_A) { lastKey = KeyEvent.VK_A; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_D) { lastKey = KeyEvent.VK_D; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_P) { String name = "Yo Mama"; Color c = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10)); } else { System.out.println("Could not spawn a new enemy."); } } else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon() instanceof RangedWeapon) { g.getGrid().get(g.getCharacterLocation()).returnCharacter() .setWeapon(g.getGrid().get(g.getCharacterLocation()).returnCharacter().getCloseStore()); } else { g.getGrid() .get(g.getCharacterLocation()) .returnCharacter() .setWeapon(g.getGrid().get(g.getCharacterLocation()).returnCharacter().getRangedStore()); } } else if (keyCode == KeyEvent.VK_SLASH) { g.killAllEnemies(); } else if (keyCode == KeyEvent.VK_SEMICOLON) { g.placeTerrain(keyCode); } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); } } }); while (keepGoing) { try { lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; gravityTime += curTime - lastTime; enemyDamageTime += curTime - lastTime; if (keepGoing) { if (gravityTime > value) { value += gravityRate; g.moveCharacter(0, 1, lastKey); for (int a = 0; a < 2; a++) { g.moveRangedWeapon(); } Point charLoc = g.getCharacterLocation(); ArrayList<Point> enemyLocs = g.getEnemyLocation(); for (int j = 0; j < enemyLocs.size(); j++) { if (charLoc.distance(enemyLocs.get(j)) <= 1) { keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy()); if (!keepGoing) { // System.exit(0); } } } if (keepGoing) { // check every instance of p for (int i = 0; i < g.getEnemyLocation().size(); i++) { Point p = g.getEnemyLocation().get(i); Point q = new Point((int) p.getX(), (int) p.getY() + 1); GridSpace gs = g.getGrid().get(q); if (p.getX() - g.getCharacterLocation().getX() > 0) { g.moveEnemy(-1, 0, p); } else { g.moveEnemy(1, 0, p); } if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() + 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() - 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } g.moveEnemy(0, 1, p); } if (gravityTime > 4 * gravityRate + hangTime) { gravityTime = 0; value = gravityRate + hangTime; } if (enemyDamageTime > 500) { } // clear back buffer... if (g.getCharacterLocation().getX() >= 100) { HashMap<Point, GridSpace> grid = g.getGrid(); Point oldLocation = g.getCharacterLocation(); Character c = grid.get(oldLocation).returnCharacter(); c.setHp(20); World w = new World(); int killed = g.getNumKilled(); g = w.drawWorld(1, killed); stage++; grid = g.getGrid(); g.setNumKilled(killed); ArrayList<Thing> t = new ArrayList<Thing>(); t.add(c); GridSpace gs = new GridSpace(t); gs.sortArrayOfThings(); grid.put(new Point(0, (int) oldLocation.getY()), gs); g.setCharacterLocation(new Point(0, (int) oldLocation.getY())); } } } } if (totalTime > 1000) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, 639, 479); HashMap<Point, GridSpace> grid = g.getGrid(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 25; j++) { g2d.setColor(grid.get(new Point(i, j)).getColor()); g2d.fillRect(i * 10, j * 10, 10, 10); } } // display frames per second... g2d.setFont(new Font("Courier New", Font.PLAIN, 12)); g2d.setColor(Color.GREEN); g2d.drawString(String.format("FPS: %s", fps), 20, 20); g2d.drawString(String.format("Stage: %s", stage), 100, 20); g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20); if (keepGoing) { try { if ((g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon()) instanceof RangedWeapon) { g2d.drawString("Current weapon: Bow", 640, 20); } else if ((g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon()) instanceof Weapon) { g2d.drawString("Current weapon: Sword", 640, 20); } } catch (NullPointerException e) { System.out.println("Caught null pointer error on HUD for weapon."); } catch (ConcurrentModificationException c) { System.out.println("Caught concurrent modification exception."); } try { Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); String healthString = ""; for (int i = 0; i < c.getMaxHp(); i += 5) { if (c.getHp() > i) { healthString += "* "; } else { healthString += "_ "; } } g2d.drawString(healthString, 320, 20); } catch (NullPointerException e) { System.out.println("Caught that error"); g2d.drawString("Health: Dead", 320, 20); } } // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!buffer.contentsLost()) { buffer.show(); } // Let the OS have a little time... Thread.yield(); } finally { // release resources if (graphics != null) graphics.dispose(); if (g2d != null) g2d.dispose(); } } }
public static void main(String[] args) { // Create game window... JFrame app = new JFrame(); app.setIgnoreRepaint(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create canvas for painting... Canvas canvas = new Canvas(); canvas.setIgnoreRepaint(true); canvas.setSize(1200, 480); // Add canvas to game window... app.add(canvas); app.pack(); app.setVisible(true); // Create BackBuffer... canvas.createBufferStrategy(2); BufferStrategy buffer = canvas.getBufferStrategy(); // Get graphics configuration... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); // Create off-screen drawing surface BufferedImage bi = gc.createCompatibleImage(1200, 480); // Objects needed for rendering... Graphics graphics = null; Graphics2D g2d = null; Color background = Color.BLACK; // Variables for counting frames per seconds int fps = 0; int frames = 0; long totalTime = 0; long gravityTime = 0; long enemyDamageTime = 0; hangTime = 500; gravityRate = 300; value = gravityRate + hangTime; long curTime = System.currentTimeMillis(); long lastTime = curTime; keepGoing = true; g = new Grid(0); g.makeDefaultGrid(); Character casdfasdfasd = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); System.out.println(casdfasdfasd.getRangedStore()); System.out.println(casdfasdfasd.getCloseStore()); stage = 1; app.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid() .get(new Point((int) g.getCharacterLocation().getX(), (int) g.getCharacterLocation().getY() + 1)).hasSolid()) { g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); g.moveCharacter(0, -1, lastKey); value = gravityRate + hangTime; } } else if (keyCode == KeyEvent.VK_LEFT) { g.moveCharacter(-1, 0, lastKey); lastKey = KeyEvent.VK_LEFT; } else if (keyCode == KeyEvent.VK_DOWN) { g.moveCharacter(0, 1, lastKey); } else if (keyCode == KeyEvent.VK_RIGHT) { g.moveCharacter(1, 0, lastKey); lastKey = KeyEvent.VK_RIGHT; } else if (keyCode == KeyEvent.VK_A) { lastKey = KeyEvent.VK_A; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_D) { lastKey = KeyEvent.VK_D; g.useWeapon(lastKey); } else if (keyCode == KeyEvent.VK_P) { String name = "Yo Mama"; Color c = Color.ORANGE; Point p = g.findValidEnemyLocation(); if (p != null) { g.spawnNewEnemy(p, new Enemy(true, c, name, 10, 10, 10)); } else { System.out.println("Could not spawn a new enemy."); } } else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); if (g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon() instanceof RangedWeapon) { g.getGrid().get(g.getCharacterLocation()).returnCharacter() .setWeapon(g.getGrid().get(g.getCharacterLocation()).returnCharacter().getCloseStore()); } else { g.getGrid() .get(g.getCharacterLocation()) .returnCharacter() .setWeapon(g.getGrid().get(g.getCharacterLocation()).returnCharacter().getRangedStore()); } } else if (keyCode == KeyEvent.VK_SLASH) { g.killAllEnemies(); } else if (keyCode == KeyEvent.VK_SEMICOLON) { g.placeTerrain(keyCode); } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) { g.retractWeapon(KeyEvent.VK_A); g.retractWeapon(KeyEvent.VK_D); } } }); while (keepGoing) { try { lastTime = curTime; curTime = System.currentTimeMillis(); totalTime += curTime - lastTime; gravityTime += curTime - lastTime; enemyDamageTime += curTime - lastTime; if (keepGoing) { if (gravityTime > value) { value += gravityRate; g.moveCharacter(0, 1, lastKey); for (int a = 0; a < 2; a++) { g.moveRangedWeapon(); } Point charLoc = g.getCharacterLocation(); ArrayList<Point> enemyLocs = g.getEnemyLocation(); for (int j = 0; j < enemyLocs.size(); j++) { if (charLoc.distance(enemyLocs.get(j)) <= 1) { keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy()); if (!keepGoing) { // System.exit(0); } } } if (keepGoing) { // check every instance of p for (int i = 0; i < g.getEnemyLocation().size(); i++) { Point p = g.getEnemyLocation().get(i); Point q = new Point((int) p.getX(), (int) p.getY() + 1); GridSpace gs = g.getGrid().get(q); if (p.getX() - g.getCharacterLocation().getX() > 0) { g.moveEnemy(-1, 0, p); } else { g.moveEnemy(1, 0, p); } if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() + 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) { Point check = new Point((int) (p.getX() - 1), (int) (p.getY())); GridSpace more = g.getGrid().get(check); if (more.hasSolid()) { for (Terrain t : more.returnTerrain()) { if (t.getSolid()) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } for (LivingThing e : more.returnLivingThings()) { if (e.getSolid() && !(e instanceof Character)) { g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); g.moveEnemy(0, -1, p); } } } } g.moveEnemy(0, 1, p); } if (gravityTime > 4 * gravityRate + hangTime) { gravityTime = 0; value = gravityRate + hangTime; } if (enemyDamageTime > 500) { } // clear back buffer... if (g.getCharacterLocation().getX() >= 100) { HashMap<Point, GridSpace> grid = g.getGrid(); Point oldLocation = g.getCharacterLocation(); Character c = grid.get(oldLocation).returnCharacter(); c.setHp(c.getMaxHp()); World w = new World(); int killed = g.getNumKilled(); g = w.drawWorld(1, killed); stage++; grid = g.getGrid(); g.setNumKilled(killed); ArrayList<Thing> t = new ArrayList<Thing>(); t.add(c); GridSpace gs = new GridSpace(t); gs.sortArrayOfThings(); grid.put(new Point(0, (int) oldLocation.getY()), gs); g.setCharacterLocation(new Point(0, (int) oldLocation.getY())); } } } } if (totalTime > 1000) { totalTime -= 1000; fps = frames; frames = 0; } ++frames; g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, 639, 479); HashMap<Point, GridSpace> grid = g.getGrid(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 25; j++) { g2d.setColor(grid.get(new Point(i, j)).getColor()); g2d.fillRect(i * 10, j * 10, 10, 10); } } // display frames per second... g2d.setFont(new Font("Courier New", Font.PLAIN, 12)); g2d.setColor(Color.GREEN); g2d.drawString(String.format("FPS: %s", fps), 20, 20); g2d.drawString(String.format("Stage: %s", stage), 100, 20); g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20); if (keepGoing) { try { if ((g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon()) instanceof RangedWeapon) { g2d.drawString("Current weapon: Bow", 640, 20); } else if ((g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon()) instanceof Weapon) { g2d.drawString("Current weapon: Sword", 640, 20); } } catch (NullPointerException e) { System.out.println("Caught null pointer error on HUD for weapon."); } catch (ConcurrentModificationException c) { System.out.println("Caught concurrent modification exception."); } try { Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter(); g2d.drawString("Current level: " + c.getLevel(), 840, 20); String healthString = ""; for (int i = 0; i < c.getMaxHp(); i += 5) { if (c.getHp() > i) { healthString += "* "; } else { healthString += "_ "; } } g2d.drawString(healthString, 320, 20); } catch (NullPointerException e) { System.out.println("Caught that error"); g2d.drawString("Health: Dead", 320, 20); } } // Blit image and flip... graphics = buffer.getDrawGraphics(); graphics.drawImage(bi, 0, 0, null); if (!buffer.contentsLost()) { buffer.show(); } // Let the OS have a little time... Thread.yield(); } finally { // release resources if (graphics != null) graphics.dispose(); if (g2d != null) g2d.dispose(); } } }
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java index 7d1614163..1222e77d8 100644 --- a/src/com/android/settings/wifi/WifiSettings.java +++ b/src/com/android/settings/wifi/WifiSettings.java @@ -1,743 +1,745 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.wifi; import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID; import com.android.settings.ProgressCategoryBase; import com.android.settings.R; import com.android.settings.SettingsPreferenceFragment; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.DetailedState; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WpsResult; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WpsConfiguration; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.ListPreference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.provider.Settings.Secure; import android.provider.Settings; import android.security.Credentials; import android.security.KeyStore; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * This currently provides three types of UI. * * Two are for phones with relatively small screens: "for SetupWizard" and "for usual Settings". * Users just need to launch WifiSettings Activity as usual. The request will be appropriately * handled by ActivityManager, and they will have appropriate look-and-feel with this fragment. * * Third type is for Setup Wizard with X-Large, landscape UI. Users need to launch * {@link WifiSettingsForSetupWizardXL} Activity, which contains this fragment but also has * other decorations specific to that screen. */ public class WifiSettings extends SettingsPreferenceFragment implements DialogInterface.OnClickListener, Preference.OnPreferenceChangeListener { private static final int MENU_ID_SCAN = Menu.FIRST; private static final int MENU_ID_ADVANCED = Menu.FIRST + 1; private static final int MENU_ID_CONNECT = Menu.FIRST + 2; private static final int MENU_ID_FORGET = Menu.FIRST + 3; private static final int MENU_ID_MODIFY = Menu.FIRST + 4; private static final String KEY_SLEEP_POLICY = "sleep_policy"; private final IntentFilter mFilter; private final BroadcastReceiver mReceiver; private final Scanner mScanner; private WifiManager mWifiManager; private WifiEnabler mWifiEnabler; private CheckBoxPreference mNotifyOpenNetworks; private ProgressCategoryBase mAccessPoints; private Preference mAddNetwork; // An access point being editted is stored here. private AccessPoint mSelectedAccessPoint; private boolean mEdit; private DetailedState mLastState; private WifiInfo mLastInfo; private AtomicBoolean mConnected = new AtomicBoolean(false); private int mKeyStoreNetworkId = INVALID_NETWORK_ID; private WifiDialog mDialog; /* Used in Wifi Setup context */ // this boolean extra specifies whether to disable the Next button when not connected private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; // should Next button only be enabled when we have a connection? private boolean mEnableNextOnConnection; private boolean mInXlSetupWizard; /* End of "used in Wifi Setup context" */ public WifiSettings() { mFilter = new IntentFilter(); mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION); mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); mFilter.addAction(WifiManager.ERROR_ACTION); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { handleEvent(context, intent); } }; mScanner = new Scanner(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mInXlSetupWizard = (activity instanceof WifiSettingsForSetupWizardXL); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (mInXlSetupWizard) { return inflater.inflate(R.layout.custom_preference_list_fragment, container, false); } else { return super.onCreateView(inflater, container, savedInstanceState); } } @Override public void onActivityCreated(Bundle savedInstanceState) { // We don't call super.onActivityCreated() here, since it assumes we already set up // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in // this method. mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); final Activity activity = getActivity(); final Intent intent = activity.getIntent(); // if we're supposed to enable/disable the Next button based on our current connection // state, start it off in the right state mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); // Avoid re-adding on returning from an overlapping activity/fragment. if (getPreferenceScreen() == null || getPreferenceScreen().getPreferenceCount() < 2) { if (mEnableNextOnConnection) { if (hasNextButton()) { final ConnectivityManager connectivity = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getNetworkInfo( ConnectivityManager.TYPE_WIFI); changeNextButtonState(info.isConnected()); } } } if (mInXlSetupWizard) { addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl); } else if (intent.getBooleanExtra("only_access_points", false)) { addPreferencesFromResource(R.xml.wifi_access_points); } else { addPreferencesFromResource(R.xml.wifi_settings); mWifiEnabler = new WifiEnabler(activity, (CheckBoxPreference) findPreference("enable_wifi")); mNotifyOpenNetworks = (CheckBoxPreference) findPreference("notify_open_networks"); mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); } // This may be either ProgressCategory or AccessPointCategoryForXL. final ProgressCategoryBase preference = (ProgressCategoryBase) findPreference("access_points"); mAccessPoints = preference; mAccessPoints.setOrderingAsAdded(false); mAddNetwork = findPreference("add_network"); ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY); - pref.setOnPreferenceChangeListener(this); - int value = Settings.System.getInt(getContentResolver(), - Settings.System.WIFI_SLEEP_POLICY, - Settings.System.WIFI_SLEEP_POLICY_NEVER); - pref.setValue(String.valueOf(value)); + if (pref != null) { + pref.setOnPreferenceChangeListener(this); + int value = Settings.System.getInt(getContentResolver(), + Settings.System.WIFI_SLEEP_POLICY, + Settings.System.WIFI_SLEEP_POLICY_NEVER); + pref.setValue(String.valueOf(value)); + } registerForContextMenu(getListView()); setHasOptionsMenu(true); } // After confirming PreferenceScreen is available, we call super. super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); if (mWifiEnabler != null) { mWifiEnabler.resume(); } getActivity().registerReceiver(mReceiver, mFilter); if (mKeyStoreNetworkId != INVALID_NETWORK_ID && KeyStore.getInstance().test() == KeyStore.NO_ERROR) { mWifiManager.connectNetwork(mKeyStoreNetworkId); } mKeyStoreNetworkId = INVALID_NETWORK_ID; updateAccessPoints(); } @Override public void onPause() { super.onPause(); if (mWifiEnabler != null) { mWifiEnabler.pause(); } getActivity().unregisterReceiver(mReceiver); mScanner.pause(); if (mDialog != null) { mDialog.dismiss(); mDialog = null; } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // We don't want menus in Setup Wizard XL. if (!mInXlSetupWizard) { menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan) .setIcon(R.drawable.ic_menu_scan_network); menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) .setIcon(android.R.drawable.ic_menu_manage); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ID_SCAN: if (mWifiManager.isWifiEnabled()) { mScanner.forceScan(); } return true; case MENU_ID_ADVANCED: if (getActivity() instanceof PreferenceActivity) { ((PreferenceActivity) getActivity()).startPreferencePanel( AdvancedSettings.class.getCanonicalName(), null, R.string.wifi_advanced_titlebar, null, this, 0); } else { startFragment(this, AdvancedSettings.class.getCanonicalName(), -1, null); } return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).onCreateContextMenu(menu, view, info); } else if (info instanceof AdapterContextMenuInfo) { Preference preference = (Preference) getListView().getItemAtPosition( ((AdapterContextMenuInfo) info).position); if (preference instanceof AccessPoint) { mSelectedAccessPoint = (AccessPoint) preference; menu.setHeaderTitle(mSelectedAccessPoint.ssid); if (mSelectedAccessPoint.getLevel() != -1 && mSelectedAccessPoint.getState() == null) { menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); } if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); } } } } @Override public boolean onContextItemSelected(MenuItem item) { if (mSelectedAccessPoint == null) { return super.onContextItemSelected(item); } switch (item.getItemId()) { case MENU_ID_CONNECT: { if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { if (!requireKeyStore(mSelectedAccessPoint.getConfig())) { mWifiManager.connectNetwork(mSelectedAccessPoint.networkId); } } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) { // Shortcut for open networks. WifiConfiguration config = new WifiConfiguration(); config.SSID = AccessPoint.convertToQuotedString(mSelectedAccessPoint.ssid); config.allowedKeyManagement.set(KeyMgmt.NONE); mWifiManager.connectNetwork(config); } else { showConfigUi(mSelectedAccessPoint, true); } return true; } case MENU_ID_FORGET: { mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId); return true; } case MENU_ID_MODIFY: { showConfigUi(mSelectedAccessPoint, true); return true; } } return super.onContextItemSelected(item); } @Override public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { if (preference instanceof AccessPoint) { mSelectedAccessPoint = (AccessPoint) preference; showConfigUi(mSelectedAccessPoint, false); } else if (preference == mAddNetwork) { onAddNetworkPressed(); } else if (preference == mNotifyOpenNetworks) { Secure.putInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, mNotifyOpenNetworks.isChecked() ? 1 : 0); } else { return super.onPreferenceTreeClick(screen, preference); } return true; } public boolean onPreferenceChange(Preference preference, Object newValue) { String key = preference.getKey(); if (key == null) return true; if (key.equals(KEY_SLEEP_POLICY)) { try { Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Integer.parseInt(((String) newValue))); } catch (NumberFormatException e) { Toast.makeText(getActivity(), R.string.wifi_setting_sleep_policy_error, Toast.LENGTH_SHORT).show(); return false; } } return true; } /** * Shows an appropriate Wifi configuration component. * Called when a user clicks "Add network" preference or one of available networks is selected. */ private void showConfigUi(AccessPoint accessPoint, boolean edit) { mEdit = edit; if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).showConfigUi(accessPoint, edit); } else { showDialog(accessPoint, edit); } } private void showDialog(AccessPoint accessPoint, boolean edit) { if (mDialog != null) { mDialog.dismiss(); } mDialog = new WifiDialog(getActivity(), this, accessPoint, edit); mDialog.show(); } private boolean requireKeyStore(WifiConfiguration config) { if (WifiConfigController.requireKeyStore(config) && KeyStore.getInstance().test() != KeyStore.NO_ERROR) { mKeyStoreNetworkId = config.networkId; Credentials.getInstance().unlock(getActivity()); return true; } return false; } /** * Shows the latest access points available with supplimental information like * the strength of network and the security for it. */ private void updateAccessPoints() { mAccessPoints.removeAll(); // AccessPoints are automatically sorted with TreeSet. final Collection<AccessPoint> accessPoints = constructAccessPoints(); if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).onAccessPointsUpdated( mAccessPoints, accessPoints); } else { for (AccessPoint accessPoint : accessPoints) { mAccessPoints.addPreference(accessPoint); } } } private Collection<AccessPoint> constructAccessPoints() { Collection<AccessPoint> accessPoints = new ArrayList<AccessPoint>(); final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); if (configs != null) { for (WifiConfiguration config : configs) { AccessPoint accessPoint = new AccessPoint(getActivity(), config); accessPoint.update(mLastInfo, mLastState); accessPoints.add(accessPoint); } } final List<ScanResult> results = mWifiManager.getScanResults(); if (results != null) { for (ScanResult result : results) { // Ignore hidden and ad-hoc networks. if (result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]")) { continue; } boolean found = false; for (AccessPoint accessPoint : accessPoints) { if (accessPoint.update(result)) { found = true; } } if (!found) { accessPoints.add(new AccessPoint(getActivity(), result)); } } } return accessPoints; } private void handleEvent(Context context, Intent intent) { String action = intent.getAction(); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)); } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) || WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) || WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) { updateAccessPoints(); } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) { //Ignore supplicant state changes when network is connected //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and //introduce a broadcast that combines the supplicant and network //network state change events so the apps dont have to worry about //ignoring supplicant state change when network is connected //to get more fine grained information. if (!mConnected.get()) { updateConnectionState(WifiInfo.getDetailedStateOf((SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE))); } if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).onSupplicantStateChanged(intent); } } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( WifiManager.EXTRA_NETWORK_INFO); mConnected.set(info.isConnected()); changeNextButtonState(info.isConnected()); updateConnectionState(info.getDetailedState()); } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) { updateConnectionState(null); } else if (WifiManager.ERROR_ACTION.equals(action)) { int errorCode = intent.getIntExtra(WifiManager.EXTRA_ERROR_CODE, 0); switch (errorCode) { case WifiManager.WPS_OVERLAP_ERROR: Toast.makeText(context, R.string.wifi_wps_overlap_error, Toast.LENGTH_SHORT).show(); break; } } } private void updateConnectionState(DetailedState state) { /* sticky broadcasts can call this when wifi is disabled */ if (!mWifiManager.isWifiEnabled()) { mScanner.pause(); return; } if (state == DetailedState.OBTAINING_IPADDR) { mScanner.pause(); } else { mScanner.resume(); } mLastInfo = mWifiManager.getConnectionInfo(); if (state != null) { mLastState = state; } for (int i = mAccessPoints.getPreferenceCount() - 1; i >= 0; --i) { // Maybe there's a WifiConfigPreference Preference preference = mAccessPoints.getPreference(i); if (preference instanceof AccessPoint) { final AccessPoint accessPoint = (AccessPoint) preference; accessPoint.update(mLastInfo, mLastState); } } if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).updateConnectionState(mLastState); } } private void updateWifiState(int state) { if (state == WifiManager.WIFI_STATE_ENABLED) { mScanner.resume(); } else { mScanner.pause(); mAccessPoints.removeAll(); } } private class Scanner extends Handler { private int mRetry = 0; void resume() { if (!hasMessages(0)) { sendEmptyMessage(0); } } void forceScan() { sendEmptyMessage(0); } void pause() { mRetry = 0; mAccessPoints.setProgress(false); removeMessages(0); } @Override public void handleMessage(Message message) { if (mWifiManager.startScanActive()) { mRetry = 0; } else if (++mRetry >= 3) { mRetry = 0; Toast.makeText(getActivity(), R.string.wifi_fail_to_scan, Toast.LENGTH_LONG).show(); return; } mAccessPoints.setProgress(mRetry != 0); // Combo scans can take 5-6s to complete. Increase interval to 10s. sendEmptyMessageDelayed(0, 10000); } } /** * Renames/replaces "Next" button when appropriate. "Next" button usually exists in * Wifi setup screens, not in usual wifi settings screen. * * @param connected true when the device is connected to a wifi network. */ private void changeNextButtonState(boolean connected) { if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).changeNextButtonState(connected); } else if (mEnableNextOnConnection && hasNextButton()) { getNextButton().setEnabled(connected); } } public void onClick(DialogInterface dialogInterface, int button) { if (mInXlSetupWizard) { if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { forget(); } else if (button == WifiDialog.BUTTON_SUBMIT) { ((WifiSettingsForSetupWizardXL)getActivity()).onConnectButtonPressed(); } } else { if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { forget(); } else if (button == WifiDialog.BUTTON_SUBMIT) { submit(mDialog.getController()); } } } /* package */ void submit(WifiConfigController configController) { int networkSetup = configController.chosenNetworkSetupMethod(); switch(networkSetup) { case WifiConfigController.WPS_PBC: case WifiConfigController.WPS_PIN_FROM_ACCESS_POINT: case WifiConfigController.WPS_PIN_FROM_DEVICE: WpsResult result = mWifiManager.startWps(configController.getWpsConfig()); AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.wifi_wps_setup_title) .setPositiveButton(android.R.string.ok, null); switch (result.status) { case FAILURE: dialog.setMessage(R.string.wifi_wps_failed); dialog.show(); break; case IN_PROGRESS: dialog.setMessage(R.string.wifi_wps_in_progress); dialog.show(); break; default: if (networkSetup == WifiConfigController.WPS_PIN_FROM_DEVICE) { dialog.setMessage(getResources().getString(R.string.wifi_wps_pin_output, result.pin)); dialog.show(); } break; } break; case WifiConfigController.MANUAL: final WifiConfiguration config = configController.getConfig(); if (config == null) { if (mSelectedAccessPoint != null && !requireKeyStore(mSelectedAccessPoint.getConfig()) && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { mWifiManager.connectNetwork(mSelectedAccessPoint.networkId); } } else if (config.networkId != INVALID_NETWORK_ID) { if (mSelectedAccessPoint != null) { saveNetwork(config); } } else { if (configController.isEdit() || requireKeyStore(config)) { saveNetwork(config); } else { mWifiManager.connectNetwork(config); } } break; } if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } updateAccessPoints(); } private void saveNetwork(WifiConfiguration config) { if (mInXlSetupWizard) { ((WifiSettingsForSetupWizardXL)getActivity()).onSaveNetwork(config); } else { mWifiManager.saveNetwork(config); } } /* package */ void forget() { mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId); if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } updateAccessPoints(); // We need to rename/replace "Next" button in wifi setup context. changeNextButtonState(false); } /** * Refreshes acccess points and ask Wifi module to scan networks again. */ /* package */ void refreshAccessPoints() { if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } mAccessPoints.removeAll(); } /** * Called when "add network" button is pressed. */ /* package */ void onAddNetworkPressed() { // No exact access point is selected. mSelectedAccessPoint = null; showConfigUi(null, true); } /* package */ int getAccessPointsCount() { if (mAccessPoints != null) { return mAccessPoints.getPreferenceCount(); } else { return 0; } } /** * Requests wifi module to pause wifi scan. May be ignored when the module is disabled. */ /* package */ void pauseWifiScan() { if (mWifiManager.isWifiEnabled()) { mScanner.pause(); } } /** * Requests wifi module to resume wifi scan. May be ignored when the module is disabled. */ /* package */ void resumeWifiScan() { if (mWifiManager.isWifiEnabled()) { mScanner.resume(); } } }
true
true
public void onActivityCreated(Bundle savedInstanceState) { // We don't call super.onActivityCreated() here, since it assumes we already set up // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in // this method. mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); final Activity activity = getActivity(); final Intent intent = activity.getIntent(); // if we're supposed to enable/disable the Next button based on our current connection // state, start it off in the right state mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); // Avoid re-adding on returning from an overlapping activity/fragment. if (getPreferenceScreen() == null || getPreferenceScreen().getPreferenceCount() < 2) { if (mEnableNextOnConnection) { if (hasNextButton()) { final ConnectivityManager connectivity = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getNetworkInfo( ConnectivityManager.TYPE_WIFI); changeNextButtonState(info.isConnected()); } } } if (mInXlSetupWizard) { addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl); } else if (intent.getBooleanExtra("only_access_points", false)) { addPreferencesFromResource(R.xml.wifi_access_points); } else { addPreferencesFromResource(R.xml.wifi_settings); mWifiEnabler = new WifiEnabler(activity, (CheckBoxPreference) findPreference("enable_wifi")); mNotifyOpenNetworks = (CheckBoxPreference) findPreference("notify_open_networks"); mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); } // This may be either ProgressCategory or AccessPointCategoryForXL. final ProgressCategoryBase preference = (ProgressCategoryBase) findPreference("access_points"); mAccessPoints = preference; mAccessPoints.setOrderingAsAdded(false); mAddNetwork = findPreference("add_network"); ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY); pref.setOnPreferenceChangeListener(this); int value = Settings.System.getInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); pref.setValue(String.valueOf(value)); registerForContextMenu(getListView()); setHasOptionsMenu(true); } // After confirming PreferenceScreen is available, we call super. super.onActivityCreated(savedInstanceState); }
public void onActivityCreated(Bundle savedInstanceState) { // We don't call super.onActivityCreated() here, since it assumes we already set up // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in // this method. mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); final Activity activity = getActivity(); final Intent intent = activity.getIntent(); // if we're supposed to enable/disable the Next button based on our current connection // state, start it off in the right state mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); // Avoid re-adding on returning from an overlapping activity/fragment. if (getPreferenceScreen() == null || getPreferenceScreen().getPreferenceCount() < 2) { if (mEnableNextOnConnection) { if (hasNextButton()) { final ConnectivityManager connectivity = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getNetworkInfo( ConnectivityManager.TYPE_WIFI); changeNextButtonState(info.isConnected()); } } } if (mInXlSetupWizard) { addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl); } else if (intent.getBooleanExtra("only_access_points", false)) { addPreferencesFromResource(R.xml.wifi_access_points); } else { addPreferencesFromResource(R.xml.wifi_settings); mWifiEnabler = new WifiEnabler(activity, (CheckBoxPreference) findPreference("enable_wifi")); mNotifyOpenNetworks = (CheckBoxPreference) findPreference("notify_open_networks"); mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); } // This may be either ProgressCategory or AccessPointCategoryForXL. final ProgressCategoryBase preference = (ProgressCategoryBase) findPreference("access_points"); mAccessPoints = preference; mAccessPoints.setOrderingAsAdded(false); mAddNetwork = findPreference("add_network"); ListPreference pref = (ListPreference) findPreference(KEY_SLEEP_POLICY); if (pref != null) { pref.setOnPreferenceChangeListener(this); int value = Settings.System.getInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); pref.setValue(String.valueOf(value)); } registerForContextMenu(getListView()); setHasOptionsMenu(true); } // After confirming PreferenceScreen is available, we call super. super.onActivityCreated(savedInstanceState); }
diff --git a/src/nu/validator/htmlparser/test/TreePrinter.java b/src/nu/validator/htmlparser/test/TreePrinter.java index 8d095cb..d970621 100644 --- a/src/nu/validator/htmlparser/test/TreePrinter.java +++ b/src/nu/validator/htmlparser/test/TreePrinter.java @@ -1,47 +1,48 @@ /* * Copyright (c) 2007 Henri Sivonen * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package nu.validator.htmlparser.test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import nu.validator.htmlparser.sax.HtmlParser; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class TreePrinter { public static void main(String[] args) throws SAXException, IOException { TreeDumpContentHandler treeDumpContentHandler = new TreeDumpContentHandler(new OutputStreamWriter(System.out, "UTF-8")); HtmlParser htmlParser = new HtmlParser(); htmlParser.setContentHandler(treeDumpContentHandler); htmlParser.setLexicalHandler(treeDumpContentHandler); + htmlParser.setErrorHandler(new SystemErrErrorHandler()); File file = new File(args[0]); InputSource is = new InputSource(new FileInputStream(file)); is.setSystemId(file.toURI().toASCIIString()); htmlParser.parse(is); } }
true
true
public static void main(String[] args) throws SAXException, IOException { TreeDumpContentHandler treeDumpContentHandler = new TreeDumpContentHandler(new OutputStreamWriter(System.out, "UTF-8")); HtmlParser htmlParser = new HtmlParser(); htmlParser.setContentHandler(treeDumpContentHandler); htmlParser.setLexicalHandler(treeDumpContentHandler); File file = new File(args[0]); InputSource is = new InputSource(new FileInputStream(file)); is.setSystemId(file.toURI().toASCIIString()); htmlParser.parse(is); }
public static void main(String[] args) throws SAXException, IOException { TreeDumpContentHandler treeDumpContentHandler = new TreeDumpContentHandler(new OutputStreamWriter(System.out, "UTF-8")); HtmlParser htmlParser = new HtmlParser(); htmlParser.setContentHandler(treeDumpContentHandler); htmlParser.setLexicalHandler(treeDumpContentHandler); htmlParser.setErrorHandler(new SystemErrErrorHandler()); File file = new File(args[0]); InputSource is = new InputSource(new FileInputStream(file)); is.setSystemId(file.toURI().toASCIIString()); htmlParser.parse(is); }
diff --git a/projects/connector-manager/source/java/com/google/enterprise/connector/pusher/GsaFeedConnection.java b/projects/connector-manager/source/java/com/google/enterprise/connector/pusher/GsaFeedConnection.java index 74657150..66545118 100644 --- a/projects/connector-manager/source/java/com/google/enterprise/connector/pusher/GsaFeedConnection.java +++ b/projects/connector-manager/source/java/com/google/enterprise/connector/pusher/GsaFeedConnection.java @@ -1,83 +1,83 @@ // Copyright 2006 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.enterprise.connector.pusher; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; /** * Opens a connection to a url and sends data to it. */ public class GsaFeedConnection implements FeedConnection { private URL url = null;; private String host; private int port; public GsaFeedConnection(String host, int port) { this.host = host; this.port = port; } /* * Urlencodes the xml string. */ private String encode(String data) throws UnsupportedEncodingException { String encodedData = URLEncoder.encode(data, DocPusher.XML_DEFAULT_ENCODING); return encodedData; } /* * Generates the feed url for a given GSA host. */ private URL getFeedUrl() throws MalformedURLException{ String feedUrl = "http://" + host + ":" + port + "/xmlfeed"; URL url = new URL(feedUrl); return url; } public String sendData(String data) throws IOException { if (url == null) { url = getFeedUrl(); } URLConnection uc = url.openConnection(); uc.setDoInput(true); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(uc.getOutputStream()); - osw.write(encode(data)); + osw.write(data); osw.flush(); StringBuffer buf = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = br.readLine()) != null) { buf.append(line); } osw.close(); br.close(); return buf.toString(); } }
true
true
public String sendData(String data) throws IOException { if (url == null) { url = getFeedUrl(); } URLConnection uc = url.openConnection(); uc.setDoInput(true); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(uc.getOutputStream()); osw.write(encode(data)); osw.flush(); StringBuffer buf = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = br.readLine()) != null) { buf.append(line); } osw.close(); br.close(); return buf.toString(); }
public String sendData(String data) throws IOException { if (url == null) { url = getFeedUrl(); } URLConnection uc = url.openConnection(); uc.setDoInput(true); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(uc.getOutputStream()); osw.write(data); osw.flush(); StringBuffer buf = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = br.readLine()) != null) { buf.append(line); } osw.close(); br.close(); return buf.toString(); }
diff --git a/rest/src/test/java/org/usergrid/rest/management/organizations/OrganizationsResourceTest.java b/rest/src/test/java/org/usergrid/rest/management/organizations/OrganizationsResourceTest.java index 2e0e9894..c567271b 100644 --- a/rest/src/test/java/org/usergrid/rest/management/organizations/OrganizationsResourceTest.java +++ b/rest/src/test/java/org/usergrid/rest/management/organizations/OrganizationsResourceTest.java @@ -1,79 +1,79 @@ package org.usergrid.rest.management.organizations; import org.codehaus.jackson.JsonNode; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.usergrid.management.ApplicationInfo; import org.usergrid.management.UserInfo; import org.usergrid.persistence.EntityManager; import org.usergrid.persistence.EntityManagerFactory; import org.usergrid.persistence.cassandra.CassandraService; import org.usergrid.persistence.entities.User; import org.usergrid.rest.AbstractRestTest; import javax.annotation.Resource; import javax.ws.rs.core.MediaType; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.usergrid.management.cassandra.ManagementServiceImpl.*; import static org.usergrid.utils.MapUtils.entry; import static org.usergrid.utils.MapUtils.hashMap; /** * @author zznate */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="/testApplicationContext.xml") public class OrganizationsResourceTest extends AbstractRestTest { @Resource private EntityManagerFactory emf; @Test public void createOrgAndOwner() throws Exception { properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false"); properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false"); properties.setProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "false"); properties.setProperty(PROPERTIES_SYSADMIN_EMAIL, "[email protected]"); Map<String, String> payload = hashMap("email", "[email protected]") .map("username", "test-user-1").map("name", "Test User") .map("password", "password") .map("organization", "test-org-1"); JsonNode node = resource().path("/management/organizations") .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE) .post(JsonNode.class, payload); assertNotNull(node); ApplicationInfo applicationInfo = managementService.getApplicationInfo("test-org-1/sandbox"); assertNotNull(applicationInfo); Set<String> rolePerms = emf.getEntityManager(applicationInfo.getId()).getRolePermissions("guest"); assertNotNull(rolePerms); assertTrue(rolePerms.contains("get,post,put,delete:/**")); logNode(node); UserInfo ui = managementService.getAdminUserByEmail("[email protected]"); EntityManager em = emf.getEntityManager(CassandraService.MANAGEMENT_APPLICATION_ID); User user = em.get(ui.getUuid(), User.class); - assertTrue(user.activated()); - assertFalse(user.disabled()); - assertTrue(user.confirmed()); + //assertTrue(user.activated()); + //assertFalse(user.disabled()); + //assertTrue(user.confirmed()); } }
true
true
public void createOrgAndOwner() throws Exception { properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false"); properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false"); properties.setProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "false"); properties.setProperty(PROPERTIES_SYSADMIN_EMAIL, "[email protected]"); Map<String, String> payload = hashMap("email", "[email protected]") .map("username", "test-user-1").map("name", "Test User") .map("password", "password") .map("organization", "test-org-1"); JsonNode node = resource().path("/management/organizations") .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE) .post(JsonNode.class, payload); assertNotNull(node); ApplicationInfo applicationInfo = managementService.getApplicationInfo("test-org-1/sandbox"); assertNotNull(applicationInfo); Set<String> rolePerms = emf.getEntityManager(applicationInfo.getId()).getRolePermissions("guest"); assertNotNull(rolePerms); assertTrue(rolePerms.contains("get,post,put,delete:/**")); logNode(node); UserInfo ui = managementService.getAdminUserByEmail("[email protected]"); EntityManager em = emf.getEntityManager(CassandraService.MANAGEMENT_APPLICATION_ID); User user = em.get(ui.getUuid(), User.class); assertTrue(user.activated()); assertFalse(user.disabled()); assertTrue(user.confirmed()); }
public void createOrgAndOwner() throws Exception { properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false"); properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false"); properties.setProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "false"); properties.setProperty(PROPERTIES_SYSADMIN_EMAIL, "[email protected]"); Map<String, String> payload = hashMap("email", "[email protected]") .map("username", "test-user-1").map("name", "Test User") .map("password", "password") .map("organization", "test-org-1"); JsonNode node = resource().path("/management/organizations") .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON_TYPE) .post(JsonNode.class, payload); assertNotNull(node); ApplicationInfo applicationInfo = managementService.getApplicationInfo("test-org-1/sandbox"); assertNotNull(applicationInfo); Set<String> rolePerms = emf.getEntityManager(applicationInfo.getId()).getRolePermissions("guest"); assertNotNull(rolePerms); assertTrue(rolePerms.contains("get,post,put,delete:/**")); logNode(node); UserInfo ui = managementService.getAdminUserByEmail("[email protected]"); EntityManager em = emf.getEntityManager(CassandraService.MANAGEMENT_APPLICATION_ID); User user = em.get(ui.getUuid(), User.class); //assertTrue(user.activated()); //assertFalse(user.disabled()); //assertTrue(user.confirmed()); }
diff --git a/src/com/jgaap/eventCullers/ExtremeCuller.java b/src/com/jgaap/eventCullers/ExtremeCuller.java index e1f4225..14b3ace 100644 --- a/src/com/jgaap/eventCullers/ExtremeCuller.java +++ b/src/com/jgaap/eventCullers/ExtremeCuller.java @@ -1,97 +1,97 @@ /* * JGAAP -- a graphical program for stylometric authorship attribution * Copyright (C) 2009,2011 by Patrick Juola * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jgaap.eventCullers; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.jgaap.generics.Event; import com.jgaap.generics.EventCuller; import com.jgaap.generics.EventSet; /** * * Analyzes only those Events appear in all samples [as suggested by (Jockers, 2008)]. * * @author Michael Ryan * @since 5.0.0 */ public class ExtremeCuller extends EventCuller { @Override public List<EventSet> cull(List<EventSet> eventSets) { List<Set<Event>> eventSetsUnique = new ArrayList<Set<Event>>(); Set<Event> uniqueEvents = new HashSet<Event>(); Set<Event> extremeEvents = new HashSet<Event>(); for(EventSet eventSet : eventSets){ Set<Event> events = new HashSet<Event>(); for(Event event : eventSet){ events.add(event); uniqueEvents.add(event); } eventSetsUnique.add(events); } for(Event event : uniqueEvents){ boolean extreme = true; for(Set<Event> events : eventSetsUnique){ if(!events.contains(event)){ extreme = false; break; } } if(extreme){ extremeEvents.add(event); } } List<EventSet> culledEventSets = new ArrayList<EventSet>(eventSets.size()); for(EventSet eventSet : eventSets){ EventSet culledEventSet = new EventSet(); for(Event event : eventSet){ - if(extremeEvents.contains(event.getEvent())){ + if(extremeEvents.contains(event)){ culledEventSet.addEvent(event); } } culledEventSets.add(culledEventSet); } return culledEventSets; } @Override public String displayName() { return "X-treme Culler"; } @Override public String tooltipText() { return "All Events that appear in all samples."; } @Override public String longDescription() { return "Analyzes only those Events appear in all samples [as suggested by (Jockers, 2008)]."; } @Override public boolean showInGUI() { return true; } }
true
true
public List<EventSet> cull(List<EventSet> eventSets) { List<Set<Event>> eventSetsUnique = new ArrayList<Set<Event>>(); Set<Event> uniqueEvents = new HashSet<Event>(); Set<Event> extremeEvents = new HashSet<Event>(); for(EventSet eventSet : eventSets){ Set<Event> events = new HashSet<Event>(); for(Event event : eventSet){ events.add(event); uniqueEvents.add(event); } eventSetsUnique.add(events); } for(Event event : uniqueEvents){ boolean extreme = true; for(Set<Event> events : eventSetsUnique){ if(!events.contains(event)){ extreme = false; break; } } if(extreme){ extremeEvents.add(event); } } List<EventSet> culledEventSets = new ArrayList<EventSet>(eventSets.size()); for(EventSet eventSet : eventSets){ EventSet culledEventSet = new EventSet(); for(Event event : eventSet){ if(extremeEvents.contains(event.getEvent())){ culledEventSet.addEvent(event); } } culledEventSets.add(culledEventSet); } return culledEventSets; }
public List<EventSet> cull(List<EventSet> eventSets) { List<Set<Event>> eventSetsUnique = new ArrayList<Set<Event>>(); Set<Event> uniqueEvents = new HashSet<Event>(); Set<Event> extremeEvents = new HashSet<Event>(); for(EventSet eventSet : eventSets){ Set<Event> events = new HashSet<Event>(); for(Event event : eventSet){ events.add(event); uniqueEvents.add(event); } eventSetsUnique.add(events); } for(Event event : uniqueEvents){ boolean extreme = true; for(Set<Event> events : eventSetsUnique){ if(!events.contains(event)){ extreme = false; break; } } if(extreme){ extremeEvents.add(event); } } List<EventSet> culledEventSets = new ArrayList<EventSet>(eventSets.size()); for(EventSet eventSet : eventSets){ EventSet culledEventSet = new EventSet(); for(Event event : eventSet){ if(extremeEvents.contains(event)){ culledEventSet.addEvent(event); } } culledEventSets.add(culledEventSet); } return culledEventSets; }
diff --git a/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java b/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java index b5ef05b..ce0deff 100644 --- a/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java +++ b/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java @@ -1,99 +1,99 @@ package de.javadesign.cdi.extension.spring; import de.javadesign.cdi.extension.spring.context.ApplicationContextProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.web.context.ContextLoader; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessAnnotatedType; import java.text.MessageFormat; /** * This CDI Extension observes ProcessAnnotatedType events fired for every found bean during bean * discovery phase to prevent Spring Beans from being deployed again if found by the CDI XML or * class path scanner. * */ public class SpringBeanVetoExtension implements Extension { private static final Logger LOG = LoggerFactory.getLogger("de.javadesign.cdi.extension"); private boolean applicationContextFound = false; private boolean initialized = false; private ConfigurableListableBeanFactory beanFactory; public SpringBeanVetoExtension() { LOG.info(MessageFormat.format("{0} created.", this.getClass().getSimpleName())); } public void vetoSpringBeans(@Observes ProcessAnnotatedType event) { if (!initialized) { init(); } if (!applicationContextFound) { return; } if (beanForClassExists(event.getAnnotatedType().getJavaClass())) { // Do not deploy this class to the CDI context. event.veto(); if (LOG.isDebugEnabled()) { LOG.debug("Vetoing " + event.getAnnotatedType().getJavaClass().getCanonicalName()); } } } public void init() { initialized = true; AbstractApplicationContext applicationContext = (AbstractApplicationContext) ContextLoader .getCurrentWebApplicationContext(); if (applicationContext==null) { LOG.warn("No Web Spring-ApplicationContext found, try to resolve via application context provider."); applicationContext = (AbstractApplicationContext) ApplicationContextProvider.getApplicationContext(); } if (null != applicationContext) { LOG.info("ApplicationContext found."); applicationContextFound = true; beanFactory = applicationContext.getBeanFactory(); } else { LOG.warn("No Spring-ApplicationContext found."); } } /** * Uses the Spring BeanFactory to see if there is any Spring Bean matching * the given Class and returns true in the case such a bean is found and * false otherwise. * * @param clazz The Class currently observed by the CDI container. * @return True if there is a Spring Bean matching the given Class, false otherwise */ private boolean beanForClassExists(Class<?> clazz) { // Lookup if (0 != beanFactory.getBeanNamesForType(clazz).length) { return true; } // Workaround if interfaces in combination with component scanning is used. // Spring framework automatically detects interface and implementation pairs // but only returns bean names for interface types then. // We loop all known bean definitions to find out if the given class is // a spring bean. String[] names = beanFactory.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); - if (definition.getBeanClassName().equals(clazz.getCanonicalName())) { + if (definition.getBeanClassName()!=null && definition.getBeanClassName().equals(clazz.getCanonicalName())) { return true; } } return false; } }
true
true
private boolean beanForClassExists(Class<?> clazz) { // Lookup if (0 != beanFactory.getBeanNamesForType(clazz).length) { return true; } // Workaround if interfaces in combination with component scanning is used. // Spring framework automatically detects interface and implementation pairs // but only returns bean names for interface types then. // We loop all known bean definitions to find out if the given class is // a spring bean. String[] names = beanFactory.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (definition.getBeanClassName().equals(clazz.getCanonicalName())) { return true; } } return false; }
private boolean beanForClassExists(Class<?> clazz) { // Lookup if (0 != beanFactory.getBeanNamesForType(clazz).length) { return true; } // Workaround if interfaces in combination with component scanning is used. // Spring framework automatically detects interface and implementation pairs // but only returns bean names for interface types then. // We loop all known bean definitions to find out if the given class is // a spring bean. String[] names = beanFactory.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (definition.getBeanClassName()!=null && definition.getBeanClassName().equals(clazz.getCanonicalName())) { return true; } } return false; }
diff --git a/projects/TropixSshServer/src/impl/edu/umn/msi/tropix/ssh/SshFileFactoryImpl.java b/projects/TropixSshServer/src/impl/edu/umn/msi/tropix/ssh/SshFileFactoryImpl.java index 2c1b44a0..74db44cb 100644 --- a/projects/TropixSshServer/src/impl/edu/umn/msi/tropix/ssh/SshFileFactoryImpl.java +++ b/projects/TropixSshServer/src/impl/edu/umn/msi/tropix/ssh/SshFileFactoryImpl.java @@ -1,464 +1,464 @@ package edu.umn.msi.tropix.ssh; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.ManagedBean; import javax.inject.Inject; import org.apache.commons.io.output.ProxyOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.sshd.server.SshFile; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import edu.umn.msi.tropix.common.io.InputStreamCoercible; import edu.umn.msi.tropix.files.creator.TropixFileCreator; import edu.umn.msi.tropix.grid.credentials.Credential; import edu.umn.msi.tropix.models.Folder; import edu.umn.msi.tropix.models.TropixFile; import edu.umn.msi.tropix.models.TropixObject; import edu.umn.msi.tropix.models.locations.Locations; import edu.umn.msi.tropix.persistence.service.FolderService; import edu.umn.msi.tropix.persistence.service.TropixObjectService; import edu.umn.msi.tropix.storage.core.StorageManager; import edu.umn.msi.tropix.storage.core.StorageManager.FileMetadata; @ManagedBean public class SshFileFactoryImpl implements SshFileFactory { private static final Log LOG = LogFactory.getLog(SshFileFactoryImpl.class); private final TropixObjectService tropixObjectService; private final TropixFileCreator tropixFileCreator; private final StorageManager storageManager; private final FolderService folderService; private static final String HOME_DIRECTORY_PATH = "/" + Locations.MY_HOME; private static final String MY_GROUP_FOLDERS_PATH = "/" + Locations.MY_GROUP_FOLDERS; private static final Set<String> META_OBJECT_PATHS = Sets.newHashSet("/", HOME_DIRECTORY_PATH, MY_GROUP_FOLDERS_PATH); @Inject public SshFileFactoryImpl(final TropixObjectService tropixObjectService, final TropixFileCreator tropixFileCreator, final StorageManager storageManager, final FolderService folderService) { this.tropixObjectService = tropixObjectService; this.tropixFileCreator = tropixFileCreator; this.storageManager = storageManager; this.folderService = folderService; } public SshFile getFile(final Credential credential, final String virtualPath) { return new SshFileImpl(credential, virtualPath); } class SshFileImpl implements SshFile { private final Credential credential; private final String identity; private final String virtualPath; private final String absolutePath; private final boolean isMetaLocation; private StorageManager.FileMetadata fileMetadata; private boolean fileMetadataSet = false; private TropixObject object; private void initObject() { if(object == null) { log("setting object"); object = getTropixObject(virtualPath); } } private TropixObject getTropixObject(final String path) { List<String> pathPieces = Utils.pathPieces(path); if(pathPieces.size() > 0 && Locations.isValidBaseLocation(pathPieces.get(0))) { return tropixObjectService.getPath(identity, Iterables.toArray(pathPieces, String.class)); } else { return null; } } SshFileImpl(final Credential credential, final String virtualPath) { this.credential = credential; this.identity = credential.getIdentity(); this.virtualPath = virtualPath; this.absolutePath = Utils.cleanAndExpandPath(virtualPath); this.isMetaLocation = META_OBJECT_PATHS.contains(absolutePath); log("Create file for virtualPath " + virtualPath); } SshFileImpl(final Credential credential, final String virtualPath, final TropixObject object) { this(credential, virtualPath); this.object = object; } SshFileImpl(final Credential credential, final String virtualPath, final TropixObject object, final FileMetadata fileMetadata) { this(credential, virtualPath, object); this.fileMetadata = fileMetadata; this.fileMetadataSet = true; } // Remove trailing / for directories, is this expected? public String getAbsolutePath() { final String absolutePath = this.absolutePath; log(String.format("getAbsolutePath called, result is %s", absolutePath)); return absolutePath; } // What should this return for root? public String getName() { final String name = Utils.name(virtualPath); log(String.format("getName called, result is %s", name)); return name; } public boolean isDirectory() { log("isDirectory"); if(isMetaLocationOrRootFolder()) { return true; } else if(internalDoesExist()) { initObject(); return !(object instanceof TropixFile); } else { return false; } } public boolean isFile() { log("isFile"); if(isMetaLocationOrRootFolder()) { return false; } else if(internalDoesExist()) { initObject(); return (object instanceof TropixFile); } else { return false; } } public boolean doesExist() { log("doesExist"); return internalDoesExist(); } private boolean internalDoesExist() { boolean doesExist = false; if(isMetaLocation) { doesExist = true; } else { initObject(); doesExist = object != null; } return doesExist; } public boolean isRemovable() { log("isRemovable"); return !isMetaLocation && internalDoesExist(); } public SshFile getParentFile() { log("getParentFile"); return getFile(credential, Utils.parent(virtualPath)); } public long getLastModified() { log("getLastModified"); initFileMetadata(); if(fileMetadata != null) { return fileMetadata.getDateModified(); } else { return 0L; } } public boolean setLastModified(final long time) { return false; } private boolean isTropixFile() { if(isMetaLocationOrRootFolder()) { return false; } else { initObject(); return object instanceof TropixFile; } } private String getFileId() { Preconditions.checkState(isTropixFile(), "getFileId called for non-file object"); final TropixFile file = (TropixFile) object; return file.getFileId(); } private void initFileMetadata() { if(!fileMetadataSet) { if(isTropixFile()) { fileMetadata = storageManager.getFileMetadata(getFileId(), identity); } fileMetadataSet = true; } } public long getSize() { log("getSize"); initFileMetadata(); if(fileMetadata != null) { return fileMetadata.getLength(); } else { return 0; } } private InputStreamCoercible readFile() { return storageManager.download(getFileId(), identity); } public void truncate() throws IOException { log("truncate"); if(internalDoesExist()) { // TODO: Handle this better throw new IllegalStateException("Cannot truncate this file, please delete and add a new file."); } } public boolean delete() { log("delete"); if(isMetaLocation || !internalDoesExist()) { return false; } else { initObject(); tropixObjectService.delete(identity, object.getId()); return true; } } public boolean move(final SshFile destination) { log("move"); if(isMetaLocation) { return false; } initObject(); boolean moved = false; if(parentIsFolder() && destination instanceof SshFileImpl) { final SshFileImpl destinationFile = (SshFileImpl) destination; final boolean validDestination = !destinationFile.doesExist() && destinationFile.parentIsFolder(); System.out.println(destinationFile.doesExist()); log("Move valid destination - " + validDestination); if(validDestination) { final String objectId = object.getId(); tropixObjectService.move(identity, objectId, destinationFile.parentAsFolder().getId()); final TropixObject object = tropixObjectService.load(identity, objectId); object.setName(destination.getName()); tropixObjectService.update(identity, object); moved = true; } } log(String.format("In move - moved? %b", moved)); return moved; } public boolean isReadable() { final boolean readable = true; log(String.format("Checking is readable - %b", readable)); return readable; } private void log(final String message) { if(LOG.isTraceEnabled()) { LOG.trace(String.format("For virtual path <%s> - %s", virtualPath, message)); } } public boolean isWritable() { log("Checking is writable"); if(isHomeDirectory()) { return true; } else if(isMetaLocation) { return false; } else { initObject(); return object instanceof Folder || (object == null && parentIsFolder()); } } public void handleClose() throws IOException { } private boolean isMetaLocationOrRootFolder() { return isMetaLocation || isRootGroupFolder(); } // TODO: Check uniqueness public boolean mkdir() { log("Creating directory"); if(isMetaLocationOrRootFolder()) { return false; } final TropixObject parentObject = getParentFolder(); if(!(parentObject instanceof Folder)) { return false; } else { final Folder newFolder = new Folder(); newFolder.setCommitted(true); newFolder.setName(Utils.name(virtualPath)); folderService.createFolder(identity, parentObject.getId(), newFolder); return true; } } private TropixObject getParentFolder() { final String parentPath = Utils.parent(virtualPath); final TropixObject parentObject = getTropixObject(parentPath); return parentObject; } private boolean parentIsFolder() { return getParentFolder() instanceof Folder; } private Folder parentAsFolder() { return (Folder) getParentFolder(); } public OutputStream createOutputStream(final long offset) throws IOException { if(!parentIsFolder()) { final String errorMessage = "Invalid path to create output stream from " + virtualPath; LOG.warn(errorMessage); throw new IllegalStateException(errorMessage); } else if(offset > 0) { final String errorMessage = "Server only supports offsets of 0 - path " + virtualPath; LOG.warn(errorMessage); throw new IllegalStateException(errorMessage); } else { final String newFileId = UUID.randomUUID().toString(); final OutputStream outputStream = storageManager.prepareUploadStream(newFileId, identity); return new ProxyOutputStream(outputStream) { @Override public void close() throws IOException { try { super.close(); } finally { LOG.debug("Preparing file for tropixfilecreator"); final Folder parentFolder = parentAsFolder(); final TropixFile tropixFile = new TropixFile(); tropixFile.setName(getName()); tropixFile.setCommitted(true); tropixFile.setFileId(newFileId); tropixFileCreator.createFile(credential, parentFolder.getId(), tropixFile, null); LOG.debug("File created " + virtualPath); } } }; } } public InputStream createInputStream(final long offset) throws IOException { final InputStream inputStream = readFile().asInputStream(); inputStream.skip(offset); return inputStream; } public List<SshFile> listSshFiles() { log("listSshFiles"); final ImmutableList.Builder<SshFile> children = ImmutableList.builder(); if(isRoot()) { children.add(getFile(credential, HOME_DIRECTORY_PATH)); children.add(getFile(credential, MY_GROUP_FOLDERS_PATH)); } else if(isMyGroupFolders()) { final TropixObject[] objects = folderService.getGroupFolders(identity); buildSshFiles(objects, children); } else { initObject(); final TropixObject[] objects = tropixObjectService.getChildren(identity, object.getId()); buildSshFiles(objects, children); } return children.build(); } // Hacking this to make sure names are unique in a case-insensitive manner because MySQL // likes are case-insensitive for the current schema. At some point we should update the name column // according to http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html. private <T extends TropixObject> void buildSshFiles(final T[] objects, final ImmutableList.Builder<SshFile> children) { final Map<String, Boolean> uniqueName = Maps.newHashMap(); for(TropixObject object : objects) { final String objectName = object.getName().toUpperCase(); if(!uniqueName.containsKey(objectName)) { uniqueName.put(objectName, true); } else { uniqueName.put(objectName, false); } } // Optimization: Separate files so we can batch prefetch metadata for them all at once final ImmutableList.Builder<TropixFile> tropixFilesBuilder = ImmutableList.builder(); final ImmutableList.Builder<String> tropixFileIds = ImmutableList.builder(); for(TropixObject object : objects) { if(object instanceof TropixFile) { TropixFile tropixFile = (TropixFile) object; tropixFilesBuilder.add(tropixFile); tropixFileIds.add(tropixFile.getFileId()); } else { final String name = object.getName(); final String derivedName = uniqueName.get(name.toUpperCase()) ? name : String.format("%s [id:%s]", name, object.getId()); final String childName = Utils.join(virtualPath, derivedName); LOG.debug(String.format("Creating child with name [%s]", childName)); children.add(new SshFileImpl(credential, childName, object)); } } final List<TropixFile> tropixFiles = tropixFilesBuilder.build(); if(!tropixFiles.isEmpty()) { final Iterator<FileMetadata> filesMetadataIterator = storageManager.getFileMetadata(tropixFileIds.build(), identity).iterator(); for(final TropixFile tropixFile : tropixFiles) { final String name = tropixFile.getName(); final String derivedName = uniqueName.get(name.toUpperCase()) ? name : String.format("%s [id:%s]", name, object.getId()); final String childName = Utils.join(virtualPath, derivedName); LOG.debug(String.format("Creating child with name [%s]", childName)); - children.add(new SshFileImpl(credential, childName, object, filesMetadataIterator.next())); + children.add(new SshFileImpl(credential, childName, tropixFile, filesMetadataIterator.next())); } } } private boolean isRoot() { return "/".equals(absolutePath); } private boolean isMyGroupFolders() { return MY_GROUP_FOLDERS_PATH.equals(absolutePath); } private boolean isRootGroupFolder() { boolean isRootGroupFolder = false; if(absolutePath.startsWith(MY_GROUP_FOLDERS_PATH)) { isRootGroupFolder = Utils.pathPiecesCountForAbsolutePath(absolutePath) == 2; } return isRootGroupFolder; } private boolean isHomeDirectory() { return HOME_DIRECTORY_PATH.equals(absolutePath); } public boolean create() throws IOException { log("Attempting create"); return !isTropixFile(); } public boolean isExecutable() { log("Checking executable"); return true; } } }
true
true
private <T extends TropixObject> void buildSshFiles(final T[] objects, final ImmutableList.Builder<SshFile> children) { final Map<String, Boolean> uniqueName = Maps.newHashMap(); for(TropixObject object : objects) { final String objectName = object.getName().toUpperCase(); if(!uniqueName.containsKey(objectName)) { uniqueName.put(objectName, true); } else { uniqueName.put(objectName, false); } } // Optimization: Separate files so we can batch prefetch metadata for them all at once final ImmutableList.Builder<TropixFile> tropixFilesBuilder = ImmutableList.builder(); final ImmutableList.Builder<String> tropixFileIds = ImmutableList.builder(); for(TropixObject object : objects) { if(object instanceof TropixFile) { TropixFile tropixFile = (TropixFile) object; tropixFilesBuilder.add(tropixFile); tropixFileIds.add(tropixFile.getFileId()); } else { final String name = object.getName(); final String derivedName = uniqueName.get(name.toUpperCase()) ? name : String.format("%s [id:%s]", name, object.getId()); final String childName = Utils.join(virtualPath, derivedName); LOG.debug(String.format("Creating child with name [%s]", childName)); children.add(new SshFileImpl(credential, childName, object)); } } final List<TropixFile> tropixFiles = tropixFilesBuilder.build(); if(!tropixFiles.isEmpty()) { final Iterator<FileMetadata> filesMetadataIterator = storageManager.getFileMetadata(tropixFileIds.build(), identity).iterator(); for(final TropixFile tropixFile : tropixFiles) { final String name = tropixFile.getName(); final String derivedName = uniqueName.get(name.toUpperCase()) ? name : String.format("%s [id:%s]", name, object.getId()); final String childName = Utils.join(virtualPath, derivedName); LOG.debug(String.format("Creating child with name [%s]", childName)); children.add(new SshFileImpl(credential, childName, object, filesMetadataIterator.next())); } } }
private <T extends TropixObject> void buildSshFiles(final T[] objects, final ImmutableList.Builder<SshFile> children) { final Map<String, Boolean> uniqueName = Maps.newHashMap(); for(TropixObject object : objects) { final String objectName = object.getName().toUpperCase(); if(!uniqueName.containsKey(objectName)) { uniqueName.put(objectName, true); } else { uniqueName.put(objectName, false); } } // Optimization: Separate files so we can batch prefetch metadata for them all at once final ImmutableList.Builder<TropixFile> tropixFilesBuilder = ImmutableList.builder(); final ImmutableList.Builder<String> tropixFileIds = ImmutableList.builder(); for(TropixObject object : objects) { if(object instanceof TropixFile) { TropixFile tropixFile = (TropixFile) object; tropixFilesBuilder.add(tropixFile); tropixFileIds.add(tropixFile.getFileId()); } else { final String name = object.getName(); final String derivedName = uniqueName.get(name.toUpperCase()) ? name : String.format("%s [id:%s]", name, object.getId()); final String childName = Utils.join(virtualPath, derivedName); LOG.debug(String.format("Creating child with name [%s]", childName)); children.add(new SshFileImpl(credential, childName, object)); } } final List<TropixFile> tropixFiles = tropixFilesBuilder.build(); if(!tropixFiles.isEmpty()) { final Iterator<FileMetadata> filesMetadataIterator = storageManager.getFileMetadata(tropixFileIds.build(), identity).iterator(); for(final TropixFile tropixFile : tropixFiles) { final String name = tropixFile.getName(); final String derivedName = uniqueName.get(name.toUpperCase()) ? name : String.format("%s [id:%s]", name, object.getId()); final String childName = Utils.join(virtualPath, derivedName); LOG.debug(String.format("Creating child with name [%s]", childName)); children.add(new SshFileImpl(credential, childName, tropixFile, filesMetadataIterator.next())); } } }
diff --git a/src/test/java/org/wyona/security/test/LDAPIdentityManagerImplTest.java b/src/test/java/org/wyona/security/test/LDAPIdentityManagerImplTest.java index 68e1ea3..0037db2 100644 --- a/src/test/java/org/wyona/security/test/LDAPIdentityManagerImplTest.java +++ b/src/test/java/org/wyona/security/test/LDAPIdentityManagerImplTest.java @@ -1,170 +1,171 @@ package org.wyona.security.test; import java.io.File; import org.wyona.security.core.api.Group; import org.wyona.security.core.api.GroupManager; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.Item; import org.wyona.security.core.api.User; import org.wyona.security.core.api.UserManager; import org.wyona.security.impl.ldap.LDAPIdentityManagerImpl; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import junit.framework.TestCase; import org.apache.log4j.Logger; /** * Test of the LDAPIdentityManagerImpl */ public class LDAPIdentityManagerImplTest extends TestCase { private static Logger log = Logger.getLogger(LDAPIdentityManagerImplTest.class); private Repository repo; private IdentityManager identityManager; public void setUp() throws Exception { RepositoryFactory repoFactory = new RepositoryFactory(); repo = repoFactory.newRepository("ldap-identities-repository", new File("repository-ldap-local-cache/repository.xml")); identityManager = new LDAPIdentityManagerImpl(repo, true); } /** * Get all users from cache (Yarep repository) */ public void testGetAllUsersFromCache() throws Exception { User[] users = identityManager.getUserManager().getUsers(false); assertNotNull(users); log.debug("Number of users: " + users.length); for (int i = 0; i < users.length; i++) { log.debug("User: " + users[i].getName()); } assertEquals(1, users.length); assertEquals("[email protected]", users[0].getEmail()); } /** * Get all users from LDAP */ public void testGetAllUsersFromLDAP() throws Exception { User[] users = identityManager.getUserManager().getUsers(true); - assertNull(users); + assertNotNull(users); + //assertNull(users); /* log.warn("DEBUG: Number of users: " + users.length); for (int i = 0; i < users.length; i++) { log.warn("DEBUG: User: " + users[i].getName()); } assertEquals(1, users.length); assertEquals("[email protected]", users[0].getEmail()); */ } /* public void testGetUser() throws Exception { String userID = "bob"; User user = identityManager.getUserManager().getUser(userID); assertNotNull(user); assertEquals("[email protected]", user.getEmail()); } */ /* public void testGetUserGroups() throws Exception { String userID = "lenya"; String groupID = "editors"; User user = identityManager.getUserManager().getUser(userID); assertNotNull(user); Group group = identityManager.getGroupManager().getGroup(groupID); assertTrue(group.isMember(user)); Group[] userGroups = user.getGroups(); assertEquals(1,userGroups.length); assertEquals(groupID , userGroups[0].getID()); } */ /* TODO: Delete testuser if it already exists public void testAddUser() throws Exception { UserManager userManager = identityManager.getUserManager(); String id = "testuser"; String name = "Test User"; String email = "[email protected]"; String password = "test123"; assertFalse("User already exists: " + id, userManager.existsUser(id)); User user = userManager.createUser(id, name, email, password); assertTrue(userManager.existsUser(id)); assertNotNull(user); assertEquals(id, user.getID()); assertEquals(email, user.getEmail()); assertEquals(name, user.getName()); assertTrue(user.authenticate(password)); } */ /* public void testGetGroups() throws Exception { String groupID = "editors"; Group group = identityManager.getGroupManager().getGroup(groupID); assertNotNull(group); assertEquals("Editors", group.getName()); } */ /* TODO: Delete testgroup1 if it already exists public void testAddGroup() throws Exception { GroupManager groupManager = identityManager.getGroupManager(); String id = "testgroup1"; String name = "Test Group 1"; assertFalse("Group already exists: " + id, groupManager.existsGroup(id)); Group group = groupManager.createGroup(id, name); assertTrue(groupManager.existsGroup(id)); assertNotNull(group); assertEquals(id, group.getID()); assertEquals(name, group.getName()); // add member: UserManager userManager = identityManager.getUserManager(); String userID = "user789"; User user = userManager.createUser(userID, "Some Name", "[email protected]", "pwd123"); assertFalse(group.isMember(user)); group.addMember(user); group.save(); assertTrue(group.isMember(user)); // delete user: userManager.removeUser(userID); assertFalse(group.isMember(user)); } */ /* TODO: Delete testgroup2 if it already exists public void testGroupMembers() throws Exception { GroupManager groupManager = identityManager.getGroupManager(); UserManager userManager = identityManager.getUserManager(); String id = "testgroup2"; String name = "Test Group 2"; Group group = groupManager.createGroup(id, name); String userID1 = "user-test1"; User user1 = userManager.createUser(userID1, "Some Name 1", "[email protected]", "pwd123"); String userID2 = "user-test2"; User user2 = userManager.createUser(userID2, "Some Name 2", "[email protected]", "pwd123"); String userID3 = "user-test3"; User user3 = userManager.createUser(userID3, "Some Name 3", "[email protected]", "pwd123"); group.addMember(user1); group.addMember(user2); group.addMember(user3); group.save(); Item[] items = group.getMembers(); assertEquals(3, items.length); for (int i=0; i<items.length; i++) { User user = (User)items[i]; assertTrue(group.isMember(user)); assertTrue(user.getName().startsWith("Some Name")); } } */ }
true
true
public void testGetAllUsersFromLDAP() throws Exception { User[] users = identityManager.getUserManager().getUsers(true); assertNull(users); /* log.warn("DEBUG: Number of users: " + users.length); for (int i = 0; i < users.length; i++) { log.warn("DEBUG: User: " + users[i].getName()); } assertEquals(1, users.length); assertEquals("[email protected]", users[0].getEmail()); */ }
public void testGetAllUsersFromLDAP() throws Exception { User[] users = identityManager.getUserManager().getUsers(true); assertNotNull(users); //assertNull(users); /* log.warn("DEBUG: Number of users: " + users.length); for (int i = 0; i < users.length; i++) { log.warn("DEBUG: User: " + users[i].getName()); } assertEquals(1, users.length); assertEquals("[email protected]", users[0].getEmail()); */ }
diff --git a/trunk/dig.java b/trunk/dig.java index 3d74a16..c301655 100644 --- a/trunk/dig.java +++ b/trunk/dig.java @@ -1,191 +1,191 @@ // Copyright (c) 1999 Brian Wellington ([email protected]) // Portions Copyright (c) 1999 Network Associates, Inc. import java.io.*; import java.util.*; import org.xbill.DNS.*; /** @author Brian Wellington &lt;[email protected]&gt; */ public class dig { static Name name = null; static short type = Type.A, _class = DClass.IN; static void usage() { System.out.println("Usage: dig [@server] name [<type>] [<class>] " + "[options]"); System.exit(0); } static void doQuery(Message response) throws IOException { System.out.println("; java dig 0.0"); System.out.println(response); } static void doAXFR(Message response) throws IOException { System.out.println("; java dig 0.0 <> " + name + " axfr"); if (response.isSigned()) { System.out.print(";; TSIG "); if (response.isVerified()) System.out.println("ok"); else System.out.println("failed"); } if (response.getRcode() != Rcode.NOERROR) { System.out.println(response); return; } Enumeration e = response.getSection(Section.ANSWER); while (e.hasMoreElements()) System.out.println(e.nextElement()); System.out.print(";; done ("); System.out.print(response.getHeader().getCount(Section.ANSWER)); System.out.print(" records, "); System.out.print(response.getHeader().getCount(Section.ADDITIONAL)); System.out.println(" additional)"); } public static void main(String argv[]) throws IOException { String server; int arg; Message query, response; Record rec; Record opt = null; Resolver res = null; boolean printQuery = false; if (argv.length < 1) { usage(); } try { arg = 0; if (argv[arg].startsWith("@")) { server = argv[arg++].substring(1); res = new SimpleResolver(server); } else res = new ExtendedResolver(); String nameString = argv[arg++]; if (nameString.equals("-x")) { name = new Name(dns.inaddrString(argv[arg++])); type = Type.PTR; _class = DClass.IN; } else { name = new Name(nameString); type = Type.value(argv[arg]); if (type < 0) type = Type.A; else arg++; _class = DClass.value(argv[arg]); if (_class < 0) _class = DClass.IN; else arg++; } while (argv[arg].startsWith("-") && argv[arg].length() > 1) { switch (argv[arg].charAt(1)) { case 'p': String portStr; int port; if (argv[arg].length() > 2) portStr = argv[arg].substring(2); else portStr = argv[++arg]; port = Integer.parseInt(portStr); if (port < 0 || port > 65536) { System.out.println("Invalid port"); return; } res.setPort(port); break; case 'k': String key; if (argv[arg].length() > 2) key = argv[arg].substring(2); else key = argv[++arg]; int index = key.indexOf('/'); if (index < 0) res.setTSIGKey(key); else res.setTSIGKey(key.substring(0, index), key.substring(index+1)); break; case 't': res.setTCP(true); break; case 'i': res.setIgnoreTruncation(true); break; case 'e': String ednsStr; int edns; if (argv[arg].length() > 2) ednsStr = argv[arg].substring(2); else ednsStr = argv[++arg]; edns = Integer.parseInt(ednsStr); if (edns < 0 || edns > 1) { System.out.println("Unsupported " + "EDNS level: " + edns); return; } res.setEDNS(edns); break; case 'd': opt = new OPTRecord((short)1280, (byte)0, (byte)0, Flags.DO); break; case 'q': printQuery = true; break; default: - System.out.print("Invalid option"); + System.out.print("Invalid option: "); System.out.println(argv[arg]); } arg++; } } catch (ArrayIndexOutOfBoundsException e) { if (name == null) usage(); } rec = Record.newRecord(name, type, _class); query = Message.newQuery(rec); if (opt != null) query.addRecord(opt, Section.ADDITIONAL); if (printQuery) System.out.println(query); response = res.send(query); if (type == Type.AXFR) doAXFR(response); else doQuery(response); } }
true
true
public static void main(String argv[]) throws IOException { String server; int arg; Message query, response; Record rec; Record opt = null; Resolver res = null; boolean printQuery = false; if (argv.length < 1) { usage(); } try { arg = 0; if (argv[arg].startsWith("@")) { server = argv[arg++].substring(1); res = new SimpleResolver(server); } else res = new ExtendedResolver(); String nameString = argv[arg++]; if (nameString.equals("-x")) { name = new Name(dns.inaddrString(argv[arg++])); type = Type.PTR; _class = DClass.IN; } else { name = new Name(nameString); type = Type.value(argv[arg]); if (type < 0) type = Type.A; else arg++; _class = DClass.value(argv[arg]); if (_class < 0) _class = DClass.IN; else arg++; } while (argv[arg].startsWith("-") && argv[arg].length() > 1) { switch (argv[arg].charAt(1)) { case 'p': String portStr; int port; if (argv[arg].length() > 2) portStr = argv[arg].substring(2); else portStr = argv[++arg]; port = Integer.parseInt(portStr); if (port < 0 || port > 65536) { System.out.println("Invalid port"); return; } res.setPort(port); break; case 'k': String key; if (argv[arg].length() > 2) key = argv[arg].substring(2); else key = argv[++arg]; int index = key.indexOf('/'); if (index < 0) res.setTSIGKey(key); else res.setTSIGKey(key.substring(0, index), key.substring(index+1)); break; case 't': res.setTCP(true); break; case 'i': res.setIgnoreTruncation(true); break; case 'e': String ednsStr; int edns; if (argv[arg].length() > 2) ednsStr = argv[arg].substring(2); else ednsStr = argv[++arg]; edns = Integer.parseInt(ednsStr); if (edns < 0 || edns > 1) { System.out.println("Unsupported " + "EDNS level: " + edns); return; } res.setEDNS(edns); break; case 'd': opt = new OPTRecord((short)1280, (byte)0, (byte)0, Flags.DO); break; case 'q': printQuery = true; break; default: System.out.print("Invalid option"); System.out.println(argv[arg]); } arg++; } } catch (ArrayIndexOutOfBoundsException e) { if (name == null) usage(); } rec = Record.newRecord(name, type, _class); query = Message.newQuery(rec); if (opt != null) query.addRecord(opt, Section.ADDITIONAL); if (printQuery) System.out.println(query); response = res.send(query); if (type == Type.AXFR) doAXFR(response); else doQuery(response); }
public static void main(String argv[]) throws IOException { String server; int arg; Message query, response; Record rec; Record opt = null; Resolver res = null; boolean printQuery = false; if (argv.length < 1) { usage(); } try { arg = 0; if (argv[arg].startsWith("@")) { server = argv[arg++].substring(1); res = new SimpleResolver(server); } else res = new ExtendedResolver(); String nameString = argv[arg++]; if (nameString.equals("-x")) { name = new Name(dns.inaddrString(argv[arg++])); type = Type.PTR; _class = DClass.IN; } else { name = new Name(nameString); type = Type.value(argv[arg]); if (type < 0) type = Type.A; else arg++; _class = DClass.value(argv[arg]); if (_class < 0) _class = DClass.IN; else arg++; } while (argv[arg].startsWith("-") && argv[arg].length() > 1) { switch (argv[arg].charAt(1)) { case 'p': String portStr; int port; if (argv[arg].length() > 2) portStr = argv[arg].substring(2); else portStr = argv[++arg]; port = Integer.parseInt(portStr); if (port < 0 || port > 65536) { System.out.println("Invalid port"); return; } res.setPort(port); break; case 'k': String key; if (argv[arg].length() > 2) key = argv[arg].substring(2); else key = argv[++arg]; int index = key.indexOf('/'); if (index < 0) res.setTSIGKey(key); else res.setTSIGKey(key.substring(0, index), key.substring(index+1)); break; case 't': res.setTCP(true); break; case 'i': res.setIgnoreTruncation(true); break; case 'e': String ednsStr; int edns; if (argv[arg].length() > 2) ednsStr = argv[arg].substring(2); else ednsStr = argv[++arg]; edns = Integer.parseInt(ednsStr); if (edns < 0 || edns > 1) { System.out.println("Unsupported " + "EDNS level: " + edns); return; } res.setEDNS(edns); break; case 'd': opt = new OPTRecord((short)1280, (byte)0, (byte)0, Flags.DO); break; case 'q': printQuery = true; break; default: System.out.print("Invalid option: "); System.out.println(argv[arg]); } arg++; } } catch (ArrayIndexOutOfBoundsException e) { if (name == null) usage(); } rec = Record.newRecord(name, type, _class); query = Message.newQuery(rec); if (opt != null) query.addRecord(opt, Section.ADDITIONAL); if (printQuery) System.out.println(query); response = res.send(query); if (type == Type.AXFR) doAXFR(response); else doQuery(response); }
diff --git a/common/logisticspipes/transport/CraftingPipeMk3Transport.java b/common/logisticspipes/transport/CraftingPipeMk3Transport.java index 4cfea533..0316f346 100644 --- a/common/logisticspipes/transport/CraftingPipeMk3Transport.java +++ b/common/logisticspipes/transport/CraftingPipeMk3Transport.java @@ -1,67 +1,67 @@ package logisticspipes.transport; import logisticspipes.pipes.PipeItemsCraftingLogisticsMk3; import net.minecraft.src.EntityItem; import net.minecraft.src.IInventory; import net.minecraft.src.ItemStack; import net.minecraft.src.TileEntity; import buildcraft.api.transport.IPipeEntry; import buildcraft.core.inventory.Transactor; import buildcraft.core.proxy.CoreProxy; import buildcraft.transport.EntityData; import buildcraft.transport.PipeTransportItems; import buildcraft.transport.TileGenericPipe; public class CraftingPipeMk3Transport extends PipeTransportLogistics { public PipeItemsCraftingLogisticsMk3 pipe; public CraftingPipeMk3Transport() { super(); travelHook = new LogisticsItemTravelingHook(worldObj, xCoord, yCoord, zCoord, this) { @Override public void endReached(PipeTransportItems pipe, EntityData data, TileEntity tile) { scheduleRemoval(data.item); handleTileReached(data, tile); } }; } private void handleTileReached(EntityData data, TileEntity tile) { if (tile instanceof IPipeEntry) ((IPipeEntry) tile).entityEntering(data.item, data.output); else if (tile instanceof TileGenericPipe && ((TileGenericPipe) tile).pipe.transport instanceof PipeTransportItems) { TileGenericPipe pipe = (TileGenericPipe) tile; ((PipeTransportItems) pipe.pipe.transport).entityEntering(data.item, data.output); } else if (tile instanceof IInventory) { - ItemStack added = Transactor.getTransactorFor(tile).add(data.item.getItemStack(), data.input.reverse(), true); + ItemStack added = Transactor.getTransactorFor(tile).add(data.item.getItemStack(), data.output.reverse(), true); if (!CoreProxy.proxy.isRenderWorld(worldObj)) if(added.stackSize >= data.item.getItemStack().stackSize) data.item.remove(); else { data.item.getItemStack().stackSize -= added.stackSize; data.item.getItemStack().stackSize = pipe.inv.addCompressed(data.item.getItemStack()); if(data.item.getItemStack().stackSize > 0) { data.toCenter = true; data.input = data.output.reverse(); unscheduleRemoval(data.item); entityEntering(data.item, data.output.reverse()); } } } else { if (travelHook != null) travelHook.drop(this, data); EntityItem dropped = data.item.toEntityItem(data.output); if (dropped != null) // On SMP, the client side doesn't actually drops // items onDropped(dropped); } } }
true
true
private void handleTileReached(EntityData data, TileEntity tile) { if (tile instanceof IPipeEntry) ((IPipeEntry) tile).entityEntering(data.item, data.output); else if (tile instanceof TileGenericPipe && ((TileGenericPipe) tile).pipe.transport instanceof PipeTransportItems) { TileGenericPipe pipe = (TileGenericPipe) tile; ((PipeTransportItems) pipe.pipe.transport).entityEntering(data.item, data.output); } else if (tile instanceof IInventory) { ItemStack added = Transactor.getTransactorFor(tile).add(data.item.getItemStack(), data.input.reverse(), true); if (!CoreProxy.proxy.isRenderWorld(worldObj)) if(added.stackSize >= data.item.getItemStack().stackSize) data.item.remove(); else { data.item.getItemStack().stackSize -= added.stackSize; data.item.getItemStack().stackSize = pipe.inv.addCompressed(data.item.getItemStack()); if(data.item.getItemStack().stackSize > 0) { data.toCenter = true; data.input = data.output.reverse(); unscheduleRemoval(data.item); entityEntering(data.item, data.output.reverse()); } } } else { if (travelHook != null) travelHook.drop(this, data); EntityItem dropped = data.item.toEntityItem(data.output); if (dropped != null) // On SMP, the client side doesn't actually drops // items onDropped(dropped); } }
private void handleTileReached(EntityData data, TileEntity tile) { if (tile instanceof IPipeEntry) ((IPipeEntry) tile).entityEntering(data.item, data.output); else if (tile instanceof TileGenericPipe && ((TileGenericPipe) tile).pipe.transport instanceof PipeTransportItems) { TileGenericPipe pipe = (TileGenericPipe) tile; ((PipeTransportItems) pipe.pipe.transport).entityEntering(data.item, data.output); } else if (tile instanceof IInventory) { ItemStack added = Transactor.getTransactorFor(tile).add(data.item.getItemStack(), data.output.reverse(), true); if (!CoreProxy.proxy.isRenderWorld(worldObj)) if(added.stackSize >= data.item.getItemStack().stackSize) data.item.remove(); else { data.item.getItemStack().stackSize -= added.stackSize; data.item.getItemStack().stackSize = pipe.inv.addCompressed(data.item.getItemStack()); if(data.item.getItemStack().stackSize > 0) { data.toCenter = true; data.input = data.output.reverse(); unscheduleRemoval(data.item); entityEntering(data.item, data.output.reverse()); } } } else { if (travelHook != null) travelHook.drop(this, data); EntityItem dropped = data.item.toEntityItem(data.output); if (dropped != null) // On SMP, the client side doesn't actually drops // items onDropped(dropped); } }
diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java index f0ad33f4d..e39cfdde9 100644 --- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java +++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/rollback/FormerState.java @@ -1,363 +1,363 @@ /******************************************************************************* * Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.equinox.internal.p2.rollback; import java.net.URL; import java.util.*; import java.util.Map.Entry; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.director.*; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus; import org.eclipse.equinox.internal.provisional.p2.core.eventbus.SynchronousProvisioningListener; import org.eclipse.equinox.internal.provisional.p2.core.repository.IRepository; import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest; import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory; import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription; import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.query.*; import org.osgi.framework.Version; public class FormerState { public static final String IUPROP_PREFIX = "---IUPROPERTY---"; //$NON-NLS-1$ public static final String IUPROP_POSTFIX = "---IUPROPERTYKEY---"; //$NON-NLS-1$ private static long lastTimestamp; URL location = null; Hashtable generatedIUs = new Hashtable(); //key profile id, value the iu representing this profile private synchronized static long uniqueTimestamp() { long timewaited = 0; long timestamp = System.currentTimeMillis(); while (timestamp == lastTimestamp) { if (timewaited > 1000) throw new IllegalStateException("uniquetimestamp failed"); //$NON-NLS-1$ try { Thread.sleep(10); } catch (InterruptedException e) { // reset interrupted status Thread.currentThread().interrupt(); } timewaited += 10; timestamp = System.currentTimeMillis(); } lastTimestamp = timestamp; return timestamp; } public FormerState(URL repoLocation) { if (repoLocation == null) throw new IllegalArgumentException("Repository location can't be null"); //$NON-NLS-1$ IProvisioningEventBus eventBus = (IProvisioningEventBus) ServiceHelper.getService(DirectorActivator.context, IProvisioningEventBus.SERVICE_NAME); location = repoLocation; //listen for pre-event. to snapshot the profile eventBus.addListener(new SynchronousProvisioningListener() { public void notify(EventObject o) { if (o instanceof BeginOperationEvent) { BeginOperationEvent event = (BeginOperationEvent) o; IInstallableUnit iuForProfile = profileToIU(event.getProfile()); generatedIUs.put(event.getProfile().getProfileId(), iuForProfile); } else if (o instanceof ProfileEvent) { ProfileEvent event = (ProfileEvent) o; if (event.getReason() == ProfileEvent.CHANGED) getRepository().addInstallableUnits(new IInstallableUnit[] {(IInstallableUnit) generatedIUs.get(event.getProfileId())}); return; } else if (o instanceof RollbackOperationEvent) { RollbackOperationEvent event = (RollbackOperationEvent) o; generatedIUs.remove(event.getProfile().getProfileId()); return; } //TODO We need to decide what to do on profile removal // else if (o instanceof ProfileEvent) { // ProfileEvent pe = (ProfileEvent) o; // if (pe.getReason() == ProfileEvent.REMOVED) { // profileRegistries.remove(pe.getProfile().getProfileId()); // persist(); // } // } } }); } IMetadataRepository getRepository() { IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(DirectorActivator.context, IMetadataRepositoryManager.class.getName()); try { return manager.loadRepository(location, null); } catch (ProvisionException e) { //fall through and create a new repository } try { Map properties = new HashMap(1); properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString()); return manager.createRepository(location, "Agent rollback repository", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); //$NON-NLS-1$ } catch (ProvisionException e) { LogHelper.log(e); } throw new IllegalStateException("Unable to open or create Agent's rollback repository"); //$NON-NLS-1$ } public static IInstallableUnit profileToIU(IProfile profile) { InstallableUnitDescription result = new MetadataFactory.InstallableUnitDescription(); result.setProperty(IInstallableUnit.PROP_TYPE_PROFILE, Boolean.TRUE.toString()); result.setId(profile.getProfileId()); result.setVersion(new Version(0, 0, 0, Long.toString(uniqueTimestamp()))); result.setRequiredCapabilities(IUTransformationHelper.toRequirements(profile.query(InstallableUnitQuery.ANY, new Collector(), null).iterator(), false)); // Save the profile properties // TODO we aren't marking these properties in any special way to indicate they came from profile properties. Should we? Map properties = profile.getProperties(); Iterator iter = properties.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); result.setProperty(key, (String) properties.get(key)); } // Save the IU profile properties Iterator allIUs = profile.query(InstallableUnitQuery.ANY, new Collector(), null).iterator(); while (allIUs.hasNext()) { IInstallableUnit iu = (IInstallableUnit) allIUs.next(); properties = profile.getInstallableUnitProperties(iu); iter = properties.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); result.setProperty(IUPROP_PREFIX + iu.getId() + IUPROP_POSTFIX + key, (String) properties.get(key)); } } return MetadataFactory.createInstallableUnit(result); } public static IProfile IUToProfile(IInstallableUnit profileIU, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException { try { return new FormerStateProfile(profileIU, profile, context); } finally { if (monitor != null) monitor.done(); } } public static ProfileChangeRequest generateProfileDeltaChangeRequest(IProfile current, IProfile target) { ProfileChangeRequest request = new ProfileChangeRequest(current); synchronizeProfileProperties(request, current, target); synchronizeMarkedIUs(request, current, target); synchronizeAllIUProperties(request, current, target); return request; } private static void synchronizeAllIUProperties(ProfileChangeRequest request, IProfile current, IProfile target) { Collection currentIUs = current.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection(); Collection targetIUs = target.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection(); List iusToAdd = new ArrayList(targetIUs); iusToAdd.remove(currentIUs); //additions for (Iterator iterator = iusToAdd.iterator(); iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); for (Iterator it = target.getInstallableUnitProperties(iu).entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); request.setInstallableUnitProfileProperty(iu, key, value); } } // updates List iusToUpdate = new ArrayList(targetIUs); iusToUpdate.remove(iusToAdd); for (Iterator iterator = iusToUpdate.iterator(); iterator.hasNext();) { IInstallableUnit iu = (IInstallableUnit) iterator.next(); Map propertiesToSet = new HashMap(target.getInstallableUnitProperties(iu)); for (Iterator it = current.getInstallableUnitProperties(iu).entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String newValue = (String) propertiesToSet.get(key); if (newValue == null) { request.removeInstallableUnitProfileProperty(iu, key); } else if (newValue.equals(entry.getValue())) propertiesToSet.remove(key); } for (Iterator it = propertiesToSet.entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); request.setInstallableUnitProfileProperty(iu, key, value); } } } private static void synchronizeMarkedIUs(ProfileChangeRequest request, IProfile current, IProfile target) { IInstallableUnit[] currentPlannerMarkedIUs = SimplePlanner.findPlannerMarkedIUs(current); IInstallableUnit[] targetPlannerMarkedIUs = SimplePlanner.findPlannerMarkedIUs(target); //additions List markedIUsToAdd = new ArrayList(Arrays.asList(targetPlannerMarkedIUs)); markedIUsToAdd.removeAll(Arrays.asList(currentPlannerMarkedIUs)); request.addInstallableUnits((IInstallableUnit[]) markedIUsToAdd.toArray(new IInstallableUnit[markedIUsToAdd.size()])); // removes List markedIUsToRemove = new ArrayList(Arrays.asList(currentPlannerMarkedIUs)); markedIUsToRemove.removeAll(Arrays.asList(targetPlannerMarkedIUs)); request.removeInstallableUnits((IInstallableUnit[]) markedIUsToRemove.toArray(new IInstallableUnit[markedIUsToRemove.size()])); } private static void synchronizeProfileProperties(ProfileChangeRequest request, IProfile current, IProfile target) { Map profilePropertiesToSet = new HashMap(target.getProperties()); for (Iterator it = current.getProperties().entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String newValue = (String) profilePropertiesToSet.get(key); if (newValue == null) { request.removeProfileProperty(key); } else if (newValue.equals(entry.getValue())) profilePropertiesToSet.remove(key); } for (Iterator it = profilePropertiesToSet.entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); request.setProfileProperty(key, value); } } public static class FormerStateProfile implements IProfile { private String profileId; private HashMap profileProperties = new HashMap(); private HashMap iuProfileProperties = new HashMap(); private Set ius = new HashSet(); public FormerStateProfile(IInstallableUnit profileIU, IProfile profile, ProvisioningContext context) throws ProvisionException { String profileTypeProperty = profileIU.getProperty(IInstallableUnit.PROP_TYPE_PROFILE); if (profileTypeProperty == null || !Boolean.valueOf(profileTypeProperty).booleanValue()) throw new ProvisionException(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, "Not a profile type IU")); profileId = profileIU.getId(); for (Iterator it = profileIU.getProperties().entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); if (key.startsWith(IUPROP_PREFIX)) { int postIndex = key.indexOf(FormerState.IUPROP_POSTFIX, FormerState.IUPROP_PREFIX.length()); String iuId = key.substring(FormerState.IUPROP_PREFIX.length(), postIndex); Map iuProperties = (Map) iuProfileProperties.get(iuId); if (iuProperties == null) { iuProperties = new HashMap(); iuProfileProperties.put(iuId, iuProperties); } String iuPropertyKey = key.substring(postIndex + FormerState.IUPROP_POSTFIX.length()); iuProperties.put(iuPropertyKey, entry.getValue()); } else { profileProperties.put(key, entry.getValue()); } } profileProperties.remove(IInstallableUnit.PROP_TYPE_PROFILE); - List extraIUs = new ArrayList(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); + List extraIUs = new ArrayList(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); extraIUs.add(profileIU); IInstallableUnit[] availableIUs = SimplePlanner.gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), context.getMetadataRepositories(), context, new NullProgressMonitor()); Dictionary snapshotSelectionContext = SimplePlanner.createSelectionContext(profileProperties); IInstallableUnit[] allIUs = new IInstallableUnit[] {profileIU}; Slicer slicer = new Slicer(allIUs, availableIUs, snapshotSelectionContext); IQueryable slice = slicer.slice(allIUs, new NullProgressMonitor()); if (slice == null) throw new ProvisionException(slicer.getStatus()); Projector projector = new Projector(slice, snapshotSelectionContext); projector.encode(allIUs, new NullProgressMonitor()); IStatus s = projector.invokeSolver(new NullProgressMonitor()); if (s.getSeverity() == IStatus.ERROR) { //log the error from the new solver so it is not lost LogHelper.log(s); if (!"true".equalsIgnoreCase(context == null ? null : context.getProperty("org.eclipse.equinox.p2.disable.error.reporting"))) { //We invoke the old resolver to get explanations for now IStatus oldResolverStatus = new NewDependencyExpander(allIUs, null, availableIUs, snapshotSelectionContext, false).expand(new NullProgressMonitor()); if (!oldResolverStatus.isOK()) s = oldResolverStatus; } throw new ProvisionException(s); } ius.addAll(projector.extractSolution()); ius.remove(profileIU); } public Map getInstallableUnitProperties(IInstallableUnit iu) { Map iuProperties = (Map) iuProfileProperties.get(iu.getId()); if (iuProperties == null) { return Collections.EMPTY_MAP; } return Collections.unmodifiableMap(iuProperties); } public String getInstallableUnitProperty(IInstallableUnit iu, String key) { return (String) getInstallableUnitProperties(iu).get(key); } public Map getLocalProperties() { return Collections.unmodifiableMap(profileProperties); } public String getLocalProperty(String key) { return (String) profileProperties.get(key); } public IProfile getParentProfile() { return null; } public String getProfileId() { return profileId; } public Map getProperties() { return Collections.unmodifiableMap(profileProperties); } public String getProperty(String key) { return (String) profileProperties.get(key); } public String[] getSubProfileIds() { return null; } public long getTimestamp() { return 0; } public boolean hasSubProfiles() { return false; } public boolean isRootProfile() { return true; } public Collector query(Query query, Collector collector, IProgressMonitor monitor) { return query.perform(ius.iterator(), collector); } public Collector available(Query query, Collector collector, IProgressMonitor monitor) { return query(query, collector, monitor); } } }
true
true
public FormerStateProfile(IInstallableUnit profileIU, IProfile profile, ProvisioningContext context) throws ProvisionException { String profileTypeProperty = profileIU.getProperty(IInstallableUnit.PROP_TYPE_PROFILE); if (profileTypeProperty == null || !Boolean.valueOf(profileTypeProperty).booleanValue()) throw new ProvisionException(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, "Not a profile type IU")); profileId = profileIU.getId(); for (Iterator it = profileIU.getProperties().entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); if (key.startsWith(IUPROP_PREFIX)) { int postIndex = key.indexOf(FormerState.IUPROP_POSTFIX, FormerState.IUPROP_PREFIX.length()); String iuId = key.substring(FormerState.IUPROP_PREFIX.length(), postIndex); Map iuProperties = (Map) iuProfileProperties.get(iuId); if (iuProperties == null) { iuProperties = new HashMap(); iuProfileProperties.put(iuId, iuProperties); } String iuPropertyKey = key.substring(postIndex + FormerState.IUPROP_POSTFIX.length()); iuProperties.put(iuPropertyKey, entry.getValue()); } else { profileProperties.put(key, entry.getValue()); } } profileProperties.remove(IInstallableUnit.PROP_TYPE_PROFILE); List extraIUs = new ArrayList(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); extraIUs.add(profileIU); IInstallableUnit[] availableIUs = SimplePlanner.gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), context.getMetadataRepositories(), context, new NullProgressMonitor()); Dictionary snapshotSelectionContext = SimplePlanner.createSelectionContext(profileProperties); IInstallableUnit[] allIUs = new IInstallableUnit[] {profileIU}; Slicer slicer = new Slicer(allIUs, availableIUs, snapshotSelectionContext); IQueryable slice = slicer.slice(allIUs, new NullProgressMonitor()); if (slice == null) throw new ProvisionException(slicer.getStatus()); Projector projector = new Projector(slice, snapshotSelectionContext); projector.encode(allIUs, new NullProgressMonitor()); IStatus s = projector.invokeSolver(new NullProgressMonitor()); if (s.getSeverity() == IStatus.ERROR) { //log the error from the new solver so it is not lost LogHelper.log(s); if (!"true".equalsIgnoreCase(context == null ? null : context.getProperty("org.eclipse.equinox.p2.disable.error.reporting"))) { //We invoke the old resolver to get explanations for now IStatus oldResolverStatus = new NewDependencyExpander(allIUs, null, availableIUs, snapshotSelectionContext, false).expand(new NullProgressMonitor()); if (!oldResolverStatus.isOK()) s = oldResolverStatus; } throw new ProvisionException(s); } ius.addAll(projector.extractSolution()); ius.remove(profileIU); }
public FormerStateProfile(IInstallableUnit profileIU, IProfile profile, ProvisioningContext context) throws ProvisionException { String profileTypeProperty = profileIU.getProperty(IInstallableUnit.PROP_TYPE_PROFILE); if (profileTypeProperty == null || !Boolean.valueOf(profileTypeProperty).booleanValue()) throw new ProvisionException(new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, "Not a profile type IU")); profileId = profileIU.getId(); for (Iterator it = profileIU.getProperties().entrySet().iterator(); it.hasNext();) { Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); if (key.startsWith(IUPROP_PREFIX)) { int postIndex = key.indexOf(FormerState.IUPROP_POSTFIX, FormerState.IUPROP_PREFIX.length()); String iuId = key.substring(FormerState.IUPROP_PREFIX.length(), postIndex); Map iuProperties = (Map) iuProfileProperties.get(iuId); if (iuProperties == null) { iuProperties = new HashMap(); iuProfileProperties.put(iuId, iuProperties); } String iuPropertyKey = key.substring(postIndex + FormerState.IUPROP_POSTFIX.length()); iuProperties.put(iuPropertyKey, entry.getValue()); } else { profileProperties.put(key, entry.getValue()); } } profileProperties.remove(IInstallableUnit.PROP_TYPE_PROFILE); List extraIUs = new ArrayList(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()); extraIUs.add(profileIU); IInstallableUnit[] availableIUs = SimplePlanner.gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), context.getMetadataRepositories(), context, new NullProgressMonitor()); Dictionary snapshotSelectionContext = SimplePlanner.createSelectionContext(profileProperties); IInstallableUnit[] allIUs = new IInstallableUnit[] {profileIU}; Slicer slicer = new Slicer(allIUs, availableIUs, snapshotSelectionContext); IQueryable slice = slicer.slice(allIUs, new NullProgressMonitor()); if (slice == null) throw new ProvisionException(slicer.getStatus()); Projector projector = new Projector(slice, snapshotSelectionContext); projector.encode(allIUs, new NullProgressMonitor()); IStatus s = projector.invokeSolver(new NullProgressMonitor()); if (s.getSeverity() == IStatus.ERROR) { //log the error from the new solver so it is not lost LogHelper.log(s); if (!"true".equalsIgnoreCase(context == null ? null : context.getProperty("org.eclipse.equinox.p2.disable.error.reporting"))) { //We invoke the old resolver to get explanations for now IStatus oldResolverStatus = new NewDependencyExpander(allIUs, null, availableIUs, snapshotSelectionContext, false).expand(new NullProgressMonitor()); if (!oldResolverStatus.isOK()) s = oldResolverStatus; } throw new ProvisionException(s); } ius.addAll(projector.extractSolution()); ius.remove(profileIU); }
diff --git a/core/components/descriptors/src/main/java/org/mobicents/slee/container/component/validator/SbbComponentValidator.java b/core/components/descriptors/src/main/java/org/mobicents/slee/container/component/validator/SbbComponentValidator.java index 4ff37eba5..b1f8c8730 100644 --- a/core/components/descriptors/src/main/java/org/mobicents/slee/container/component/validator/SbbComponentValidator.java +++ b/core/components/descriptors/src/main/java/org/mobicents/slee/container/component/validator/SbbComponentValidator.java @@ -1,1969 +1,1969 @@ /** * Start time:17:06:21 2009-01-30<br> * Project: mobicents-jainslee-server-core<br> * * @author <a href="mailto:[email protected]">baranowb - Bartosz Baranowski * </a> * @author <a href="mailto:[email protected]"> Alexandre Mendonca </a> */ package org.mobicents.slee.container.component.validator; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.slee.EventTypeID; import javax.slee.SLEEException; import javax.slee.SbbID; import javax.slee.profile.ProfileID; import javax.slee.profile.ProfileSpecificationID; import javax.slee.profile.UnrecognizedProfileNameException; import javax.slee.profile.UnrecognizedProfileTableNameException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.mobicents.slee.container.component.ComponentRepository; import org.mobicents.slee.container.component.EventTypeComponent; import org.mobicents.slee.container.component.ProfileSpecificationComponent; import org.mobicents.slee.container.component.SbbComponent; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.SbbDescriptorImpl; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.MEnvEntry; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.references.MEventTypeRef; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.references.MProfileSpecRef; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.references.MSbbRef; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MEventEntry; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MGetChildRelationMethod; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MGetProfileCMPMethod; import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MSbbCMPField; /** * Start time:17:06:21 2009-01-30<br> * Project: mobicents-jainslee-server-core<br> * base validator for sbb components. It validates all sbb class constraints. * However it does not check referential constraints and similar. Checks that * have to be done before this class is used are: reference checks(this includes * dependencies), field values - like duplicate cmps, duplicate entries. * * @author <a href="mailto:[email protected]">baranowb - Bartosz Baranowski * </a> * @author <a href="mailto:[email protected]"> Alexandre Mendonca </a> */ public class SbbComponentValidator implements Validator { public static final String _SBB_AS_SBB_ACTIVITY_CONTEXT_INTERFACE = "asSbbActivityContextInterface"; public static final String _SBB_GET_CHILD_RELATION_SIGNATURE_PART = "[]"; private SbbComponent component = null; private ComponentRepository repository = null; private final static transient Logger logger = Logger.getLogger(SbbComponentValidator.class); private final static Set<String> _PRIMITIVES; static { Set<String> tmp = new HashSet<String>(); tmp.add("int"); tmp.add("boolean"); tmp.add("byte"); tmp.add("char"); tmp.add("double"); tmp.add("float"); tmp.add("long"); tmp.add("short"); _PRIMITIVES = Collections.unmodifiableSet(tmp); } private final static Set<String> _ENV_ENTRIES_TYPES; static { Set<String> tmp = new HashSet<String>(); tmp.add(Integer.TYPE.getName()); tmp.add(Boolean.TYPE.getName()); tmp.add(Byte.TYPE.getName()); tmp.add(Character.TYPE.getName()); tmp.add(Double.TYPE.getName()); tmp.add(Float.TYPE.getName()); tmp.add(Long.TYPE.getName()); tmp.add(Short.TYPE.getName()); tmp.add(String.class.getName()); _ENV_ENTRIES_TYPES = Collections.unmodifiableSet(tmp); } public boolean validate() { boolean valid = true; // Uf here we go try { if (!validateDescriptor()) { valid = false; return valid; } Map<String, Method> abstractMehotds, superClassesAbstractMethod, concreteMethods, superClassesConcreteMethods; abstractMehotds = ClassUtils.getAbstractMethodsFromClass(this.component.getAbstractSbbClass()); superClassesAbstractMethod = ClassUtils.getAbstractMethodsFromSuperClasses(this.component.getAbstractSbbClass()); concreteMethods = ClassUtils.getConcreteMethodsFromClass(this.component.getAbstractSbbClass()); superClassesConcreteMethods = ClassUtils.getConcreteMethodsFromSuperClasses(this.component.getAbstractSbbClass()); if (!validateAbstractClassConstraints(concreteMethods, superClassesConcreteMethods)) { valid = false; } if (!validateCmpFileds(abstractMehotds, superClassesAbstractMethod)) { valid = false; } if (!validateEventHandlers(abstractMehotds, superClassesAbstractMethod, concreteMethods, superClassesAbstractMethod)) { valid = false; } if (!validateGetChildRelationMethods(abstractMehotds, superClassesAbstractMethod)) { valid = false; } if (!validateGetProfileCmpInterfaceMethods(abstractMehotds, superClassesAbstractMethod)) { valid = false; } if (!validateSbbActivityContextInterface(abstractMehotds, superClassesAbstractMethod)) { valid = false; } if (!validateSbbLocalInterface(concreteMethods, superClassesConcreteMethods)) { valid = false; } if (!validateSbbUsageParameterInterface(abstractMehotds, superClassesAbstractMethod)) { valid = false; } if (!validateEnvEntries()) { valid = false; } // now lets test abstract methods, we have to remove all of them by // now? if (abstractMehotds.size() > 0 || superClassesAbstractMethod.size() > 0) { valid = false; if(logger.isEnabledFor(Level.ERROR)) logger .error(this.component.getDescriptor().getSbbID() + " : violates sbb constraints, it declares more abstract methods than SLEE is bound to implement. Methods directly from class: " + Arrays.toString(abstractMehotds.keySet().toArray()) + ", methods from super classes: " + Arrays.toString(superClassesAbstractMethod.keySet().toArray())); } } catch (Exception e) { e.printStackTrace(); valid = false; } return valid; } public void setComponentRepository(ComponentRepository repository) { this.repository = repository; } public SbbComponent getComponent() { return component; } public void setComponent(SbbComponent component) { this.component = component; } /** * Sbb abstract class(general rule � methods cannot start neither with �ejb� * nor �sbb�) * <ul> * <li>(1.1 ?) must have package declaration * <li>must implement in some way javax.slee.Sbb(only methods from interface * can have �sbb� prefix) * <ul> * <li>each method defined must be implemented as public � not abstract, * final or static * </ul> * <li>must be public and abstract * <li>must have public no arg constructor * <li>must implement sbbExceptionThrown method * <ul> * <li> * public, not abstract, final or static no return type 3 arguments: * java.lang.Exception, java.lang.Object, * javax.slee.ActivityContextInterface * </ul> * <li>must implement sbbRolledBack * <ul> * <li>method must be public, not abstract, final or static * <li>no return type * <li>with single argument - javax.slee.RoledBackContext * </ul> * <li>there is no finalize method * </ul> * * @return */ boolean validateAbstractClassConstraints(Map<String, Method> concreteMethods, Map<String, Method> concreteSuperClassesMethods) { String errorBuffer = new String(""); boolean passed = true; // Presence of those classes must be checked elsewhere Class sbbAbstractClass = this.component.getAbstractSbbClass(); // Must be public and abstract int modifiers = sbbAbstractClass.getModifiers(); // check that the class modifiers contain abstratc and public if (!Modifier.isAbstract(modifiers) || !Modifier.isPublic(modifiers)) { errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must be public and abstract", "6.1", errorBuffer); } // 1.1 - must be in package if (this.component.isSlee11()) { Package declaredPackage = sbbAbstractClass.getPackage(); if (declaredPackage == null || declaredPackage.getName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must be defined inside package space", "6.1", errorBuffer); } } // Public no arg constructor - can it have more ? // sbbAbstractClass.getConstructor // FIXME: no arg constructor has signature "()V" when added from // javaassist we check for such constructor and if its public try { Constructor constructor = sbbAbstractClass.getConstructor(); int conMod = constructor.getModifiers(); if (!Modifier.isPublic(conMod)) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must have public constructor ", "6.1", errorBuffer); } } catch (SecurityException e) { e.printStackTrace(); passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must have no arg constructor, error:" + e.getMessage(), "6.1", errorBuffer); } catch (NoSuchMethodException e) { e.printStackTrace(); passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must have no arg constructor, error:" + e.getMessage(), "6.1", errorBuffer); } // Must implements javax.slee.Sbb - and each method there defined, only // those methods and two above can have "sbb" prefix // those methods MUST be in concrete methods map, later we will use them // to see if there is ant "sbbXXXX" method // Check if we implement javax.slee.Sbb - either directly or from super // class Class javaxSleeSbbInterface = ClassUtils.checkInterfaces(sbbAbstractClass, "javax.slee.Sbb"); // sbbAbstractClass.getI if (javaxSleeSbbInterface == null) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must implement, directly or indirectly, the javax.slee.Sbb interface.", "6.1", errorBuffer); } // FIXME: add check for finalize method // Now we have to check methods from javax.slee.Sbb // This takes care of method throws clauses if (javaxSleeSbbInterface != null) { // if it is, we dont have those methods for sure, or maybe we do, // implemnted by hand // either way its a failure // We want only java.slee.Sbb methods :) Method[] sbbLifecycleMethods = javaxSleeSbbInterface.getDeclaredMethods(); for (Method lifecycleMehtod : sbbLifecycleMethods) { // It must be implemented - so only in concrete methods, if we // are left with one not checked bang, its an error String methodKey = ClassUtils.getMethodKey(lifecycleMehtod); Method concreteLifeCycleImpl = null; if (concreteMethods.containsKey(methodKey)) { concreteLifeCycleImpl = concreteMethods.remove(methodKey); } else if (concreteSuperClassesMethods.containsKey(methodKey)) { concreteLifeCycleImpl = concreteSuperClassesMethods.remove(methodKey); } else { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must implement life cycle methods, it lacks concrete implementation of: " + lifecycleMehtod.getName(), "6.1.1", errorBuffer); continue; } // now we now there is such method, its not private and abstract // If we are here its not null int lifeCycleModifier = concreteLifeCycleImpl.getModifiers(); if (!Modifier.isPublic(lifeCycleModifier) || Modifier.isStatic(lifeCycleModifier) || Modifier.isFinal(lifeCycleModifier)) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must implement life cycle methods, which can not be static, final or not public, method: " + lifecycleMehtod.getName(), "6.1.1", errorBuffer); } } } // there can not be any method which start with ejb/sbb - we removed // every from concrete, lets iterate over those sets for (Method concreteMethod : concreteMethods.values()) { if (concreteMethod.getName().startsWith("ejb") || concreteMethod.getName().startsWith("sbb")) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " with method: " + concreteMethod.getName(), "6.12", errorBuffer); } if (concreteMethod.getName().compareTo("finalize") == 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must not implement \"finalize\" method.", "6.1", errorBuffer); } } for (Method concreteMethod : concreteSuperClassesMethods.values()) { if (concreteMethod.getName().startsWith("ejb") || concreteMethod.getName().startsWith("sbb")) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " with method from super classes: " + concreteMethod.getName(), "6.12", errorBuffer); } if (concreteMethod.getName().compareTo("finalize") == 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "sbb abstract class must not implement \"finalize\" method. Its implemented by super class.", "6.1", errorBuffer); } } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; } /** * This method checks for presence of * * @param sbbAbstractClassAbstraMethod * @param sbbAbstractClassAbstraMethodFromSuperClasses * @return */ boolean validateSbbActivityContextInterface(Map<String, Method> sbbAbstractClassAbstraMethod, Map<String, Method> sbbAbstractClassAbstraMethodFromSuperClasses) { if (this.component.getDescriptor().getSbbClasses().getSbbActivityContextInterface() == null) { // FIXME: add check for asSbbActivityContextInteface method ? This // will be catched at the end of check anyway if (logger.isDebugEnabled()) { logger.debug(this.component.getDescriptor().getSbbID() + " : No Sbb activity context interface defined"); } return true; } String errorBuffer = new String(""); boolean passed = true; Class sbbAbstractClass = this.component.getAbstractSbbClass(); Method asACIMethod = null; // lets go through methods of sbbAbstract class, for (Method someMethod : sbbAbstractClassAbstraMethod.values()) { if (someMethod.getName().compareTo(_SBB_AS_SBB_ACTIVITY_CONTEXT_INTERFACE) == 0) { // we have a winner, possibly - we have to check parameter // list, cause someone can create abstract method(or crap, // it can be concrete) with different parametrs, in case its // abstract, it will fail later on if (someMethod.getParameterTypes().length == 1 && someMethod.getParameterTypes()[0].getName().compareTo("javax.slee.ActivityContextInterface") == 0) { asACIMethod = someMethod; break; } } } if (asACIMethod == null) for (Method someMethod : sbbAbstractClassAbstraMethodFromSuperClasses.values()) { if (someMethod.getName().compareTo(_SBB_AS_SBB_ACTIVITY_CONTEXT_INTERFACE) == 0) { // we have a winner, possibly - we have to check // parameter // list, cause someone can create abstract method(or // crap, // it can be concrete) with different parametrs, in case // its // abstract, it will fail later on if (someMethod.getParameterTypes().length == 1 && someMethod.getParameterTypes()[0].getName().compareTo("javax/slee/ActivityContextInterface") == 0) { asACIMethod = someMethod; break; } } } if (asACIMethod == null) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " must imlement narrow method asSbbActivityContextInterface", "7.7.2", errorBuffer); } else { // must be public, abstract? FIXME: not native? int asACIMethodModifiers = asACIMethod.getModifiers(); if (!Modifier.isPublic(asACIMethodModifiers) || !Modifier.isAbstract(asACIMethodModifiers) || Modifier.isNative(asACIMethodModifiers)) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " narrow method asSbbActivityContextInterface must be public,abstract and not native.", "7.7.2", errorBuffer); } // now this misery comes to play, return type check Class returnType = asACIMethod.getReturnType(); // Must return something from Sbb defined aci class inheritance // tree Class definedReturnType = this.component.getActivityContextInterface(); if (returnType.getName().compareTo("void") == 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " narrow method asSbbActivityContextInterface must have return type.", "7.7.2", errorBuffer); } else if (returnType.equals(definedReturnType)) { // its ok // } else if (ClassUtils.checkInterfaces(definedReturnType, // returnType // .getName()) != null) { } else { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " narrow method asSbbActivityContextInterface has wrong return type: " + returnType, "7.7.2", errorBuffer); } // no throws clause if (asACIMethod.getExceptionTypes() != null && asACIMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " narrow method asSbbActivityContextInterface must not have throws clause.", "7.7.2", errorBuffer); } } // Even if we fail above we can do some checks on ACI if its present. // this has to be present Class sbbActivityContextInterface = this.component.getActivityContextInterface(); // ACI VALIDATION // (1.1) = must be declared in package if (this.component.isSlee11() && sbbActivityContextInterface.getPackage() == null) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface must be declared in package.", "7.5", errorBuffer); } if (!Modifier.isPublic(sbbActivityContextInterface.getModifiers())) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface must be declared as public.", "7.5", errorBuffer); } // We can have here ACI objects and java primitives, ugh, both methods // dont have to be shown passed = checkSbbAciFieldsConstraints(this.component.getActivityContextInterface()); // finally lets remove asSbb method form abstract lists, this is used // later to determine methods that didnt match any sbb definition if (asACIMethod != null) { sbbAbstractClassAbstraMethod.remove(ClassUtils.getMethodKey(asACIMethod)); sbbAbstractClassAbstraMethodFromSuperClasses.remove(ClassUtils.getMethodKey(asACIMethod)); } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; } /** * This method validates all methods in ACI interface: * <ul> * <li>set/get methods and parameter names as in CMP fields decalration * <li>methods must * <ul> * <li>be public, abstract * <li>setters must have one param * <li>getters return type must match setter type * <li>allowe types are: primitives and serilizable types * </ul> * </ul> * <br> * Sbb descriptor provides method to obtain aci field names, if this test * passes it means that all fields there should be correct and can be used * to verify aliases * * @param sbbAciInterface * @return */ boolean checkSbbAciFieldsConstraints(Class sbbAciInterface) { boolean passed = true; String errorBuffer = new String(""); try { if (!sbbAciInterface.isInterface()) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface MUST be an interface.", "7.5", errorBuffer); return passed; } // here we need all fields :) HashSet<String> ignore = new HashSet<String>(); ignore.add("javax.slee.ActivityContextInterface"); // FIXME: we could go other way, run this for each super interface // we // have??? Map<String, Method> aciInterfacesDefinedMethods = ClassUtils.getAllInterfacesMethods(sbbAciInterface, ignore); // Here we will store fields name-type - if there is getter and // setter, // type must match!!! Map<String, Class> localNameToType = new HashMap<String, Class>(); for (String methodKey : aciInterfacesDefinedMethods.keySet()) { Method fieldMethod = aciInterfacesDefinedMethods.get(methodKey); String methodName = fieldMethod.getName(); if (!(methodName.startsWith("get") || methodName.startsWith("set"))) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface can have only getter/setter methods.", "7.5.1", errorBuffer); continue; } // let us get field name: String fieldName = methodName.replaceFirst("set", "").replaceFirst("get", ""); if (!Character.isUpperCase(fieldName.charAt(0))) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface can have only getter/setter methods - 4th char in those methods must be capital.", "7.5.1", errorBuffer); } // check throws clause. // number of parameters if (fieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface getter method must have empty throws clause: " + fieldMethod.getName(), "7.5.1", errorBuffer); } boolean isGetter = methodName.startsWith("get"); Class fieldType = null; if (isGetter) { // no params if (fieldMethod.getParameterTypes() != null && fieldMethod.getParameterTypes().length > 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface getter method must not have parameters: " + fieldMethod.getName(), "7.5.1", errorBuffer); } fieldType = fieldMethod.getReturnType(); if (fieldType.getName().compareTo("void") == 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface getter method must have return type: " + fieldMethod.getName(), "7.5.1", errorBuffer); } } else { if (fieldMethod.getParameterTypes() != null && fieldMethod.getParameterTypes().length != 1) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface setter method must single parameter: " + fieldMethod.getName(), "7.5.1", errorBuffer); // Here we quick fail continue; } fieldType = fieldMethod.getParameterTypes()[0]; if (fieldMethod.getReturnType().getName().compareTo("void") != 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface setter method must not have return type: " + fieldMethod.getName(), "7.5.1", errorBuffer); } } // Field type can be primitive and serialzable if (!(_PRIMITIVES.contains(fieldType.getName()) || ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null)) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface field(" + fieldName + ") has wrong type, only primitives and serializable: " + fieldType, "7.5.1", errorBuffer); // we fail here continue; } if (localNameToType.containsKey(fieldName)) { Class storedType = localNameToType.get(fieldName); if (!storedType.equals(fieldType)) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + " sbb activity context interface has wrong definition of parameter - setter and getter types do not match: " + fieldName + ", type1: " + fieldType.getName() + " typ2:" + storedType.getName(), "7.5.1", errorBuffer); // we fail here continue; } } else { // simply store localNameToType.put(fieldName, fieldType); } } // FIXME: add check against components get aci fields ? } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateGetChildRelationMethods(Map<String, Method> sbbAbstractClassAbstractMethod, Map<String, Method> sbbAbstractClassAbstractMethodFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); // FIXME: its cant be out of scope, since its byte.... // we look for method key for (MGetChildRelationMethod mMetod : this.component.getDescriptor().getSbbClasses().getSbbAbstractClass().getChildRelationMethods().values()) { if (mMetod.getDefaultPriority() > 127 || mMetod.getDefaultPriority() < -128) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "Defined get child relation method priority for method: " + mMetod.getChildRelationMethodName() + " is out of scope!!", "6.8", errorBuffer); } // This is key == <<methodName>>()Ljavax/slee/ChildRelation // We it makes sure that method name, parameters, and return type is // ok. String methodKey = mMetod.getChildRelationMethodName() + _SBB_GET_CHILD_RELATION_SIGNATURE_PART; Method childRelationMethod = null; childRelationMethod = sbbAbstractClassAbstractMethod.get(methodKey); if (childRelationMethod == null) { childRelationMethod = sbbAbstractClassAbstractMethodFromSuperClasses.get(methodKey); } if (childRelationMethod == null) { passed = false; errorBuffer = appendToBuffer( this.component.getAbstractSbbClass() + "Defined get child rekatuib method: " + mMetod.getChildRelationMethodName() + " is not matched by any abstract method, either its not abstract, is private, has parameter or has wrong return type(should be javax.slee.ChildRelation)!!", "6.8", errorBuffer); // we fail fast here continue; } // if we are here we have to check throws clause, prefix - it cant // be ejb or sbb if (childRelationMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "Defined get child relation method priority for method: " + mMetod.getChildRelationMethodName() + " must hot have throws clause", "6.8", errorBuffer); } if (childRelationMethod.getName().startsWith("ejb") || childRelationMethod.getName().startsWith("sbb")) { // this is checked for concrete methods only passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "Defined get child relation method priority for method: " + mMetod.getChildRelationMethodName() + " has wrong prefix, it can not start with \"ejb\" or \"sbb\".!", "6.8", errorBuffer); } // remove, we will later determine methods that were not implemented // by this if (childRelationMethod != null) { sbbAbstractClassAbstractMethod.remove(methodKey); sbbAbstractClassAbstractMethodFromSuperClasses.remove(methodKey); } } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; } boolean validateSbbLocalInterface(Map<String, Method> sbbAbstractClassConcreteMethods, Map<String, Method> sbbAbstractClassConcreteFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); try { if (this.component.getDescriptor().getSbbClasses().getSbbLocalInterface() == null) return passed; Class sbbLocalInterfaceClass = this.component.getSbbLocalInterfaceClass(); if (!sbbLocalInterfaceClass.isInterface()) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "DSbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " MUST be an interface!", "5.6", errorBuffer); return passed; } Class genericSbbLocalInterface = ClassUtils.checkInterfaces(sbbLocalInterfaceClass, "javax.slee.SbbLocalObject"); if (genericSbbLocalInterface == null) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "DSbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " does not implement javax.slee.SbbLocalInterface super interface in any way!!!", "5.6", errorBuffer); } int sbbLocalInterfaceClassModifiers = sbbLocalInterfaceClass.getModifiers(); if (this.component.isSlee11() && sbbLocalInterfaceClass.getPackage() == null) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "SbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " is nto defined in package", "6.5", errorBuffer); } if (!Modifier.isPublic(sbbLocalInterfaceClassModifiers)) { passed = false; errorBuffer = appendToBuffer(this.component.getAbstractSbbClass() + "SbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " must be public!", "5.6", errorBuffer); } Set<String> ignore = new HashSet<String>(); ignore.add("javax.slee.SbbLocalObject"); ignore.add("java.lang.Object"); Map<String, Method> interfaceMethods = ClassUtils.getAllInterfacesMethods(sbbLocalInterfaceClass, ignore); // here we have all defined methods in interface, we have to checkif // their names do not start with sbb/ejb and if they are contained // in // collections with concrete methods from sbb //System.err.println(sbbAbstractClassConcreteMethods.keySet()); for (Method methodToCheck : interfaceMethods.values()) { if (methodToCheck.getName().startsWith("ejb") || methodToCheck.getName().startsWith("sbb")) { passed = false; errorBuffer = appendToBuffer("Method from SbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " starts with wrong prefix: " + methodToCheck.getName(), "5.6", errorBuffer); } Method methodFromSbbClass = ClassUtils.getMethodFromMap(methodToCheck.getName(), methodToCheck.getParameterTypes(), sbbAbstractClassConcreteMethods, sbbAbstractClassConcreteFromSuperClasses); if (methodFromSbbClass == null) { passed = false; errorBuffer = appendToBuffer("Method from SbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " with name: " + methodToCheck.getName() + " is not implemented by sbb class or its super classes!", "5.6", errorBuffer); // we fails fast here continue; } // XXX: Note this does not check throws clause, only name and // signature // this side // FIXME: Note that we dont check modifier, is this corerct if (!(methodFromSbbClass.getName().compareTo(methodToCheck.getName()) == 0) || !methodFromSbbClass.getReturnType().equals(methodToCheck.getReturnType()) || !Arrays.equals(methodFromSbbClass.getParameterTypes(), methodToCheck.getParameterTypes()) || !Arrays.equals((Object[]) methodFromSbbClass.getExceptionTypes(), (Object[]) methodToCheck.getExceptionTypes())) { passed = false; errorBuffer = appendToBuffer("Method from SbbLocalInterface: " + sbbLocalInterfaceClass.getName() + " with name: " + methodToCheck.getName() + " is not implemented by sbb class or its super classes. Its visibility, throws clause or modifiers are different!", "5.6", errorBuffer); // we fails fast here continue; } } // FIXME: is this ok, is it needed ? If not checked here, abstract // methods check will make it fail later, but not concrete ? // now lets check javax.slee.SbbLocalObject methods - sbb cant have // those implemented or defined as abstract. } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateCmpFileds(Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); List<MSbbCMPField> cmpFields = this.component.getDescriptor().getSbbClasses().getSbbAbstractClass().getCmpFields(); for (MSbbCMPField entry : cmpFields) { String fieldName = entry.getCmpFieldName(); Character c = fieldName.charAt(0); // we must start with lower case letter if (!Character.isLetter(c) || !Character.isLowerCase(c)) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field name. Name must start with lower case letter: " + fieldName, "6.5.1", errorBuffer); // In this case we should fail fast? continue; } // lets find method in abstracts, it cannot be implemented // FIXME: do we have to check concrete as well? String methodPartFieldName = Character.toUpperCase(c) + fieldName.substring(1); String getterName = "get" + methodPartFieldName; String setterName = "set" + methodPartFieldName; Method getterFieldMethod = null; Method setterFieldMethod = null; // Both have to be present, lets do trick, first we can get getter // so we know field type and can get setter Class sbbAbstractClass = this.component.getAbstractSbbClass(); getterFieldMethod = ClassUtils.getMethodFromMap(getterName, new Class[0], sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (getterFieldMethod == null) { errorBuffer = appendToBuffer("Failed to validate CMP field. Could not find getter method: " + getterName + ". Both accessors must be present.", "6.5.1", errorBuffer); passed = false; // we fail fast here continue; } Class fieldType = getterFieldMethod.getReturnType(); setterFieldMethod = ClassUtils.getMethodFromMap(setterName, new Class[] { fieldType }, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (setterFieldMethod == null) { errorBuffer = appendToBuffer("Failed to validate CMP field. Could not find setter method: " + setterName + " with single parameter of type: " + getterFieldMethod.getReturnType() + ". Both accessors must be present and have the same type.", "6.5.1", errorBuffer); passed = false; // we fail fast here continue; } // not needed // if (setterFieldMethod.getReturnType().getName().compareTo("void") // != 0) { // errorBuffer = appendToBuffer( // "Failed to validate CMP field. Setter method: " // + setterName + " has return type of: " // + setterFieldMethod.getReturnType(), "6.5.1", // errorBuffer); // } // we know methods are here, we must check if they are - abstract, // public, what about static and native? int modifiers = getterFieldMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isAbstract(modifiers)) { errorBuffer = appendToBuffer("Failed to validate CMP field. Getter method is either public or not abstract: " + getterName, "6.5.1", errorBuffer); passed = false; } modifiers = setterFieldMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isAbstract(modifiers)) { errorBuffer = appendToBuffer("Failed to validate CMP field. Setter method is neither public nor abstract: " + getterName, "6.5.1", errorBuffer); passed = false; } // 1.1 and 1.0 allow // primitives and serializables and if reference is present sbbLo or // derived type boolean referenceIsPresent = entry.getSbbAliasRef() != null; boolean isSbbLOFieldType = false; if (_PRIMITIVES.contains(fieldType.getName())) { // do nothing, this does not include wrapper classes, isSbbLOFieldType = false; } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.SbbLocalObject") != null) { // FIXME: is there a better way? // in 1.0 sbb ref MUST be present always // again, if referenced sbb has wrong type of SbbLO defined here // it mail fail, however it a matter of validating other // component isSbbLOFieldType = true; /* * emmartins: page 70 of slee 1.1 specs say that sbb-alias-ref is now optional (it doesn't say it is just for slee 1.1 components) * if (!this.component.isSlee11() && !referenceIsPresent) { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. In JSLEE 1.0 Sbb reference element must be present when CMP type is Sbb Local Object or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); // for this we fail fast, nothing more to do. continue; } */ // now its a check for 1.1 and 1.0 if (referenceIsPresent) { SbbID referencedSbb = null; SbbComponent referencedComponent = null; if (entry.getSbbAliasRef().equals(this.component.getDescriptor().getSbbAlias())) { referencedSbb = this.component.getSbbID(); referencedComponent = this.component; } else { for (MSbbRef mSbbRef : this.component.getDescriptor().getSbbRefs()) { if (mSbbRef.getSbbAlias().equals(entry.getSbbAliasRef())) { referencedSbb = new SbbID(mSbbRef.getSbbName(), mSbbRef.getSbbVendor(), mSbbRef.getSbbVersion()); break; } } if (referencedSbb == null) { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field references sbb with alias "+entry.getSbbAliasRef()+" but no sbb ref has been found with which such alias. Field: " + fieldName, "6.5.1", errorBuffer); continue; } else { referencedComponent = this.repository.getComponentByID(referencedSbb); if (referencedComponent == null) { //FIXME: throw or fail? throw new SLEEException("Referenced (in cmp field) "+referencedSbb+" was not found in component repository, this should not happen since dependencies were already verified"); } } } // FIXME: field type must be equal to defined or must be // javax.slee.SbbLocalObject = what about intermediate types // X -> Y -> SbbLocalObject - and we have Y? - if (fieldType.getName().compareTo(referencedComponent.getSbbLocalInterfaceClass().getName()) == 0) { + if (referencedComponent.getDescriptor().getSbbLocalInterface()!=null && fieldType.getName().compareTo(referencedComponent.getDescriptor().getSbbLocalInterface().getSbbLocalInterfaceName()) == 0) { // its ok } else if (fieldType.getName().compareTo("javax.slee.SbbLocalObject") == 0) { // its ok? } else if (ClassUtils.checkInterfaces(referencedComponent.getSbbLocalInterfaceClass(), fieldType.getName()) != null) { // its ok } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for sbb entities must be of generic type javax.slee.SbbLocalObject or type declared by referenced sbb, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } /* * emmartins: page 70 of slee 1.1 specs say that sbb-alias-ref is now optional * else { // here only 1.1 will go if (fieldType.getName().compareTo("javax.slee.SbbLocalObject") == 0) { // its ok? } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for sbb entities must be of generic type javax.slee.SbbLocalObject when no reference to sbb is present, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } */ // FIXME: end of checks here? } else if (this.component.isSlee11()) { isSbbLOFieldType = false; if (fieldType.getName().compareTo("javax.slee.EventContext") == 0) { // we do nothing, its ok. } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.profile.ProfileLocalObject") != null) { // FIXME: there is no ref maybe we shoudl check referenced // profiles? } else if (ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null) { // do nothing, its check same as below } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.ActivityContextInterface") != null) { // we can haev generic ACI or derived object defined in // sbb,... uffff Class definedAciType = this.component.getActivityContextInterface(); if (definedAciType.getName().compareTo(fieldType.getName()) == 0) { // do nothing } else if (fieldType.getName().compareTo("javax.slee.ActivityContextInterface") == 0) { // do nothing } else if (ClassUtils.checkInterfaces(definedAciType, fieldType.getName()) != null) { // do anything } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for ACIs must be of generic type javax.slee.ActivityContextInterface or defined by sbb Custom ACI, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } else { // FAIL passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type must be: primitive,serializable, SbbLocalObject or derived,(1.1): EventContext, ActivityContextInterface or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } else if (ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null) { // This is tricky, someone can implement serializable in SbbLO // derived objec, however it could not be valid SBB LO(for // isntance wrong Sbb,not extending SbbLO) but if this was first // it would pass test without checks on constraints // this includes all serializables and primitive wrapper classes isSbbLOFieldType = false; } else { // FAIL } if (referenceIsPresent && !isSbbLOFieldType) { // this is not permited? passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Sbb reefrence is present when field type is not Sbb Local Object or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } // Check throws clause if (getterFieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field. Getter method declared throws clause: " + Arrays.toString(getterFieldMethod.getExceptionTypes()), "6.5.1", errorBuffer); } if (setterFieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field. Setter method declared throws clause: " + Arrays.toString(setterFieldMethod.getExceptionTypes()), "6.5.1", errorBuffer); } // else remove those from list sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(setterFieldMethod)); sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(getterFieldMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(setterFieldMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(getterFieldMethod)); } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; } boolean validateEventHandlers(Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses, Map<String, Method> concreteMethods, Map<String, Method> concreteMethodsFromSuperClasses) { boolean passed = true; // String errorBuffer = new String(""); // Abstract methods are for fire methods, we have to check them and // remove if present :) Map<EventTypeID,MEventEntry> events = this.component.getDescriptor().getEventEntries(); for (MEventEntry event : events.values()) { switch (event.getEventDirection()) { case Fire: if (!validateFireEvent(event, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses)) { passed = false; } break; case Receive: if (!validateReceiveEvent(event, concreteMethods, concreteMethodsFromSuperClasses)) { passed = false; } break; case FireAndReceive: if (!validateFireEvent(event, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses)) { passed = false; } if (!validateReceiveEvent(event, concreteMethods, concreteMethodsFromSuperClasses)) { passed = false; } break; } } return passed; } boolean validateReceiveEvent(MEventEntry event, Map<String, Method> concreteMethods, Map<String, Method> concreteMethodsFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); try { // we can have only one receive method EventTypeComponent eventTypeComponent = this.repository.getComponentByID(event.getEventReference().getComponentID()); if (eventTypeComponent == null) { passed = false; errorBuffer = appendToBuffer( "Failed to validate event receive method. reference points to event comopnent that has not been validated, event name: " + event.getEventName(), "8.5.2", errorBuffer); return passed; } Class eventClass = eventTypeComponent.getEventTypeClass(); Class sbbAbstractClass = this.component.getAbstractSbbClass(); String methodName = "on" + event.getEventName(); // lets look for basic event handler // the thing with each event handler is that aci can be generic or // sbb // custom.... Method receiveMethod = null; Method receiveMethodCustomACI = null; boolean receiverWithContextPresent = false; boolean receiverWithoutContextPresent = false; if (this.component.isSlee11()) { receiveMethod = ClassUtils.getMethodFromMap(methodName, new Class[] { eventClass, javax.slee.ActivityContextInterface.class, javax.slee.EventContext.class }, concreteMethods, concreteMethodsFromSuperClasses); if (this.component.getActivityContextInterface() != null) receiveMethodCustomACI = ClassUtils.getMethodFromMap(methodName, new Class[] { eventClass, this.component.getActivityContextInterface(), javax.slee.EventContext.class }, concreteMethods, concreteMethodsFromSuperClasses); // is there any clever way to lookup those? // ok, here only one method can be present if (receiveMethod != null && receiveMethodCustomACI != null) { // we cant have both passed = false; errorBuffer = appendToBuffer( "Failed to validate event receive method. Sbb can not define event receive method with generic and custom aci, event name: " + event.getEventName(), "8.5.2", errorBuffer); } // now here we are sure we have one or none if (receiveMethod != null) { receiverWithContextPresent = true; if (!validateReceiveMethodSignature(receiveMethod, "8.5.2")) { passed = false; } receiveMethod = null; } else if (receiveMethodCustomACI != null) { receiverWithContextPresent = true; if (!validateReceiveMethodSignature(receiveMethodCustomACI, "8.5.2")) { passed = false; } receiveMethodCustomACI = null; } } // this is for all receiveMethod = ClassUtils.getMethodFromMap(methodName, new Class[] { eventClass, javax.slee.ActivityContextInterface.class }, concreteMethods, concreteMethodsFromSuperClasses); if (this.component.getActivityContextInterface() != null) receiveMethodCustomACI = ClassUtils.getMethodFromMap(methodName, new Class[] { eventClass, this.component.getActivityContextInterface() }, concreteMethods, concreteMethodsFromSuperClasses); // is there any clever way to lookup those? // ok, here only one method can be present if (receiveMethod != null && receiveMethodCustomACI != null) { // we cant have both passed = false; errorBuffer = appendToBuffer( "Failed to validate event receive method. Sbb can not define event receive method with generic and custom aci, event name: " + event.getEventName(), "8.5.2", errorBuffer); } // now here we are sure we have one or none if (receiveMethod != null) { receiverWithoutContextPresent = true; if (!validateReceiveMethodSignature(receiveMethod, "8.5.2")) passed = false; } else if (receiveMethodCustomACI != null) { receiverWithoutContextPresent = true; if (!validateReceiveMethodSignature(receiveMethodCustomACI, "8.5.2")) passed = false; } // here we have to check, only one can be present if (receiverWithoutContextPresent && receiverWithContextPresent) { passed = false; errorBuffer = appendToBuffer( "Failed to validate event receive method. Sbb can not define event receive method with and without EventContext, only one can be present: " + event.getEventName(), "8.5.2", errorBuffer); } if (!receiverWithoutContextPresent && !receiverWithContextPresent) { passed = false; errorBuffer = appendToBuffer( "Failed to validate event receive method. Sbb must define handler method when direction is \"XReceive\". Event receiver has different name or wrong parameters, event: " + event.getEventName(), "8.5.2", errorBuffer); } // now its time for initial event selector if (event.isInitialEvent() && event.getInitialEventSelectorMethod() != null && !validateInitialEventSelector(event, concreteMethods, concreteMethodsFromSuperClasses)) { // FIXME: we dont check if variable or selector method is // present passed = false; } } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateInitialEventSelector(MEventEntry event, Map<String, Method> concreteMethods, Map<String, Method> concreteMethodsFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); try { if (event.getInitialEventSelectorMethod().startsWith("ejb") || event.getInitialEventSelectorMethod().startsWith("sbb")) { passed = false; errorBuffer = appendToBuffer("Initial event seelctor method can not start with \"ejb\" or \"sbb\", method name: " + event.getInitialEventSelectorMethod(), "8.6.4", errorBuffer); } Method m = ClassUtils.getMethodFromMap(event.getInitialEventSelectorMethod(), new Class[] { javax.slee.InitialEventSelector.class }, concreteMethods, concreteMethodsFromSuperClasses); if (m == null) { // TODO Auto-generated catch block // e.printStackTrace(); passed = false; errorBuffer = appendToBuffer("Failed to find initial event selector method, method name: " + event.getInitialEventSelectorMethod(), "8.6.4", errorBuffer); return passed; } // FIXME: It has to be concrete... int modifiers = m.getModifiers(); if (Modifier.isAbstract(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate initial event selector method" + " Receive method is abstract, method name: " + m.getName(), "8.6.4", errorBuffer); } if (!Modifier.isPublic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate initial event selector method" + " Receive method is not public, method name: " + m.getName(), "8.6.4", errorBuffer); } if (Modifier.isStatic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate initial event selector method" + " Receive method is static, method name: " + m.getName(), "8.6.4", errorBuffer); } if (Modifier.isFinal(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate initial event selector method" + " Receive method is final, method name: " + m.getName(), "8.6.4", errorBuffer); } // FIXME: native? if (m.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Method has throws clause, method: " + m.getName(), "8.6.4", errorBuffer); } if (m.getReturnType().getName().compareTo("javax.slee.InitialEventSelector") != 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate initial event selector method" + " Return type must be javax.slee.InitialEventSelector, method: " + m.getName(), "8.6.4", errorBuffer); } } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateReceiveMethodSignature(Method m, String section) { boolean passed = true; String errorBuffer = new String(""); int modifiers = m.getModifiers(); if (Modifier.isAbstract(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate receive event method" + " Receive method is abstract, method name: " + m.getName(), section, errorBuffer); } if (!Modifier.isPublic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate receive event method" + " Receive method is not public, method name: " + m.getName(), section, errorBuffer); } if (Modifier.isStatic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate receive event method" + " Receive method is static, method name: " + m.getName(), section, errorBuffer); } if (Modifier.isFinal(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate receive event method" + " Receive method is final, method name: " + m.getName(), section, errorBuffer); } // FIXME: native? // FIXME: only runtime exceptions? if (m.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Fire method is has throws clause, method: " + m.getName(), section, errorBuffer); } if (m.getReturnType().getName().compareTo("void") != 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate Receive event method" + " Receive method cant have return type, method: " + m.getName(), section, errorBuffer); } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; } boolean validateFireEvent(MEventEntry event, Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); try { // we can have only one receive method EventTypeComponent eventTypeComponent = this.repository.getComponentByID(event.getEventReference().getComponentID()); if (eventTypeComponent == null) { passed = false; errorBuffer = appendToBuffer( "Failed to validate event receive method. reference points to event comopnent that has not been validated, event name: " + event.getEventName(), "8.5.2", errorBuffer); return passed; } Class eventClass = eventTypeComponent.getEventTypeClass(); Class sbbAbstractClass = this.component.getAbstractSbbClass(); String methodName = "fire" + event.getEventName(); // we we have to validate abstract methods :} // this is 1.0 Method fireMethod = null; // this is 1.1 Method fire11Method = null; // FIXME: is it ok to refer directly to: // javax.slee.ActivityContextInterface.class ?? fireMethod = ClassUtils.getMethodFromMap(methodName, new Class[] { eventClass, javax.slee.ActivityContextInterface.class, javax.slee.Address.class }, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); fire11Method = ClassUtils.getMethodFromMap(methodName, new Class[] { eventClass, javax.slee.ActivityContextInterface.class, javax.slee.Address.class, javax.slee.ServiceID.class }, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (!this.component.isSlee11()) { if (fireMethod == null) { // fail fast passed = false; errorBuffer = appendToBuffer( "Failed to validate fire vent method, JSLEE 1.0 sbbs have to have method with signature: public abstract void fire<event name>(<event class> event,ActivityContextInterface activity,Address address);. Event name: " + event.getEventName(), "8.5.1", errorBuffer); // the end return passed; } } else { if (fireMethod == null && fire11Method == null) { // fail fast passed = false; errorBuffer = appendToBuffer( "Failed to validate fire vent method, JSLEE 1.1 sbbs have to have one of those methods. Sbb class either does not declare them, method has wrong parameters/name or is concrete. Event name: " + event.getEventName(), "8.5.1", errorBuffer); // the end return passed; } } if (this.component.isSlee11() && fire11Method != null && !validateFireMethodSignature(fire11Method, "8.5.1")) { passed = false; } // if we are here we are either 1.0 in which case this method is not // null, or we are 1.1 in which case it could be if (fireMethod != null && !validateFireMethodSignature(fireMethod, "8.5.1")) { passed = false; } if (fire11Method != null) { sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(fire11Method)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(fire11Method)); } if (fireMethod != null) { sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(fireMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(fireMethod)); } } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateFireMethodSignature(Method m, String section) { boolean passed = true; String errorBuffer = new String(""); int modifiers = m.getModifiers(); if (!Modifier.isAbstract(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Fire method is not abstract, method name: " + m.getName(), section, errorBuffer); } if (!Modifier.isPublic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Fire method is not public, method name: " + m.getName(), section, errorBuffer); } if (Modifier.isStatic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Fire method is static, method name: " + m.getName(), section, errorBuffer); } // FIXME: native? if (m.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Fire method has throws clause, method: " + m.getName(), section, errorBuffer); } if (m.getReturnType().getName().compareTo("void") != 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate fire event method" + " Fire method cant have return type, method: " + m.getName(), section, errorBuffer); } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; } boolean validateSbbUsageParameterInterface(Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses) { if (this.component.getUsageParametersInterface() == null) { return true; } else { return UsageInterfaceValidator.validateSbbUsageParameterInterface(this.component, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); } } boolean validateGetProfileCmpInterfaceMethods(Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses) { // Section 6.7 boolean passed = true; String errorBuffer = new String(""); try { Map<String,MGetProfileCMPMethod> profileCmpMethods = this.component.getDescriptor().getSbbClasses().getSbbAbstractClass() .getProfileCMPMethods(); if (profileCmpMethods.size() == 0) { return passed; } // eh, else we have to do all checks for (MGetProfileCMPMethod method : profileCmpMethods.values()) { if (method.getProfileCmpMethodName().startsWith("ejb") || method.getProfileCmpMethodName().startsWith("sbb")) { passed = false; errorBuffer = appendToBuffer( "Wrong method prefix, get profile cmp interface method must not start with \"sbb\" or \"ejb\", method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); } Method m = ClassUtils.getMethodFromMap(method.getProfileCmpMethodName(), new Class[] { ProfileID.class }, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); ; if (m == null) { passed = false; errorBuffer = appendToBuffer( "Failed to find method in sbb abstract class - it either does not exist,is private or has wrong parameter, method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); continue; } int modifiers = m.getModifiers(); if (!Modifier.isPublic(modifiers)) { passed = false; errorBuffer = appendToBuffer("Get profile CMP interface method must be public, method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); continue; } if (!Modifier.isAbstract(modifiers)) { passed = false; errorBuffer = appendToBuffer("Get profile CMP interface method must be abstract, method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); continue; } Class methodReturnType = m.getReturnType(); // this is referential integrity Map<String, ProfileSpecificationID> map = new HashMap<String, ProfileSpecificationID>(); for (MProfileSpecRef rf : this.component.getDescriptor().getProfileSpecRefs()) { map.put(rf.getProfileSpecAlias(), rf.getComponentID()); } ProfileSpecificationID profileID = map.get(method.getProfileSpecAliasRef()); ProfileSpecificationComponent profileComponent = this.repository.getComponentByID(profileID); if (profileComponent == null) { // this means referential integrity is nto met, possibly // class is not loaded passed = false; errorBuffer = appendToBuffer("Get profile CMP interface method references profile which has not been validated, method: " + method.getProfileCmpMethodName() + " , reference: " + method.getProfileSpecAliasRef(), "6,7", errorBuffer); continue; } Class profileDefinedCMPInterface = profileComponent.getProfileCmpInterfaceClass(); if (methodReturnType.getName().compareTo(profileDefinedCMPInterface.getName()) != 0 && ClassUtils.checkInterfaces(profileDefinedCMPInterface, methodReturnType.getName()) == null) { passed = false; errorBuffer = appendToBuffer( "Get profile CMP interface method has wrong return type - it has to be defined CMP interface or its super class, method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); } Class[] exceptions = m.getExceptionTypes(); // UnrecognizedProfileTableNameException, // UnrecognizedProfileNameException if (exceptions.length != 2) { passed = false; errorBuffer = appendToBuffer( "Get profile CMP interface method has wrong number of exceptions, it can throw only two - UnrecognizedProfileNameException and UnrecognizedProfileTableNameException, method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); } HashSet<String> possibleExcpetions = new HashSet<String>(); possibleExcpetions.add(UnrecognizedProfileTableNameException.class.getName()); possibleExcpetions.add(UnrecognizedProfileNameException.class.getName()); for (Class c : exceptions) { if (possibleExcpetions.contains(c.getName())) { possibleExcpetions.remove(c.getName()); } } if (possibleExcpetions.size() != 0) { passed = false; errorBuffer = appendToBuffer("Get profile CMP interface method has decalration of throws clause, it lacks following exceptions: " + Arrays.toString(possibleExcpetions.toArray()) + " , method: " + method.getProfileCmpMethodName(), "6,7", errorBuffer); } } } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateEnvEntries() { boolean passed = true; String errorBuffer = new String(""); try { List<MEnvEntry> envEntries = this.component.getDescriptor().getEnvEntries(); for (MEnvEntry e : envEntries) { if (!_ENV_ENTRIES_TYPES.contains(e.getEnvEntryType())) { passed = false; errorBuffer = appendToBuffer("Env entry has wrong type: " + e.getEnvEntryType() + " , method: " + e.getEnvEntryName(), "6.13", errorBuffer); } } } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } boolean validateDescriptor() { boolean passed = true; String errorBuffer = new String(""); try { Map<String, MProfileSpecRef> declaredProfileReferences = new HashMap<String, MProfileSpecRef>(); Map<String, MSbbRef> declaredSbbreferences = new HashMap<String, MSbbRef>(); SbbDescriptorImpl descriptor = this.component.getDescriptor(); for (MProfileSpecRef ref : descriptor.getProfileSpecRefs()) { // if(ref.getProfileSpecAlias()==null || // ref.getProfileSpecAlias().compareTo("")==0) if (ref.getProfileSpecAlias() != null && ref.getProfileSpecAlias().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares profile spec reference without alias, id: " + ref.getComponentID(), "3.1.8", errorBuffer); } else if (declaredProfileReferences.containsKey(ref.getProfileSpecAlias())) { passed = false; errorBuffer = appendToBuffer( "Sbb descriptor declares profile spec reference more than once, alias: " + ref.getProfileSpecAlias(), "3.1.8", errorBuffer); } else { declaredProfileReferences.put(ref.getProfileSpecAlias(), ref); } } for (MSbbRef ref : descriptor.getSbbRefs()) { if (ref.getSbbAlias() == null || ref.getSbbAlias().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares sbb reference without alias, id: " + ref.getComponentID(), "3.1.8", errorBuffer); } else if (declaredSbbreferences.containsKey(ref.getSbbAlias())) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares sbb reference more than once, alias: " + ref.getSbbAlias(), "3.1.8", errorBuffer); } else { declaredSbbreferences.put(ref.getSbbAlias(), ref); } } Set<String> childRelationMethods = new HashSet<String>(); for (MGetChildRelationMethod childMethod : descriptor.getSbbClasses().getSbbAbstractClass().getChildRelationMethods().values()) { if (childMethod.getChildRelationMethodName() == null || childMethod.getChildRelationMethodName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer( "Sbb descriptor declares child relation method without name, alias: " + childMethod.getSbbAliasRef(), "3.1.8", errorBuffer); } else if (childMethod.getSbbAliasRef() == null || childMethod.getSbbAliasRef().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares child relation method without sbb alias, name: " + childMethod.getChildRelationMethodName(), "3.1.8", errorBuffer); } else if (!declaredSbbreferences.containsKey(childMethod.getSbbAliasRef())) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares child relation method with sbb alias that has not been declared, name: " + childMethod.getChildRelationMethodName() + ", method alias: " + childMethod.getSbbAliasRef(), "3.1.8", errorBuffer); } else if (childRelationMethods.contains(childMethod.getChildRelationMethodName())) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares child relation method more than once, name: " + childMethod.getChildRelationMethodName(), "3.1.8", errorBuffer); } else { childRelationMethods.add(childMethod.getChildRelationMethodName()); } } Map<String, MSbbCMPField> declaredCmps = new HashMap<String, MSbbCMPField>(); for (MSbbCMPField cmp : descriptor.getSbbClasses().getSbbAbstractClass().getCmpFields()) { if (cmp.getCmpFieldName() == null || cmp.getCmpFieldName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor cmp field with empty name.", "3.1.8", errorBuffer); } else if (cmp.getSbbAliasRef() != null && cmp.getSbbAliasRef().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares cmp field with empty sbb alias, name: " + cmp.getCmpFieldName(), "3.1.8", errorBuffer); } else if (declaredCmps.containsKey(cmp.getCmpFieldName())) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares cmp field more than once, name: " + cmp.getCmpFieldName(), "3.1.8", errorBuffer); } else { declaredCmps.put(cmp.getCmpFieldName(), cmp); } } // This is required, events can be decalred once Map<String, MEventTypeRef> eventNameToReference = new HashMap<String, MEventTypeRef>(); for (MEventEntry event : descriptor.getEventEntries().values()) { if (event.getEventName() == null || event.getEventName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares event with empty event name, ", "3.1.8", errorBuffer); } else if (eventNameToReference.containsKey(event.getEventName())) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares event with the same event name more than once, name: " + event.getEventName(), "3.1.8", errorBuffer); } else if (eventNameToReference.containsValue(event.getEventReference())) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares event reference twice, events can be references only once, name: " + event.getEventName(), "3.1.8", errorBuffer); } else { eventNameToReference.put(event.getEventName(), event.getEventReference()); } } // FIXME: ra part? if (descriptor.getSbbClasses().getSbbActivityContextInterface() != null) { if (descriptor.getSbbClasses().getSbbActivityContextInterface().getInterfaceName() == null || descriptor.getSbbClasses().getSbbActivityContextInterface().getInterfaceName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares sbb aci which is empty.", "3.1.8", errorBuffer); } } if (descriptor.getSbbClasses().getSbbLocalInterface() != null) { if (descriptor.getSbbClasses().getSbbLocalInterface().getSbbLocalInterfaceName() == null || descriptor.getSbbClasses().getSbbLocalInterface().getSbbLocalInterfaceName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares sbb local interface which is empty.", "3.1.8", errorBuffer); } } if (descriptor.getSbbClasses().getSbbUsageParametersInterface() != null) { if (descriptor.getSbbClasses().getSbbUsageParametersInterface().getUsageParametersInterfaceName() == null || descriptor.getSbbClasses().getSbbUsageParametersInterface().getUsageParametersInterfaceName().compareTo("") == 0) { passed = false; errorBuffer = appendToBuffer("Sbb descriptor declares sbb usage interface which is empty.", "3.1.8", errorBuffer); } } } finally { if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } } return passed; } /** * See section 1.3 of jslee 1.1 specs * * @return */ boolean validateCompatibilityReferenceConstraints() { boolean passed = true; String errorBuffer = new String(""); try { if (!this.component.isSlee11()) { // A 1.0 SBB must not reference or use a 1.1 Profile // Specification. This must be enforced by a 1.1 // JAIN SLEE. for (MProfileSpecRef profileReference : this.component.getDescriptor().getProfileSpecRefs()) { ProfileSpecificationComponent specComponent = this.repository.getComponentByID(profileReference.getComponentID()); if (specComponent == null) { // should not happen passed = false; errorBuffer = appendToBuffer("Referenced "+profileReference.getComponentID()+" was not found in component repository, this should not happen since dependencies were already verified","1.3", errorBuffer); } else { if (specComponent.isSlee11()) { passed = false; errorBuffer = appendToBuffer("Sbb is following 1.0 JSLEE contract, it must not reference 1.1 profile specification: " + profileReference.getComponentID(), "1.3", errorBuffer); } } } } } finally { if (!passed) { if (logger.isEnabledFor(Level.ERROR)) { logger.error(errorBuffer); } } } return passed; } protected String appendToBuffer(String message, String section, String buffer) { buffer += (this.component.getDescriptor().getSbbID() + " : violates section " + section + " of jSLEE 1.1 specification : " + message + "\n"); return buffer; } }
true
true
boolean validateCmpFileds(Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); List<MSbbCMPField> cmpFields = this.component.getDescriptor().getSbbClasses().getSbbAbstractClass().getCmpFields(); for (MSbbCMPField entry : cmpFields) { String fieldName = entry.getCmpFieldName(); Character c = fieldName.charAt(0); // we must start with lower case letter if (!Character.isLetter(c) || !Character.isLowerCase(c)) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field name. Name must start with lower case letter: " + fieldName, "6.5.1", errorBuffer); // In this case we should fail fast? continue; } // lets find method in abstracts, it cannot be implemented // FIXME: do we have to check concrete as well? String methodPartFieldName = Character.toUpperCase(c) + fieldName.substring(1); String getterName = "get" + methodPartFieldName; String setterName = "set" + methodPartFieldName; Method getterFieldMethod = null; Method setterFieldMethod = null; // Both have to be present, lets do trick, first we can get getter // so we know field type and can get setter Class sbbAbstractClass = this.component.getAbstractSbbClass(); getterFieldMethod = ClassUtils.getMethodFromMap(getterName, new Class[0], sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (getterFieldMethod == null) { errorBuffer = appendToBuffer("Failed to validate CMP field. Could not find getter method: " + getterName + ". Both accessors must be present.", "6.5.1", errorBuffer); passed = false; // we fail fast here continue; } Class fieldType = getterFieldMethod.getReturnType(); setterFieldMethod = ClassUtils.getMethodFromMap(setterName, new Class[] { fieldType }, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (setterFieldMethod == null) { errorBuffer = appendToBuffer("Failed to validate CMP field. Could not find setter method: " + setterName + " with single parameter of type: " + getterFieldMethod.getReturnType() + ". Both accessors must be present and have the same type.", "6.5.1", errorBuffer); passed = false; // we fail fast here continue; } // not needed // if (setterFieldMethod.getReturnType().getName().compareTo("void") // != 0) { // errorBuffer = appendToBuffer( // "Failed to validate CMP field. Setter method: " // + setterName + " has return type of: " // + setterFieldMethod.getReturnType(), "6.5.1", // errorBuffer); // } // we know methods are here, we must check if they are - abstract, // public, what about static and native? int modifiers = getterFieldMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isAbstract(modifiers)) { errorBuffer = appendToBuffer("Failed to validate CMP field. Getter method is either public or not abstract: " + getterName, "6.5.1", errorBuffer); passed = false; } modifiers = setterFieldMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isAbstract(modifiers)) { errorBuffer = appendToBuffer("Failed to validate CMP field. Setter method is neither public nor abstract: " + getterName, "6.5.1", errorBuffer); passed = false; } // 1.1 and 1.0 allow // primitives and serializables and if reference is present sbbLo or // derived type boolean referenceIsPresent = entry.getSbbAliasRef() != null; boolean isSbbLOFieldType = false; if (_PRIMITIVES.contains(fieldType.getName())) { // do nothing, this does not include wrapper classes, isSbbLOFieldType = false; } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.SbbLocalObject") != null) { // FIXME: is there a better way? // in 1.0 sbb ref MUST be present always // again, if referenced sbb has wrong type of SbbLO defined here // it mail fail, however it a matter of validating other // component isSbbLOFieldType = true; /* * emmartins: page 70 of slee 1.1 specs say that sbb-alias-ref is now optional (it doesn't say it is just for slee 1.1 components) * if (!this.component.isSlee11() && !referenceIsPresent) { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. In JSLEE 1.0 Sbb reference element must be present when CMP type is Sbb Local Object or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); // for this we fail fast, nothing more to do. continue; } */ // now its a check for 1.1 and 1.0 if (referenceIsPresent) { SbbID referencedSbb = null; SbbComponent referencedComponent = null; if (entry.getSbbAliasRef().equals(this.component.getDescriptor().getSbbAlias())) { referencedSbb = this.component.getSbbID(); referencedComponent = this.component; } else { for (MSbbRef mSbbRef : this.component.getDescriptor().getSbbRefs()) { if (mSbbRef.getSbbAlias().equals(entry.getSbbAliasRef())) { referencedSbb = new SbbID(mSbbRef.getSbbName(), mSbbRef.getSbbVendor(), mSbbRef.getSbbVersion()); break; } } if (referencedSbb == null) { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field references sbb with alias "+entry.getSbbAliasRef()+" but no sbb ref has been found with which such alias. Field: " + fieldName, "6.5.1", errorBuffer); continue; } else { referencedComponent = this.repository.getComponentByID(referencedSbb); if (referencedComponent == null) { //FIXME: throw or fail? throw new SLEEException("Referenced (in cmp field) "+referencedSbb+" was not found in component repository, this should not happen since dependencies were already verified"); } } } // FIXME: field type must be equal to defined or must be // javax.slee.SbbLocalObject = what about intermediate types // X -> Y -> SbbLocalObject - and we have Y? if (fieldType.getName().compareTo(referencedComponent.getSbbLocalInterfaceClass().getName()) == 0) { // its ok } else if (fieldType.getName().compareTo("javax.slee.SbbLocalObject") == 0) { // its ok? } else if (ClassUtils.checkInterfaces(referencedComponent.getSbbLocalInterfaceClass(), fieldType.getName()) != null) { // its ok } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for sbb entities must be of generic type javax.slee.SbbLocalObject or type declared by referenced sbb, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } /* * emmartins: page 70 of slee 1.1 specs say that sbb-alias-ref is now optional * else { // here only 1.1 will go if (fieldType.getName().compareTo("javax.slee.SbbLocalObject") == 0) { // its ok? } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for sbb entities must be of generic type javax.slee.SbbLocalObject when no reference to sbb is present, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } */ // FIXME: end of checks here? } else if (this.component.isSlee11()) { isSbbLOFieldType = false; if (fieldType.getName().compareTo("javax.slee.EventContext") == 0) { // we do nothing, its ok. } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.profile.ProfileLocalObject") != null) { // FIXME: there is no ref maybe we shoudl check referenced // profiles? } else if (ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null) { // do nothing, its check same as below } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.ActivityContextInterface") != null) { // we can haev generic ACI or derived object defined in // sbb,... uffff Class definedAciType = this.component.getActivityContextInterface(); if (definedAciType.getName().compareTo(fieldType.getName()) == 0) { // do nothing } else if (fieldType.getName().compareTo("javax.slee.ActivityContextInterface") == 0) { // do nothing } else if (ClassUtils.checkInterfaces(definedAciType, fieldType.getName()) != null) { // do anything } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for ACIs must be of generic type javax.slee.ActivityContextInterface or defined by sbb Custom ACI, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } else { // FAIL passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type must be: primitive,serializable, SbbLocalObject or derived,(1.1): EventContext, ActivityContextInterface or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } else if (ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null) { // This is tricky, someone can implement serializable in SbbLO // derived objec, however it could not be valid SBB LO(for // isntance wrong Sbb,not extending SbbLO) but if this was first // it would pass test without checks on constraints // this includes all serializables and primitive wrapper classes isSbbLOFieldType = false; } else { // FAIL } if (referenceIsPresent && !isSbbLOFieldType) { // this is not permited? passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Sbb reefrence is present when field type is not Sbb Local Object or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } // Check throws clause if (getterFieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field. Getter method declared throws clause: " + Arrays.toString(getterFieldMethod.getExceptionTypes()), "6.5.1", errorBuffer); } if (setterFieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field. Setter method declared throws clause: " + Arrays.toString(setterFieldMethod.getExceptionTypes()), "6.5.1", errorBuffer); } // else remove those from list sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(setterFieldMethod)); sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(getterFieldMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(setterFieldMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(getterFieldMethod)); } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; }
boolean validateCmpFileds(Map<String, Method> sbbAbstractClassMethods, Map<String, Method> sbbAbstractMethodsFromSuperClasses) { boolean passed = true; String errorBuffer = new String(""); List<MSbbCMPField> cmpFields = this.component.getDescriptor().getSbbClasses().getSbbAbstractClass().getCmpFields(); for (MSbbCMPField entry : cmpFields) { String fieldName = entry.getCmpFieldName(); Character c = fieldName.charAt(0); // we must start with lower case letter if (!Character.isLetter(c) || !Character.isLowerCase(c)) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field name. Name must start with lower case letter: " + fieldName, "6.5.1", errorBuffer); // In this case we should fail fast? continue; } // lets find method in abstracts, it cannot be implemented // FIXME: do we have to check concrete as well? String methodPartFieldName = Character.toUpperCase(c) + fieldName.substring(1); String getterName = "get" + methodPartFieldName; String setterName = "set" + methodPartFieldName; Method getterFieldMethod = null; Method setterFieldMethod = null; // Both have to be present, lets do trick, first we can get getter // so we know field type and can get setter Class sbbAbstractClass = this.component.getAbstractSbbClass(); getterFieldMethod = ClassUtils.getMethodFromMap(getterName, new Class[0], sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (getterFieldMethod == null) { errorBuffer = appendToBuffer("Failed to validate CMP field. Could not find getter method: " + getterName + ". Both accessors must be present.", "6.5.1", errorBuffer); passed = false; // we fail fast here continue; } Class fieldType = getterFieldMethod.getReturnType(); setterFieldMethod = ClassUtils.getMethodFromMap(setterName, new Class[] { fieldType }, sbbAbstractClassMethods, sbbAbstractMethodsFromSuperClasses); if (setterFieldMethod == null) { errorBuffer = appendToBuffer("Failed to validate CMP field. Could not find setter method: " + setterName + " with single parameter of type: " + getterFieldMethod.getReturnType() + ". Both accessors must be present and have the same type.", "6.5.1", errorBuffer); passed = false; // we fail fast here continue; } // not needed // if (setterFieldMethod.getReturnType().getName().compareTo("void") // != 0) { // errorBuffer = appendToBuffer( // "Failed to validate CMP field. Setter method: " // + setterName + " has return type of: " // + setterFieldMethod.getReturnType(), "6.5.1", // errorBuffer); // } // we know methods are here, we must check if they are - abstract, // public, what about static and native? int modifiers = getterFieldMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isAbstract(modifiers)) { errorBuffer = appendToBuffer("Failed to validate CMP field. Getter method is either public or not abstract: " + getterName, "6.5.1", errorBuffer); passed = false; } modifiers = setterFieldMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isAbstract(modifiers)) { errorBuffer = appendToBuffer("Failed to validate CMP field. Setter method is neither public nor abstract: " + getterName, "6.5.1", errorBuffer); passed = false; } // 1.1 and 1.0 allow // primitives and serializables and if reference is present sbbLo or // derived type boolean referenceIsPresent = entry.getSbbAliasRef() != null; boolean isSbbLOFieldType = false; if (_PRIMITIVES.contains(fieldType.getName())) { // do nothing, this does not include wrapper classes, isSbbLOFieldType = false; } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.SbbLocalObject") != null) { // FIXME: is there a better way? // in 1.0 sbb ref MUST be present always // again, if referenced sbb has wrong type of SbbLO defined here // it mail fail, however it a matter of validating other // component isSbbLOFieldType = true; /* * emmartins: page 70 of slee 1.1 specs say that sbb-alias-ref is now optional (it doesn't say it is just for slee 1.1 components) * if (!this.component.isSlee11() && !referenceIsPresent) { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. In JSLEE 1.0 Sbb reference element must be present when CMP type is Sbb Local Object or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); // for this we fail fast, nothing more to do. continue; } */ // now its a check for 1.1 and 1.0 if (referenceIsPresent) { SbbID referencedSbb = null; SbbComponent referencedComponent = null; if (entry.getSbbAliasRef().equals(this.component.getDescriptor().getSbbAlias())) { referencedSbb = this.component.getSbbID(); referencedComponent = this.component; } else { for (MSbbRef mSbbRef : this.component.getDescriptor().getSbbRefs()) { if (mSbbRef.getSbbAlias().equals(entry.getSbbAliasRef())) { referencedSbb = new SbbID(mSbbRef.getSbbName(), mSbbRef.getSbbVendor(), mSbbRef.getSbbVersion()); break; } } if (referencedSbb == null) { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field references sbb with alias "+entry.getSbbAliasRef()+" but no sbb ref has been found with which such alias. Field: " + fieldName, "6.5.1", errorBuffer); continue; } else { referencedComponent = this.repository.getComponentByID(referencedSbb); if (referencedComponent == null) { //FIXME: throw or fail? throw new SLEEException("Referenced (in cmp field) "+referencedSbb+" was not found in component repository, this should not happen since dependencies were already verified"); } } } // FIXME: field type must be equal to defined or must be // javax.slee.SbbLocalObject = what about intermediate types // X -> Y -> SbbLocalObject - and we have Y? if (referencedComponent.getDescriptor().getSbbLocalInterface()!=null && fieldType.getName().compareTo(referencedComponent.getDescriptor().getSbbLocalInterface().getSbbLocalInterfaceName()) == 0) { // its ok } else if (fieldType.getName().compareTo("javax.slee.SbbLocalObject") == 0) { // its ok? } else if (ClassUtils.checkInterfaces(referencedComponent.getSbbLocalInterfaceClass(), fieldType.getName()) != null) { // its ok } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for sbb entities must be of generic type javax.slee.SbbLocalObject or type declared by referenced sbb, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } /* * emmartins: page 70 of slee 1.1 specs say that sbb-alias-ref is now optional * else { // here only 1.1 will go if (fieldType.getName().compareTo("javax.slee.SbbLocalObject") == 0) { // its ok? } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for sbb entities must be of generic type javax.slee.SbbLocalObject when no reference to sbb is present, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } */ // FIXME: end of checks here? } else if (this.component.isSlee11()) { isSbbLOFieldType = false; if (fieldType.getName().compareTo("javax.slee.EventContext") == 0) { // we do nothing, its ok. } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.profile.ProfileLocalObject") != null) { // FIXME: there is no ref maybe we shoudl check referenced // profiles? } else if (ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null) { // do nothing, its check same as below } else if (ClassUtils.checkInterfaces(fieldType, "javax.slee.ActivityContextInterface") != null) { // we can haev generic ACI or derived object defined in // sbb,... uffff Class definedAciType = this.component.getActivityContextInterface(); if (definedAciType.getName().compareTo(fieldType.getName()) == 0) { // do nothing } else if (fieldType.getName().compareTo("javax.slee.ActivityContextInterface") == 0) { // do nothing } else if (ClassUtils.checkInterfaces(definedAciType, fieldType.getName()) != null) { // do anything } else { passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type for ACIs must be of generic type javax.slee.ActivityContextInterface or defined by sbb Custom ACI, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } else { // FAIL passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Field type must be: primitive,serializable, SbbLocalObject or derived,(1.1): EventContext, ActivityContextInterface or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } } else if (ClassUtils.checkInterfaces(fieldType, "java.io.Serializable") != null) { // This is tricky, someone can implement serializable in SbbLO // derived objec, however it could not be valid SBB LO(for // isntance wrong Sbb,not extending SbbLO) but if this was first // it would pass test without checks on constraints // this includes all serializables and primitive wrapper classes isSbbLOFieldType = false; } else { // FAIL } if (referenceIsPresent && !isSbbLOFieldType) { // this is not permited? passed = false; errorBuffer = appendToBuffer( "Failed to validate CMP field. Sbb reefrence is present when field type is not Sbb Local Object or derived, field name: " + fieldName + " type: " + fieldType, "6.5.1", errorBuffer); } // Check throws clause if (getterFieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field. Getter method declared throws clause: " + Arrays.toString(getterFieldMethod.getExceptionTypes()), "6.5.1", errorBuffer); } if (setterFieldMethod.getExceptionTypes().length > 0) { passed = false; errorBuffer = appendToBuffer("Failed to validate CMP field. Setter method declared throws clause: " + Arrays.toString(setterFieldMethod.getExceptionTypes()), "6.5.1", errorBuffer); } // else remove those from list sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(setterFieldMethod)); sbbAbstractClassMethods.remove(ClassUtils.getMethodKey(getterFieldMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(setterFieldMethod)); sbbAbstractMethodsFromSuperClasses.remove(ClassUtils.getMethodKey(getterFieldMethod)); } if (!passed) { if(logger.isEnabledFor(Level.ERROR)) logger.error(errorBuffer); } return passed; }
diff --git a/api/src/main/java/org/jboss/shrinkwrap/api/ReflectionUtil.java b/api/src/main/java/org/jboss/shrinkwrap/api/ReflectionUtil.java index a4f6b75d..bd3a28c7 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/api/ReflectionUtil.java +++ b/api/src/main/java/org/jboss/shrinkwrap/api/ReflectionUtil.java @@ -1,103 +1,103 @@ /* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.shrinkwrap.api; import java.lang.reflect.Constructor; import com.sun.xml.internal.txw2.IllegalAnnotationException; /** * ReflectionUtil * * Helper class for creating new instances of a class * * @author <a href="mailto:[email protected]">Aslak Knutsen</a> * @version $Revision: $ */ final class ReflectionUtil { /** * Create a new instance by finding a constructor that matches the argumentTypes signature * using the arguments for instantiation. * * @param className Full classname of class to create * @param argumentTypes The constructor argument types * @param arguments The constructor arguments * @return a new instance * @throws IllegalArgumentException if className is null * @throws IllegalArgumentException if argumentTypes is null * @throws IllegalArgumentException if arguments is null * @throws RuntimeException if any exceptions during creation */ public static Object createInstance(String className, Class<?>[] argumentTypes, Object[] arguments) { if(className == null) { throw new IllegalArgumentException("ClassName must be specified"); } if(argumentTypes == null) { throw new IllegalAnnotationException("ArgumentTypes must be specified. Use empty array if no arguments"); } if(arguments == null) { throw new IllegalAnnotationException("Arguments must be specified. Use empty array if no arguments"); } try { Class<?> implClass = loadClass(className); Constructor<?> constructor = findConstructor(implClass, argumentTypes); - return (Path)constructor.newInstance(arguments); + return constructor.newInstance(arguments); } catch (Exception e) { throw new RuntimeException( "Could not create new instance of " + className + ", missing package from classpath?", e); } } //-------------------------------------------------------------------------------------|| // Class Members - Internal Helpers ---------------------------------------------------|| //-------------------------------------------------------------------------------------|| /** * Load the specified class using Thread Current Class Loader in a privileged block. */ private static Class<?> loadClass(String archiveImplClassName) throws Exception { return SecurityActions.getThreadContextClassLoader().loadClass(archiveImplClassName); } /** * Find a constructor that match the signature of given argumentTypes. */ private static Constructor<?> findConstructor(Class<?> archiveImplClazz, Class<?>... argumentTypes) throws Exception { return archiveImplClazz.getConstructor(argumentTypes); } //-------------------------------------------------------------------------------------|| // Constructor ------------------------------------------------------------------------|| //-------------------------------------------------------------------------------------|| /** * No instantiation */ private ReflectionUtil() { } }
true
true
public static Object createInstance(String className, Class<?>[] argumentTypes, Object[] arguments) { if(className == null) { throw new IllegalArgumentException("ClassName must be specified"); } if(argumentTypes == null) { throw new IllegalAnnotationException("ArgumentTypes must be specified. Use empty array if no arguments"); } if(arguments == null) { throw new IllegalAnnotationException("Arguments must be specified. Use empty array if no arguments"); } try { Class<?> implClass = loadClass(className); Constructor<?> constructor = findConstructor(implClass, argumentTypes); return (Path)constructor.newInstance(arguments); } catch (Exception e) { throw new RuntimeException( "Could not create new instance of " + className + ", missing package from classpath?", e); } }
public static Object createInstance(String className, Class<?>[] argumentTypes, Object[] arguments) { if(className == null) { throw new IllegalArgumentException("ClassName must be specified"); } if(argumentTypes == null) { throw new IllegalAnnotationException("ArgumentTypes must be specified. Use empty array if no arguments"); } if(arguments == null) { throw new IllegalAnnotationException("Arguments must be specified. Use empty array if no arguments"); } try { Class<?> implClass = loadClass(className); Constructor<?> constructor = findConstructor(implClass, argumentTypes); return constructor.newInstance(arguments); } catch (Exception e) { throw new RuntimeException( "Could not create new instance of " + className + ", missing package from classpath?", e); } }
diff --git a/src/main/java/org/jenkins/plugins/cloudbees/MavenArtifactFilePathSaver.java b/src/main/java/org/jenkins/plugins/cloudbees/MavenArtifactFilePathSaver.java index db19b2b..08b9b48 100644 --- a/src/main/java/org/jenkins/plugins/cloudbees/MavenArtifactFilePathSaver.java +++ b/src/main/java/org/jenkins/plugins/cloudbees/MavenArtifactFilePathSaver.java @@ -1,111 +1,110 @@ /* * Copyright 2010-2011, CloudBees Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jenkins.plugins.cloudbees; import hudson.Extension; import hudson.maven.*; import hudson.maven.reporters.MavenArtifact; import hudson.model.BuildListener; import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Olivier Lamy */ public class MavenArtifactFilePathSaver extends MavenReporter { @Override public boolean preBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { return true; } @Override public boolean preExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException { return true; } /* @Override public boolean leaveModule( MavenBuildProxy build, MavenProject pom, BuildListener listener ) throws InterruptedException, IOException { return postBuild( build, pom, listener ); } */ public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("post build " + (pom.getArtifact() != null) + ":" + (pom.getAttachedArtifacts() != null)); - if (pom.getArtifact() != null || pom.getAttachedArtifacts() != null) { + if (pom != null && pom.getArtifact() != null || pom.getAttachedArtifacts() != null) { final Set<MavenArtifactWithFilePath> mavenArtifacts = new HashSet<MavenArtifactWithFilePath>(); if (pom.getArtifact() != null) { final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact()); - if (mainArtifact != null) { + if (mainArtifact != null && pom.getArtifact() != null && pom.getArtifact().getFile() != null) { //TODO take of NPE !! mavenArtifacts.add(new MavenArtifactWithFilePath(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getArtifact().getFile().getPath(), pom.getArtifact().getType())); } } if (pom.getAttachedArtifacts()!=null) { // record attached artifacts final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>(); for (Artifact a : pom.getAttachedArtifacts()) { MavenArtifact ma = MavenArtifact.create(a); - if (ma != null) { - //TODO take of NPE !! + if (ma != null && pom.getArtifact() != null && pom.getArtifact().getFile() != null) { mavenArtifacts.add(new MavenArtifactWithFilePath(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getArtifact().getFile().getPath(), pom.getArtifact().getType())); } } } // record the action build.execute(new MavenBuildProxy.BuildCallable<Void, IOException>() { public Void call(MavenBuild build) throws IOException, InterruptedException { ArtifactFilePathSaveAction artifactFilePathSaveAction = build.getAction(ArtifactFilePathSaveAction.class); if (artifactFilePathSaveAction == null) { artifactFilePathSaveAction = new ArtifactFilePathSaveAction(mavenArtifacts); } else { artifactFilePathSaveAction.mavenArtifactWithFilePaths.addAll(mavenArtifacts); } build.addAction(artifactFilePathSaveAction); build.save(); return null; } }); } return true; } @Extension public static final class DescriptorImpl extends MavenReporterDescriptor { public String getDisplayName() { return MavenArtifactFilePathSaver.class.getName(); } public MavenReporter newAutoInstance(MavenModule module) { return new MavenArtifactFilePathSaver(); } } private static final long serialVersionUID = 1L; }
false
true
public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("post build " + (pom.getArtifact() != null) + ":" + (pom.getAttachedArtifacts() != null)); if (pom.getArtifact() != null || pom.getAttachedArtifacts() != null) { final Set<MavenArtifactWithFilePath> mavenArtifacts = new HashSet<MavenArtifactWithFilePath>(); if (pom.getArtifact() != null) { final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact()); if (mainArtifact != null) { //TODO take of NPE !! mavenArtifacts.add(new MavenArtifactWithFilePath(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getArtifact().getFile().getPath(), pom.getArtifact().getType())); } } if (pom.getAttachedArtifacts()!=null) { // record attached artifacts final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>(); for (Artifact a : pom.getAttachedArtifacts()) { MavenArtifact ma = MavenArtifact.create(a); if (ma != null) { //TODO take of NPE !! mavenArtifacts.add(new MavenArtifactWithFilePath(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getArtifact().getFile().getPath(), pom.getArtifact().getType())); } } } // record the action build.execute(new MavenBuildProxy.BuildCallable<Void, IOException>() { public Void call(MavenBuild build) throws IOException, InterruptedException { ArtifactFilePathSaveAction artifactFilePathSaveAction = build.getAction(ArtifactFilePathSaveAction.class); if (artifactFilePathSaveAction == null) { artifactFilePathSaveAction = new ArtifactFilePathSaveAction(mavenArtifacts); } else { artifactFilePathSaveAction.mavenArtifactWithFilePaths.addAll(mavenArtifacts); } build.addAction(artifactFilePathSaveAction); build.save(); return null; } }); } return true; }
public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("post build " + (pom.getArtifact() != null) + ":" + (pom.getAttachedArtifacts() != null)); if (pom != null && pom.getArtifact() != null || pom.getAttachedArtifacts() != null) { final Set<MavenArtifactWithFilePath> mavenArtifacts = new HashSet<MavenArtifactWithFilePath>(); if (pom.getArtifact() != null) { final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact()); if (mainArtifact != null && pom.getArtifact() != null && pom.getArtifact().getFile() != null) { //TODO take of NPE !! mavenArtifacts.add(new MavenArtifactWithFilePath(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getArtifact().getFile().getPath(), pom.getArtifact().getType())); } } if (pom.getAttachedArtifacts()!=null) { // record attached artifacts final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>(); for (Artifact a : pom.getAttachedArtifacts()) { MavenArtifact ma = MavenArtifact.create(a); if (ma != null && pom.getArtifact() != null && pom.getArtifact().getFile() != null) { mavenArtifacts.add(new MavenArtifactWithFilePath(pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getArtifact().getFile().getPath(), pom.getArtifact().getType())); } } } // record the action build.execute(new MavenBuildProxy.BuildCallable<Void, IOException>() { public Void call(MavenBuild build) throws IOException, InterruptedException { ArtifactFilePathSaveAction artifactFilePathSaveAction = build.getAction(ArtifactFilePathSaveAction.class); if (artifactFilePathSaveAction == null) { artifactFilePathSaveAction = new ArtifactFilePathSaveAction(mavenArtifacts); } else { artifactFilePathSaveAction.mavenArtifactWithFilePaths.addAll(mavenArtifacts); } build.addAction(artifactFilePathSaveAction); build.save(); return null; } }); } return true; }
diff --git a/src/com/android/phone/DataUsageListener.java b/src/com/android/phone/DataUsageListener.java index 6122a8ec..a72c088a 100644 --- a/src/com/android/phone/DataUsageListener.java +++ b/src/com/android/phone/DataUsageListener.java @@ -1,231 +1,233 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import com.android.phone.R; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.net.Uri; import android.net.ThrottleManager; import android.util.Log; import java.util.Calendar; import java.util.GregorianCalendar; import java.text.DateFormat; /** * Listener for broadcasts from ThrottleManager */ public class DataUsageListener { private ThrottleManager mThrottleManager; private Preference mCurrentUsagePref = null; private Preference mTimeFramePref = null; private Preference mThrottleRatePref = null; private Preference mSummaryPref = null; private PreferenceScreen mPrefScreen = null; private boolean mSummaryPrefEnabled = false; private final Context mContext; private IntentFilter mFilter; private BroadcastReceiver mReceiver; private int mPolicyThrottleValue; //in kbps private long mPolicyThreshold; private int mCurrentThrottleRate; private long mDataUsed; private Calendar mStart; private Calendar mEnd; public DataUsageListener(Context context, Preference summary, PreferenceScreen prefScreen) { mContext = context; mSummaryPref = summary; mPrefScreen = prefScreen; mSummaryPrefEnabled = true; initialize(); } public DataUsageListener(Context context, Preference currentUsage, Preference timeFrame, Preference throttleRate) { mContext = context; mCurrentUsagePref = currentUsage; mTimeFramePref = timeFrame; mThrottleRatePref = throttleRate; initialize(); } private void initialize() { mThrottleManager = (ThrottleManager) mContext.getSystemService(Context.THROTTLE_SERVICE); mStart = GregorianCalendar.getInstance(); mEnd = GregorianCalendar.getInstance(); mFilter = new IntentFilter(); mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION); mFilter.addAction(ThrottleManager.THROTTLE_ACTION); mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) { updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ, 0), intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE, 0), intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START, 0), intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END, 0)); } else if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) { updatePolicy(); } else if (ThrottleManager.THROTTLE_ACTION.equals(action)) { updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1)); } } }; } void resume() { mContext.registerReceiver(mReceiver, mFilter); updatePolicy(); } void pause() { mContext.unregisterReceiver(mReceiver); } private void updatePolicy() { /* Fetch values for default interface */ mPolicyThrottleValue = mThrottleManager.getCliffLevel(null, 1); mPolicyThreshold = mThrottleManager.getCliffThreshold(null, 1); if (mSummaryPref != null) { /* Settings preference */ /** * Remove data usage preference in settings * if policy change disables throttling */ if (mPolicyThreshold == 0) { if (mSummaryPrefEnabled) { mPrefScreen.removePreference(mSummaryPref); mSummaryPrefEnabled = false; } } else { if (!mSummaryPrefEnabled) { mSummaryPrefEnabled = true; mPrefScreen.addPreference(mSummaryPref); } } } updateUI(); } private void updateThrottleRate(int throttleRate) { mCurrentThrottleRate = throttleRate; updateUI(); } private void updateUsageStats(long readByteCount, long writeByteCount, long startTime, long endTime) { mDataUsed = readByteCount + writeByteCount; mStart.setTimeInMillis(startTime); mEnd.setTimeInMillis(endTime); updateUI(); } private void updateUI() { if (mPolicyThreshold == 0) return; int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold); long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis(); long currentTime = GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis(); int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cycleTime - currentTime); int daysLeft = cal.get(Calendar.DAY_OF_YEAR); + //cal.get() returns 365 for less than a day + if (daysLeft >= 365) daysLeft = 0; if (mCurrentUsagePref != null) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_usage_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold))); } } if (mTimeFramePref != null) { mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext, cycleThroughPercent, daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } if (mThrottleRatePref != null) { mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext, mPolicyThrottleValue)); } if (mSummaryPref != null && mSummaryPrefEnabled) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mSummaryPref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold), daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } } } private String toReadable (long data) { long KB = 1024; long MB = 1024 * KB; long GB = 1024 * MB; long TB = 1024 * GB; String ret; if (data < KB) { ret = data + " bytes"; } else if (data < MB) { ret = (data / KB) + " KB"; } else if (data < GB) { ret = (data / MB) + " MB"; } else if (data < TB) { ret = (data / GB) + " GB"; } else { ret = (data / TB) + " TB"; } return ret; } }
true
true
private void updateUI() { if (mPolicyThreshold == 0) return; int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold); long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis(); long currentTime = GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis(); int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cycleTime - currentTime); int daysLeft = cal.get(Calendar.DAY_OF_YEAR); if (mCurrentUsagePref != null) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_usage_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold))); } } if (mTimeFramePref != null) { mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext, cycleThroughPercent, daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } if (mThrottleRatePref != null) { mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext, mPolicyThrottleValue)); } if (mSummaryPref != null && mSummaryPrefEnabled) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mSummaryPref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold), daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } } }
private void updateUI() { if (mPolicyThreshold == 0) return; int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold); long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis(); long currentTime = GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis(); int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cycleTime - currentTime); int daysLeft = cal.get(Calendar.DAY_OF_YEAR); //cal.get() returns 365 for less than a day if (daysLeft >= 365) daysLeft = 0; if (mCurrentUsagePref != null) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_usage_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold))); } } if (mTimeFramePref != null) { mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext, cycleThroughPercent, daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } if (mThrottleRatePref != null) { mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext, mPolicyThrottleValue)); } if (mSummaryPref != null && mSummaryPrefEnabled) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mSummaryPref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold), daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } } }
diff --git a/src/com/ModDamage/Routines/Nested/Knockback.java b/src/com/ModDamage/Routines/Nested/Knockback.java index 8c57d3a..6da29cd 100644 --- a/src/com/ModDamage/Routines/Nested/Knockback.java +++ b/src/com/ModDamage/Routines/Nested/Knockback.java @@ -1,101 +1,101 @@ package com.ModDamage.Routines.Nested; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.entity.Entity; import org.bukkit.util.Vector; import com.ModDamage.ModDamage; import com.ModDamage.PluginConfiguration.OutputPreset; import com.ModDamage.Alias.RoutineAliaser; import com.ModDamage.Backend.BailException; import com.ModDamage.EventInfo.DataProvider; import com.ModDamage.EventInfo.EventData; import com.ModDamage.EventInfo.EventInfo; import com.ModDamage.EventInfo.IDataProvider; import com.ModDamage.EventInfo.SimpleEventInfo; import com.ModDamage.Routines.Routines; //FIXME Do I work? public class Knockback extends NestedRoutine { protected final IDataProvider<Entity> entityDP; protected final IDataProvider<Entity> entityOtherDP; protected final Routines routines; protected Knockback(String configString, IDataProvider<Entity> entityDP, IDataProvider<Entity> entityOtherDP, Routines routines) { super(configString); this.entityDP = entityDP; this.entityOtherDP = entityOtherDP; this.routines = routines; } static final EventInfo myInfo = new SimpleEventInfo( Integer.class, "x", "horiz", "-default", Integer.class, "y", "vertical"); @Override public void run(EventData data) throws BailException { Entity firstEntity = entityDP.get(data); Entity secondEntity = entityOtherDP.get(data); if(secondEntity == null) return; Vector vector = firstEntity.getLocation().toVector().subtract(secondEntity.getLocation().toVector()); EventData myData = myInfo.makeChainedData(data, 0, 0); routines.run(myData); int xRef = myData.get(Integer.class, myData.start + 0); int yRef = myData.get(Integer.class, myData.start + 1); double hLength = Math.sqrt(Math.pow(vector.getX(), 2) + Math.pow(vector.getZ(), 2)); double horizValue = ((float)xRef) / 10.0; double verticalValue = ((float)yRef) / 10.0; firstEntity.setVelocity(firstEntity.getVelocity().add( new Vector(vector.getX() / hLength * horizValue, verticalValue, vector.getZ() / hLength * horizValue))); } public static void register() { NestedRoutine.registerRoutine(Pattern.compile("(\\w+)effect\\.knockback(?:\\.from\\.(\\w+))?", Pattern.CASE_INSENSITIVE), new RoutineBuilder()); } protected static class RoutineBuilder extends NestedRoutine.RoutineBuilder { @Override public Knockback getNew(Matcher matcher, Object nestedContent, EventInfo info) { IDataProvider<Entity> entityDP = DataProvider.parse(info, Entity.class, matcher.group(1)); if (entityDP == null) return null; boolean explicitFrom = matcher.group(2) != null; String otherName; if (explicitFrom) otherName = matcher.group(2).toLowerCase(); else otherName = "-" + matcher.group(1).toLowerCase() + "-other"; - IDataProvider<Entity> entityOtherDP = DataProvider.parse(info, Entity.class, otherName); + IDataProvider<Entity> entityOtherDP = info.get(Entity.class, otherName, false); if (entityOtherDP == null) { if (!explicitFrom) ModDamage.addToLogRecord(OutputPreset.FAILURE, "The entity '"+entityDP+"' doesn't have a natural opposite, so you need to specify one using '"+matcher.group()+".from.{entity}'"); return null; } Routines routines = RoutineAliaser.parseRoutines(nestedContent, info.chain(myInfo)); if (routines == null) return null; ModDamage.addToLogRecord(OutputPreset.INFO, "KnockBack: " + entityDP + " from " + entityOtherDP); return new Knockback(matcher.group(), entityDP, entityOtherDP, routines); } } }
true
true
public Knockback getNew(Matcher matcher, Object nestedContent, EventInfo info) { IDataProvider<Entity> entityDP = DataProvider.parse(info, Entity.class, matcher.group(1)); if (entityDP == null) return null; boolean explicitFrom = matcher.group(2) != null; String otherName; if (explicitFrom) otherName = matcher.group(2).toLowerCase(); else otherName = "-" + matcher.group(1).toLowerCase() + "-other"; IDataProvider<Entity> entityOtherDP = DataProvider.parse(info, Entity.class, otherName); if (entityOtherDP == null) { if (!explicitFrom) ModDamage.addToLogRecord(OutputPreset.FAILURE, "The entity '"+entityDP+"' doesn't have a natural opposite, so you need to specify one using '"+matcher.group()+".from.{entity}'"); return null; } Routines routines = RoutineAliaser.parseRoutines(nestedContent, info.chain(myInfo)); if (routines == null) return null; ModDamage.addToLogRecord(OutputPreset.INFO, "KnockBack: " + entityDP + " from " + entityOtherDP); return new Knockback(matcher.group(), entityDP, entityOtherDP, routines); }
public Knockback getNew(Matcher matcher, Object nestedContent, EventInfo info) { IDataProvider<Entity> entityDP = DataProvider.parse(info, Entity.class, matcher.group(1)); if (entityDP == null) return null; boolean explicitFrom = matcher.group(2) != null; String otherName; if (explicitFrom) otherName = matcher.group(2).toLowerCase(); else otherName = "-" + matcher.group(1).toLowerCase() + "-other"; IDataProvider<Entity> entityOtherDP = info.get(Entity.class, otherName, false); if (entityOtherDP == null) { if (!explicitFrom) ModDamage.addToLogRecord(OutputPreset.FAILURE, "The entity '"+entityDP+"' doesn't have a natural opposite, so you need to specify one using '"+matcher.group()+".from.{entity}'"); return null; } Routines routines = RoutineAliaser.parseRoutines(nestedContent, info.chain(myInfo)); if (routines == null) return null; ModDamage.addToLogRecord(OutputPreset.INFO, "KnockBack: " + entityDP + " from " + entityOtherDP); return new Knockback(matcher.group(), entityDP, entityOtherDP, routines); }
diff --git a/ajde/testsrc/org/aspectj/ajde/StructureModelTest.java b/ajde/testsrc/org/aspectj/ajde/StructureModelTest.java index 625990e3a..fedc151be 100644 --- a/ajde/testsrc/org/aspectj/ajde/StructureModelTest.java +++ b/ajde/testsrc/org/aspectj/ajde/StructureModelTest.java @@ -1,176 +1,177 @@ /* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * AMC 21.01.2003 fixed for new source location in eclipse.org * ******************************************************************/ package org.aspectj.ajde; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import junit.framework.TestSuite; import org.aspectj.asm.*; /** * @author Mik Kersten */ public class StructureModelTest extends AjdeTestCase { private final String CONFIG_FILE_PATH = "../examples/figures-coverage/all.lst"; public StructureModelTest(String name) { super(name); } public static void main(String[] args) { junit.swingui.TestRunner.run(StructureModelTest.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(StructureModelTest.class); return result; } // XXX this should work // public void testFieldInitializerCorrespondence() throws IOException { // File testFile = createFile("testdata/examples/figures-coverage/figures/Figure.java"); // StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( // testFile.getCanonicalPath(), 28); // assertTrue("find result", node != null) ; // ProgramElementNode pNode = (ProgramElementNode)node; // ProgramElementNode foundNode = null; // final List list = pNode.getRelations(); // //System.err.println(">>>> " + pNode + ", " + list); // assertNotNull("pNode.getRelations()", list); // for (Iterator it = list.iterator(); it.hasNext(); ) { // RelationNode relation = (RelationNode)it.next(); // // if (relation.getRelation().equals(AdviceAssociation.FIELD_ACCESS_RELATION)) { // for (Iterator it2 = relation.getChildren().iterator(); it2.hasNext(); ) { // LinkNode linkNode = (LinkNode)it2.next(); // if (linkNode.getProgramElementNode().getName().equals("this.currVal = 0")) { // foundNode = linkNode.getProgramElementNode(); // } // } // } // } // // assertTrue("find associated node", foundNode != null) ; // // File pointFile = createFile("testdata/examples/figures-coverage/figures/primitives/planar/Point.java"); // StructureNode fieldNode = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( // pointFile.getCanonicalPath(), 12); // assertTrue("find result", fieldNode != null); // // assertTrue("matches", foundNode.getParent() == fieldNode.getParent()); // } public void testRootForSourceFile() throws IOException { File testFile = createFile("figures-coverage/figures/Figure.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findRootNodeForSourceFile( testFile.getCanonicalPath()); assertTrue("find result", node != null) ; ProgramElementNode pNode = (ProgramElementNode)node; String child = ((StructureNode)pNode.getChildren().get(0)).getName(); assertTrue("expected Figure got child " + child, child.equals("Figure")); } public void testPointcutName() throws IOException { File testFile = createFile("figures-coverage/figures/Main.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findRootNodeForSourceFile( testFile.getCanonicalPath()); assertTrue("find result", node != null) ; ProgramElementNode pNode = (ProgramElementNode)((ProgramElementNode)node).getChildren().get(1); ProgramElementNode pointcut = (ProgramElementNode)pNode.getChildren().get(0); assertTrue("kind", pointcut.getProgramElementKind().equals(ProgramElementNode.Kind.POINTCUT)); assertTrue("found node: " + pointcut.getName(), pointcut.getName().equals("testptct")); } public void testFileNodeFind() throws IOException { File testFile = createFile("testdata/examples/figures-coverage/figures/Main.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( testFile.getCanonicalPath(), 1); assertTrue("find result", node != null) ; ProgramElementNode pNode = (ProgramElementNode)node; assertTrue("found node: " + pNode.getName(), pNode.getProgramElementKind().equals(ProgramElementNode.Kind.FILE_JAVA)); } /** * @todo add negative test to make sure things that aren't runnable aren't annotated */ public void testMainClassNodeInfo() throws IOException { - assertTrue("root exists", Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot() != null); - File testFile = createFile("figures-coverage/figures/Main.java"); - StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( - testFile.getAbsolutePath(), 11); + StructureModel model = Ajde.getDefault().getStructureModelManager().getStructureModel(); + assertTrue("model exists", model != null); + assertTrue("root exists", model.getRoot() != null); + File testFile = createFile("figures-coverage/figures/Main.java"); + StructureNode node = model.findNodeForSourceLine(testFile.getCanonicalPath(), 11); assertTrue("find result", node != null); ProgramElementNode pNode = (ProgramElementNode)((ProgramElementNode)node).getParent(); if (null == pNode) { assertTrue("null parent of " + node, false); } assertTrue("found node: " + pNode.getName(), pNode.isRunnable()); } /** * Integrity could be checked somewhere in the API. */ public void testModelIntegrity() { StructureNode modelRoot = Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot(); assertTrue("root exists", modelRoot != null); try { testModelIntegrityHelper(modelRoot); } catch (Exception e) { assertTrue(e.toString(), false); } } private void testModelIntegrityHelper(StructureNode node) throws Exception { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { StructureNode child = (StructureNode)it.next(); if (node == child.getParent()) { testModelIntegrityHelper(child); } else { throw new Exception("parent-child check failed for child: " + child.toString()); } } } public void testNoChildIsNull() { ModelWalker walker = new ModelWalker() { public void preProcess(StructureNode node) { if (node.getChildren() == null) return; for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { if (it.next() == null) throw new NullPointerException("null child on node: " + node.getName()); } } }; Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot().walk(walker); } protected void setUp() throws Exception { super.setUp("examples"); doSynchronousBuild(CONFIG_FILE_PATH); } protected void tearDown() throws Exception { super.tearDown(); } }
true
true
public void testMainClassNodeInfo() throws IOException { assertTrue("root exists", Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot() != null); File testFile = createFile("figures-coverage/figures/Main.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( testFile.getAbsolutePath(), 11); assertTrue("find result", node != null); ProgramElementNode pNode = (ProgramElementNode)((ProgramElementNode)node).getParent(); if (null == pNode) { assertTrue("null parent of " + node, false); } assertTrue("found node: " + pNode.getName(), pNode.isRunnable()); }
public void testMainClassNodeInfo() throws IOException { StructureModel model = Ajde.getDefault().getStructureModelManager().getStructureModel(); assertTrue("model exists", model != null); assertTrue("root exists", model.getRoot() != null); File testFile = createFile("figures-coverage/figures/Main.java"); StructureNode node = model.findNodeForSourceLine(testFile.getCanonicalPath(), 11); assertTrue("find result", node != null); ProgramElementNode pNode = (ProgramElementNode)((ProgramElementNode)node).getParent(); if (null == pNode) { assertTrue("null parent of " + node, false); } assertTrue("found node: " + pNode.getName(), pNode.isRunnable()); }
diff --git a/spring-xd-dirt/src/test/java/org/springframework/xd/dirt/server/AdminMainRedisStoreIntegrationTests.java b/spring-xd-dirt/src/test/java/org/springframework/xd/dirt/server/AdminMainRedisStoreIntegrationTests.java index 3f37396c8..243336028 100644 --- a/spring-xd-dirt/src/test/java/org/springframework/xd/dirt/server/AdminMainRedisStoreIntegrationTests.java +++ b/spring-xd-dirt/src/test/java/org/springframework/xd/dirt/server/AdminMainRedisStoreIntegrationTests.java @@ -1,42 +1,42 @@ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.xd.dirt.server; import org.junit.Rule; import org.junit.Test; import org.springframework.xd.dirt.server.options.AdminOptions; import org.springframework.xd.dirt.stream.StreamServer; import org.springframework.xd.test.redis.RedisAvailableRule; /** * @author Luke Taylor * @author Gary Russell */ public class AdminMainRedisStoreIntegrationTests extends AbstractAdminMainIntegrationTests { @Rule public RedisAvailableRule redisAvailableRule = new RedisAvailableRule(); @Test public void redisStoreWithLocalTransportConfigurationLoadsSuccessfully() throws Exception { - AdminOptions opts = AdminMain.parseOptions(new String[] {"--httpPort", "0", "--transport", "local", "--store", "redis", "--disableJmx", "true"}); + AdminOptions opts = AdminMain.parseOptions(new String[] {"--httpPort", "0", "--transport", "local", "--store", "redis", "--disableJmx", "true", "--analytics", "memory"}); StreamServer s = AdminMain.launchStreamServer(opts); super.shutdown(s); } }
true
true
public void redisStoreWithLocalTransportConfigurationLoadsSuccessfully() throws Exception { AdminOptions opts = AdminMain.parseOptions(new String[] {"--httpPort", "0", "--transport", "local", "--store", "redis", "--disableJmx", "true"}); StreamServer s = AdminMain.launchStreamServer(opts); super.shutdown(s); }
public void redisStoreWithLocalTransportConfigurationLoadsSuccessfully() throws Exception { AdminOptions opts = AdminMain.parseOptions(new String[] {"--httpPort", "0", "--transport", "local", "--store", "redis", "--disableJmx", "true", "--analytics", "memory"}); StreamServer s = AdminMain.launchStreamServer(opts); super.shutdown(s); }
diff --git a/wikapidia-core/src/main/java/org/wikapidia/core/dao/sql/RedirectSqlDao.java b/wikapidia-core/src/main/java/org/wikapidia/core/dao/sql/RedirectSqlDao.java index 9df09d5e..1796f11e 100644 --- a/wikapidia-core/src/main/java/org/wikapidia/core/dao/sql/RedirectSqlDao.java +++ b/wikapidia-core/src/main/java/org/wikapidia/core/dao/sql/RedirectSqlDao.java @@ -1,264 +1,264 @@ package org.wikapidia.core.dao.sql; import com.typesafe.config.Config; import gnu.trove.map.TIntIntMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import org.apache.commons.io.IOUtils; import org.jooq.*; import org.jooq.impl.DSL; import org.wikapidia.conf.Configuration; import org.wikapidia.conf.ConfigurationException; import org.wikapidia.conf.Configurator; import org.wikapidia.core.dao.DaoException; import org.wikapidia.core.dao.DaoFilter; import org.wikapidia.core.dao.RedirectDao; import org.wikapidia.core.dao.SqlDaoIterable; import org.wikapidia.core.jooq.Tables; import org.wikapidia.core.lang.Language; import org.wikapidia.core.model.LocalPage; import org.wikapidia.core.model.Redirect; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; /** */ public class RedirectSqlDao extends AbstractSqlDao implements RedirectDao { public RedirectSqlDao(DataSource dataSource) throws DaoException { super(dataSource); } @Override public void beginLoad() throws DaoException{ Connection conn=null; try { conn = ds.getConnection(); conn.createStatement().execute( IOUtils.toString( RedirectSqlDao.class.getResource("/db/redirect-schema.sql") ) ); } catch (IOException e){ throw new DaoException(e); } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } @Override public void save(Redirect redirect) throws DaoException { save(redirect.getLanguage(), redirect.getSourceId(), redirect.getDestId()); } @Override public void save(Language lang, int src, int dest) throws DaoException { Connection conn = null; try{ conn = ds.getConnection(); DSLContext context = DSL.using(conn,dialect); context.insertInto(Tables.REDIRECT).values( lang.getId(), src, dest ).execute(); } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } @Override public void endLoad() throws DaoException{ Connection conn = null; try { conn = ds.getConnection(); conn.createStatement().execute( IOUtils.toString( LocalPageSqlDao.class.getResource("/db/redirect-indexes.sql") )); if (cache!=null){ cache.updateTableLastModified(Tables.REDIRECT.getName()); } } catch (IOException e) { throw new DaoException(e); } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } /** * Generally this method should not be used. * @param daoFilter a set of filters to limit the search * @return * @throws DaoException */ @Override public Iterable<Redirect> get(DaoFilter daoFilter) throws DaoException { Connection conn = null; try { conn = ds.getConnection(); DSLContext context = DSL.using(conn, dialect); Collection<Condition> conditions = new ArrayList<Condition>(); if (daoFilter.getLangIds() != null) { conditions.add(Tables.REDIRECT.LANG_ID.in(daoFilter.getLangIds())); } else { return null; } Cursor<Record> result = context.select(). - from(Tables.LOCAL_LINK). + from(Tables.REDIRECT). where(conditions). fetchLazy(); return new SqlDaoIterable<Redirect>(result) { @Override public Redirect transform(Record r) { return buildRedirect(r); } }; } catch (SQLException e) { throw new DaoException(e); } finally { quietlyCloseConn(conn); } } @Override public Integer resolveRedirect(Language lang, int id) throws DaoException { Connection conn=null; try{ conn = ds.getConnection(); DSLContext context = DSL.using(conn,dialect); Record record = context.select().from(Tables.REDIRECT) .where(Tables.REDIRECT.SRC_PAGE_ID.equal(id)) .and(Tables.REDIRECT.LANG_ID.equal(lang.getId())) .fetchOne(); if (record == null){ return null; } return record.getValue(Tables.REDIRECT.DEST_PAGE_ID); } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } @Override public boolean isRedirect(Language lang, int id) throws DaoException { Connection conn=null; try{ conn = ds.getConnection(); DSLContext context = DSL.using(conn,dialect); Record record = context.select().from(Tables.REDIRECT) .where(Tables.REDIRECT.SRC_PAGE_ID.equal(id)) .and(Tables.REDIRECT.LANG_ID.equal(lang.getId())) .fetchOne(); return (record != null); } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } @Override public TIntSet getRedirects(LocalPage localPage) throws DaoException { Connection conn=null; try{ conn = ds.getConnection(); DSLContext context = DSL.using(conn, dialect); Result<Record> result = context.select(). from(Tables.REDIRECT). where(Tables.REDIRECT.DEST_PAGE_ID.eq(localPage.getLocalId())). and(Tables.REDIRECT.LANG_ID.eq(localPage.getLanguage().getId())). fetch(); TIntSet ids = new TIntHashSet(); for (Record record : result){ ids.add(record.getValue(Tables.REDIRECT.SRC_PAGE_ID)); } return ids; } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } @Override public TIntIntMap getAllRedirectIdsToDestIds(Language lang) throws DaoException { Connection conn = null; try{ conn = ds.getConnection(); DSLContext context = DSL.using(conn,dialect); Cursor<Record> cursor = context.select(). from(Tables.REDIRECT). where(Tables.REDIRECT.LANG_ID.equal(lang.getId())). fetchLazy(); TIntIntMap ids = new TIntIntHashMap(10, .5f, -1, -1); for (Record record : cursor){ ids.put(record.getValue(Tables.REDIRECT.SRC_PAGE_ID), record.getValue(Tables.REDIRECT.DEST_PAGE_ID)); } return ids; } catch (SQLException e){ throw new DaoException(e); } finally { quietlyCloseConn(conn); } } private Redirect buildRedirect(Record r) { if (r == null){ return null; } return new Redirect( Language.getById(r.getValue(Tables.REDIRECT.LANG_ID)), r.getValue(Tables.REDIRECT.SRC_PAGE_ID), r.getValue(Tables.REDIRECT.DEST_PAGE_ID) ); } public static class Provider extends org.wikapidia.conf.Provider<RedirectSqlDao> { public Provider(Configurator configurator, Configuration config) throws ConfigurationException { super(configurator, config); } @Override public Class getType() { return RedirectDao.class; } @Override public String getPath() { return "dao.redirect"; } @Override public RedirectSqlDao get(String name, Config config) throws ConfigurationException { if (!config.getString("type").equals("sql")){ return null; } try { return new RedirectSqlDao( getConfigurator().get( DataSource.class, config.getString("dataSource")) ); } catch (DaoException e) { throw new ConfigurationException(e); } } } }
true
true
public Iterable<Redirect> get(DaoFilter daoFilter) throws DaoException { Connection conn = null; try { conn = ds.getConnection(); DSLContext context = DSL.using(conn, dialect); Collection<Condition> conditions = new ArrayList<Condition>(); if (daoFilter.getLangIds() != null) { conditions.add(Tables.REDIRECT.LANG_ID.in(daoFilter.getLangIds())); } else { return null; } Cursor<Record> result = context.select(). from(Tables.LOCAL_LINK). where(conditions). fetchLazy(); return new SqlDaoIterable<Redirect>(result) { @Override public Redirect transform(Record r) { return buildRedirect(r); } }; } catch (SQLException e) { throw new DaoException(e); } finally { quietlyCloseConn(conn); } }
public Iterable<Redirect> get(DaoFilter daoFilter) throws DaoException { Connection conn = null; try { conn = ds.getConnection(); DSLContext context = DSL.using(conn, dialect); Collection<Condition> conditions = new ArrayList<Condition>(); if (daoFilter.getLangIds() != null) { conditions.add(Tables.REDIRECT.LANG_ID.in(daoFilter.getLangIds())); } else { return null; } Cursor<Record> result = context.select(). from(Tables.REDIRECT). where(conditions). fetchLazy(); return new SqlDaoIterable<Redirect>(result) { @Override public Redirect transform(Record r) { return buildRedirect(r); } }; } catch (SQLException e) { throw new DaoException(e); } finally { quietlyCloseConn(conn); } }
diff --git a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java index 5b209ce0d..9b85e239f 100644 --- a/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java +++ b/bundles/org.eclipse.equinox.p2.installer/src/org/eclipse/equinox/internal/p2/installer/InstallApplication.java @@ -1,226 +1,226 @@ /******************************************************************************* * Copyright (c) 2007, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.p2.installer; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.*; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.installer.ui.SWTInstallAdvisor; import org.eclipse.equinox.internal.provisional.p2.installer.InstallAdvisor; import org.eclipse.equinox.internal.provisional.p2.installer.InstallDescription; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; /** * This is a simple installer application built using P2. The application must be given * an "install description" as a command line argument or system property * ({@link #SYS_PROP_INSTALL_DESCRIPTION}). The application reads this * install description, and looks for an existing profile in the local install registry that * matches it. If no profile is found, it creates a new profile, and installs the root * IU in the install description into the profile. It may then launch the installed application, * depending on the specification in the install description. If an existing profile is found, * the application instead performs an update on the existing profile with the new root * IU in the install description. Thus, an installed application can be updated by dropping * in a new install description file, and re-running this installer application. */ public class InstallApplication implements IApplication { /** * A property whose value is the URL of an install description. An install description is a file * that contains all the information required to complete the install. */ private static final String SYS_PROP_INSTALL_DESCRIPTION = "org.eclipse.equinox.p2.installDescription"; //$NON-NLS-1$ /** * The install advisor. This field is non null while the install application is running. */ private InstallAdvisor advisor; /** * Throws an exception of severity error with the given error message. */ private static CoreException fail(String message) { return fail(message, null); } /** * Throws an exception of severity error with the given error message. */ private static CoreException fail(String message, Throwable throwable) { return new CoreException(new Status(IStatus.ERROR, InstallerActivator.PI_INSTALLER, message, throwable)); } /** * Loads the install description, filling in any missing data if needed. */ private InstallDescription computeInstallDescription() throws CoreException { InstallDescription description = fetchInstallDescription(SubMonitor.convert(null)); return advisor.prepareInstallDescription(description); } private InstallAdvisor createInstallContext() { //TODO create an appropriate advisor depending on whether headless or GUI install is desired. InstallAdvisor result = new SWTInstallAdvisor(); result.start(); return result; } /** * Fetch and return the install description to be installed. */ private InstallDescription fetchInstallDescription(SubMonitor monitor) throws CoreException { String site = System.getProperty(SYS_PROP_INSTALL_DESCRIPTION); if (site == null) throw fail(Messages.App_NoSite); try { URL siteURL = new URL(site); return InstallDescriptionParser.loadFromProperties(siteURL.openStream(), monitor); } catch (MalformedURLException e) { throw fail(Messages.App_InvalidSite + site, e); } catch (IOException e) { throw fail(Messages.App_InvalidSite + site, e); } } private IStatus getStatus(final Exception failure) { Throwable cause = failure; //unwrap target exception if applicable if (failure instanceof InvocationTargetException) { cause = ((InvocationTargetException) failure).getTargetException(); if (cause == null) cause = failure; } if (cause instanceof CoreException) return ((CoreException) cause).getStatus(); return new Status(IStatus.ERROR, InstallerActivator.PI_INSTALLER, Messages.App_Error, cause); } private void launchProduct(InstallDescription description) throws CoreException { IPath installLocation = description.getInstallLocation(); IPath toRun = installLocation.append(description.getLauncherName()); try { Runtime.getRuntime().exec(toRun.toString(), null, installLocation.toFile()); } catch (IOException e) { throw fail(Messages.App_LaunchFailed + toRun, e); } //wait a few seconds to give the user a chance to read the message try { Thread.sleep(3000); } catch (InterruptedException e) { //ignore } } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) */ public Object start(IApplicationContext appContext) { try { appContext.applicationRunning(); + initializeProxySupport(); advisor = createInstallContext(); //fetch description of what to install InstallDescription description = null; try { description = computeInstallDescription(); startRequiredBundles(description); - initializeProxySupport(); //perform long running install operation InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description); IStatus result = advisor.performInstall(operation); if (!result.isOK()) { LogHelper.log(result); advisor.setResult(result); return IApplication.EXIT_OK; } //just exit after a successful update if (!operation.isFirstInstall()) return IApplication.EXIT_OK; if (canAutoStart(description)) launchProduct(description); else { //notify user that the product was installed //TODO present the user an option to immediately start the product advisor.setResult(result); } } catch (OperationCanceledException e) { advisor.setResult(Status.CANCEL_STATUS); } catch (Exception e) { IStatus error = getStatus(e); advisor.setResult(error); LogHelper.log(error); } return IApplication.EXIT_OK; } finally { advisor.stop(); } } private void initializeProxySupport() { IProxyService proxies = (IProxyService) ServiceHelper.getService(InstallerActivator.getDefault().getContext(), IProxyService.class.getName()); if (proxies == null) return; proxies.setProxiesEnabled(true); proxies.setSystemProxiesEnabled(true); } /** * Returns whether the configuration described by the given install * description can be started automatically. */ private boolean canAutoStart(InstallDescription description) { if (!description.isAutoStart()) return false; //can't start if we don't know launcher name and path if (description.getLauncherName() == null || description.getInstallLocation() == null) return false; return advisor.promptForLaunch(description); } /** * Starts the p2 bundles needed to continue with the install. */ private void startRequiredBundles(InstallDescription description) throws CoreException { IPath installLocation = description.getInstallLocation(); if (installLocation == null) throw fail(Messages.App_NoInstallLocation, null); //set agent location if specified IPath agentLocation = description.getAgentLocation(); if (agentLocation != null) { String agentArea = System.getProperty("eclipse.p2.data.area"); //$NON-NLS-1$ if (agentArea == null || agentArea.length() == 0) System.setProperty("eclipse.p2.data.area", agentLocation.toOSString()); //$NON-NLS-1$ } //start up p2 try { InstallerActivator.getDefault().getBundle("org.eclipse.equinox.p2.exemplarysetup").start(Bundle.START_TRANSIENT); //$NON-NLS-1$ } catch (BundleException e) { throw fail(Messages.App_FailedStart, e); } } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#stop() */ public void stop() { //note this method can be called from another thread InstallAdvisor tempContext = advisor; if (tempContext != null) { tempContext.stop(); advisor = null; } } }
false
true
public Object start(IApplicationContext appContext) { try { appContext.applicationRunning(); advisor = createInstallContext(); //fetch description of what to install InstallDescription description = null; try { description = computeInstallDescription(); startRequiredBundles(description); initializeProxySupport(); //perform long running install operation InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description); IStatus result = advisor.performInstall(operation); if (!result.isOK()) { LogHelper.log(result); advisor.setResult(result); return IApplication.EXIT_OK; } //just exit after a successful update if (!operation.isFirstInstall()) return IApplication.EXIT_OK; if (canAutoStart(description)) launchProduct(description); else { //notify user that the product was installed //TODO present the user an option to immediately start the product advisor.setResult(result); } } catch (OperationCanceledException e) { advisor.setResult(Status.CANCEL_STATUS); } catch (Exception e) { IStatus error = getStatus(e); advisor.setResult(error); LogHelper.log(error); } return IApplication.EXIT_OK; } finally { advisor.stop(); } }
public Object start(IApplicationContext appContext) { try { appContext.applicationRunning(); initializeProxySupport(); advisor = createInstallContext(); //fetch description of what to install InstallDescription description = null; try { description = computeInstallDescription(); startRequiredBundles(description); //perform long running install operation InstallUpdateProductOperation operation = new InstallUpdateProductOperation(InstallerActivator.getDefault().getContext(), description); IStatus result = advisor.performInstall(operation); if (!result.isOK()) { LogHelper.log(result); advisor.setResult(result); return IApplication.EXIT_OK; } //just exit after a successful update if (!operation.isFirstInstall()) return IApplication.EXIT_OK; if (canAutoStart(description)) launchProduct(description); else { //notify user that the product was installed //TODO present the user an option to immediately start the product advisor.setResult(result); } } catch (OperationCanceledException e) { advisor.setResult(Status.CANCEL_STATUS); } catch (Exception e) { IStatus error = getStatus(e); advisor.setResult(error); LogHelper.log(error); } return IApplication.EXIT_OK; } finally { advisor.stop(); } }
diff --git a/src/org/mvnsearch/snippet/plugin/actions/InsertSnippetFragmentAction.java b/src/org/mvnsearch/snippet/plugin/actions/InsertSnippetFragmentAction.java index 74f58f9..eccde0b 100644 --- a/src/org/mvnsearch/snippet/plugin/actions/InsertSnippetFragmentAction.java +++ b/src/org/mvnsearch/snippet/plugin/actions/InsertSnippetFragmentAction.java @@ -1,207 +1,207 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvnsearch.snippet.plugin.actions; import com.intellij.codeInsight.lookup.*; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaDirectoryService; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiPackage; import org.mvnsearch.snippet.impl.mvnsearch.SnippetService; import org.mvnsearch.snippet.plugin.SnippetAppComponent; import java.util.ArrayList; import java.util.List; /** * insert snippet fragment action in editor * * @author [email protected] */ public class InsertSnippetFragmentAction extends EditorAction { /** * construct snippet fragment action */ public InsertSnippetFragmentAction() { super(new InsertSnippetFragmentHanlder()); } /** * insert snippet fragment handler */ public static class InsertSnippetFragmentHanlder extends EditorWriteActionHandler { /** * execute insert logic * * @param editor editor * @param dataContext data context */ public void executeWriteAction(final Editor editor, DataContext dataContext) { // Get position before caret int caretOffset = editor.getCaretModel().getOffset(); int documentOffset = caretOffset - 1; if (documentOffset > 0) { StringBuilder prefixBuilder = new StringBuilder(); CharSequence charSequence = editor.getDocument().getCharsSequence(); for (char c; documentOffset >= 0 && isMnemonicPart(c = charSequence.charAt(documentOffset)); documentOffset--) { prefixBuilder.append(c); } documentOffset = caretOffset; StringBuilder suffixBuilder = new StringBuilder(); for (char c; documentOffset < charSequence.length() && isMnemonicPart(c = charSequence.charAt(documentOffset)); documentOffset++) { suffixBuilder.append(c); } SnippetService snippetService = SnippetAppComponent.getInstance().getSnippetService(); if (snippetService != null) { PsiFile currentPsiFile = (PsiFile) dataContext.getData(DataConstants.PSI_FILE); //delete snippet mnemonic and replaced by fragment content String prefix = prefixBuilder.reverse().toString(); String suffix = suffixBuilder.reverse().toString(); String mnemonic = prefix + suffix; if (StringUtil.isEmpty(suffix)) { editor.getSelectionModel().setSelection(caretOffset - prefix.length(), caretOffset); } else { editor.getSelectionModel().setSelection(caretOffset - prefix.length(), caretOffset + suffix.length()); } boolean result = executeSnippetInsert(editor, currentPsiFile, mnemonic); if (!result) { //snippet not found List<String> variants = snippetService.findMnemonicList(prefix); List<LookupItem<Object>> lookupItems = new ArrayList<LookupItem<Object>>(); for (String variant : variants) { Object obj = LookupValueFactory.createLookupValue(variant, IconLoader.findIcon("/org/mvnsearch/snippet/plugin/icons/logo.png")); lookupItems.add(new LookupItem<Object>(obj, variant)); } LookupItem[] items = new LookupItem[lookupItems.size()]; items = lookupItems.toArray(items); LookupManager lookupManager = LookupManager.getInstance(editor.getProject()); - lookupManager.showLookup(editor, items, new LookupItemPreferencePolicyImpl(editor, currentPsiFile), prefix); + lookupManager.showLookup(editor, items, new LookupItemPreferencePolicyImpl(editor, currentPsiFile)); } } } } } /** * add macro support * * @param psiFile psi file * @param editor editor * @param rawCode rawcode * @return new code */ private static String addMacroSupport(PsiFile psiFile, Editor editor, String rawCode) { String newCode = rawCode; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile != null) { String fileName = virtualFile.getName(); newCode = newCode.replace("${FILE_NAME}", fileName); PsiDirectory psiDirectory = psiFile.getParent(); if (psiDirectory != null) { PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory); if (psiPackage != null && psiPackage.getName() != null) { newCode = newCode.replace("${PACKAGE_NAME}", psiPackage.getName()); } } } return newCode; } /** * validator is part of mnemonic * * @param part part character * @return validator result */ public static boolean isMnemonicPart(char part) { return Character.isJavaIdentifierPart(part) || part == '-'; } /** * execute snippet insert * * @param editor editor * @param psiFile current psi file * @param mnemonic mnemonic * @return success mark */ public static boolean executeSnippetInsert(final Editor editor, PsiFile psiFile, String mnemonic) { SnippetService snippetService = SnippetAppComponent.getInstance().getSnippetService(); String rawCode = snippetService.renderTemplate(mnemonic, null, null, SnippetAppComponent.getInstance().userName); if (StringUtil.isNotEmpty(rawCode)) { //found and replace final String code = addMacroSupport(psiFile, editor, rawCode); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { EditorModificationUtil.deleteBlockSelection(editor); EditorModificationUtil.insertStringAtCaret(editor, code); } }); return true; } return false; } /** * lookup item preference policy */ private static class LookupItemPreferencePolicyImpl implements LookupItemPreferencePolicy { private Editor editor; private PsiFile psiFile; /** * constructure method * * @param editor current editor * @param psiFile psi file */ public LookupItemPreferencePolicyImpl(Editor editor, PsiFile psiFile) { this.editor = editor; this.psiFile = psiFile; } /** * execute snippet insert * * @param lookupElement lookup element * @param lookup lookup object */ public void itemSelected(LookupElement lookupElement, Lookup lookup) { executeSnippetInsert(editor, psiFile, lookupElement.getLookupString()); } /** * item compare * * @param element1 element1 * @param element2 element2 * @return result */ public int compare(LookupElement element1, LookupElement element2) { return element1.getLookupString().compareTo(element2.getLookupString()); } } }
true
true
public void executeWriteAction(final Editor editor, DataContext dataContext) { // Get position before caret int caretOffset = editor.getCaretModel().getOffset(); int documentOffset = caretOffset - 1; if (documentOffset > 0) { StringBuilder prefixBuilder = new StringBuilder(); CharSequence charSequence = editor.getDocument().getCharsSequence(); for (char c; documentOffset >= 0 && isMnemonicPart(c = charSequence.charAt(documentOffset)); documentOffset--) { prefixBuilder.append(c); } documentOffset = caretOffset; StringBuilder suffixBuilder = new StringBuilder(); for (char c; documentOffset < charSequence.length() && isMnemonicPart(c = charSequence.charAt(documentOffset)); documentOffset++) { suffixBuilder.append(c); } SnippetService snippetService = SnippetAppComponent.getInstance().getSnippetService(); if (snippetService != null) { PsiFile currentPsiFile = (PsiFile) dataContext.getData(DataConstants.PSI_FILE); //delete snippet mnemonic and replaced by fragment content String prefix = prefixBuilder.reverse().toString(); String suffix = suffixBuilder.reverse().toString(); String mnemonic = prefix + suffix; if (StringUtil.isEmpty(suffix)) { editor.getSelectionModel().setSelection(caretOffset - prefix.length(), caretOffset); } else { editor.getSelectionModel().setSelection(caretOffset - prefix.length(), caretOffset + suffix.length()); } boolean result = executeSnippetInsert(editor, currentPsiFile, mnemonic); if (!result) { //snippet not found List<String> variants = snippetService.findMnemonicList(prefix); List<LookupItem<Object>> lookupItems = new ArrayList<LookupItem<Object>>(); for (String variant : variants) { Object obj = LookupValueFactory.createLookupValue(variant, IconLoader.findIcon("/org/mvnsearch/snippet/plugin/icons/logo.png")); lookupItems.add(new LookupItem<Object>(obj, variant)); } LookupItem[] items = new LookupItem[lookupItems.size()]; items = lookupItems.toArray(items); LookupManager lookupManager = LookupManager.getInstance(editor.getProject()); lookupManager.showLookup(editor, items, new LookupItemPreferencePolicyImpl(editor, currentPsiFile), prefix); } } } }
public void executeWriteAction(final Editor editor, DataContext dataContext) { // Get position before caret int caretOffset = editor.getCaretModel().getOffset(); int documentOffset = caretOffset - 1; if (documentOffset > 0) { StringBuilder prefixBuilder = new StringBuilder(); CharSequence charSequence = editor.getDocument().getCharsSequence(); for (char c; documentOffset >= 0 && isMnemonicPart(c = charSequence.charAt(documentOffset)); documentOffset--) { prefixBuilder.append(c); } documentOffset = caretOffset; StringBuilder suffixBuilder = new StringBuilder(); for (char c; documentOffset < charSequence.length() && isMnemonicPart(c = charSequence.charAt(documentOffset)); documentOffset++) { suffixBuilder.append(c); } SnippetService snippetService = SnippetAppComponent.getInstance().getSnippetService(); if (snippetService != null) { PsiFile currentPsiFile = (PsiFile) dataContext.getData(DataConstants.PSI_FILE); //delete snippet mnemonic and replaced by fragment content String prefix = prefixBuilder.reverse().toString(); String suffix = suffixBuilder.reverse().toString(); String mnemonic = prefix + suffix; if (StringUtil.isEmpty(suffix)) { editor.getSelectionModel().setSelection(caretOffset - prefix.length(), caretOffset); } else { editor.getSelectionModel().setSelection(caretOffset - prefix.length(), caretOffset + suffix.length()); } boolean result = executeSnippetInsert(editor, currentPsiFile, mnemonic); if (!result) { //snippet not found List<String> variants = snippetService.findMnemonicList(prefix); List<LookupItem<Object>> lookupItems = new ArrayList<LookupItem<Object>>(); for (String variant : variants) { Object obj = LookupValueFactory.createLookupValue(variant, IconLoader.findIcon("/org/mvnsearch/snippet/plugin/icons/logo.png")); lookupItems.add(new LookupItem<Object>(obj, variant)); } LookupItem[] items = new LookupItem[lookupItems.size()]; items = lookupItems.toArray(items); LookupManager lookupManager = LookupManager.getInstance(editor.getProject()); lookupManager.showLookup(editor, items, new LookupItemPreferencePolicyImpl(editor, currentPsiFile)); } } } }
diff --git a/src/info/guardianproject/otr/app/im/service/ChatSessionAdapter.java b/src/info/guardianproject/otr/app/im/service/ChatSessionAdapter.java index 8c2f75a2..4d24c76c 100644 --- a/src/info/guardianproject/otr/app/im/service/ChatSessionAdapter.java +++ b/src/info/guardianproject/otr/app/im/service/ChatSessionAdapter.java @@ -1,830 +1,830 @@ /* * Copyright (C) 2007-2008 Esmertec AG. Copyright (C) 2007-2008 The Android Open * Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package info.guardianproject.otr.app.im.service; import info.guardianproject.otr.IOtrChatSession; import info.guardianproject.otr.OtrChatListener; import info.guardianproject.otr.OtrChatManager; import info.guardianproject.otr.OtrChatSessionAdapter; import info.guardianproject.otr.OtrDataHandler; import info.guardianproject.otr.OtrDataHandler.Transfer; import info.guardianproject.otr.app.im.IChatListener; import info.guardianproject.otr.app.im.IDataListener; import info.guardianproject.otr.app.im.engine.Address; import info.guardianproject.otr.app.im.engine.ChatGroup; import info.guardianproject.otr.app.im.engine.ChatGroupManager; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.Contact; import info.guardianproject.otr.app.im.engine.DataHandler; import info.guardianproject.otr.app.im.engine.GroupListener; import info.guardianproject.otr.app.im.engine.GroupMemberListener; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImEntity; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.MessageListener; import info.guardianproject.otr.app.im.engine.Presence; import info.guardianproject.otr.app.im.provider.Imps; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.jivesoftware.smack.packet.Packet; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.provider.BaseColumns; import com.google.common.collect.Maps; public class ChatSessionAdapter extends info.guardianproject.otr.app.im.IChatSession.Stub { private static final String NON_CHAT_MESSAGE_SELECTION = Imps.Messages.TYPE + "!=" + Imps.MessageType.INCOMING + " AND " + Imps.Messages.TYPE + "!=" + Imps.MessageType.OUTGOING; /** The registered remote listeners. */ final RemoteCallbackList<IChatListener> mRemoteListeners = new RemoteCallbackList<IChatListener>(); ImConnectionAdapter mConnection; ChatSessionManagerAdapter mChatSessionManager; //all the otr bits that work per session OtrChatManager mOtrChatManager; OtrChatSessionAdapter mOtrChatSession; ChatSession mChatSession; ListenerAdapter mListenerAdapter; boolean mIsGroupChat; StatusBarNotifier mStatusBarNotifier; private ContentResolver mContentResolver; /*package*/Uri mChatURI; private Uri mMessageURI; private Uri mOtrMessageURI; private boolean mConvertingToGroupChat; private static final int MAX_HISTORY_COPY_COUNT = 10; private HashMap<String, Integer> mContactStatusMap = new HashMap<String, Integer>(); private boolean mHasUnreadMessages; private RemoteImService service = null; private DataHandler mDataHandler; private IDataListener mDataListener; public ChatSessionAdapter(ChatSession chatSession, ImConnectionAdapter connection) { mChatSession = chatSession; mConnection = connection; service = connection.getContext(); mContentResolver = service.getContentResolver(); mStatusBarNotifier = service.getStatusBarNotifier(); mChatSessionManager = (ChatSessionManagerAdapter) connection.getChatSessionManager(); mListenerAdapter = new ListenerAdapter(); getOtrChatSession();//setup first time ImEntity participant = mChatSession.getParticipant(); if (participant instanceof ChatGroup) { init((ChatGroup) participant); } else { init((Contact) participant); } } public IOtrChatSession getOtrChatSession() { if (mOtrChatManager == null) { mOtrChatManager = service.getOtrChatManager(); if (mOtrChatManager != null) { mDataHandler = new OtrDataHandler(mChatSession); mOtrChatSession = new OtrChatSessionAdapter(mConnection.getLoginUser().getAddress().getAddress(), mChatSession.getParticipant().getAddress().getAddress(), mOtrChatManager); // add OtrChatListener as the intermediary to mListenerAdapter so it can filter OTR msgs mChatSession.addMessageListener(new OtrChatListener(mOtrChatManager, mListenerAdapter)); mChatSession.setOtrChatManager(mOtrChatManager); } } return mOtrChatSession; } private void init(ChatGroup group) { mIsGroupChat = true; long groupId = insertGroupContactInDb(group); group.addMemberListener(mListenerAdapter); mMessageURI = Imps.Messages.getContentUriByThreadId(groupId); mOtrMessageURI = Imps.Messages.getOtrMessagesContentUriByThreadId(groupId); mChatURI = ContentUris.withAppendedId(Imps.Chats.CONTENT_URI, groupId); insertOrUpdateChat(null); for (Contact c : group.getMembers()) { mContactStatusMap.put(c.getName(), c.getPresence().getStatus()); } } private void init(Contact contact) { mIsGroupChat = false; ContactListManagerAdapter listManager = (ContactListManagerAdapter) mConnection .getContactListManager(); long contactId = listManager.queryOrInsertContact(contact); mMessageURI = Imps.Messages.getContentUriByThreadId(contactId); mOtrMessageURI = Imps.Messages.getOtrMessagesContentUriByThreadId(contactId); mChatURI = ContentUris.withAppendedId(Imps.Chats.CONTENT_URI, contactId); insertOrUpdateChat(null); mContactStatusMap.put(contact.getName(), contact.getPresence().getStatus()); } private ChatGroupManager getGroupManager() { return mConnection.getAdaptee().getChatGroupManager(); } public ChatSession getAdaptee() { return mChatSession; } public Uri getChatUri() { return mChatURI; } public String[] getParticipants() { if (mIsGroupChat) { Contact self = mConnection.getLoginUser(); ChatGroup group = (ChatGroup) mChatSession.getParticipant(); List<Contact> members = group.getMembers(); String[] result = new String[members.size() - 1]; int index = 0; for (Contact c : members) { if (!c.equals(self)) { result[index++] = c.getAddress().getAddress(); } } return result; } else { return new String[] { mChatSession.getParticipant().getAddress().getAddress() }; } } /** * Convert this chat session to a group chat. If it's already a group chat, * nothing will happen. The method works in async mode and the registered * listener will be notified when it's converted to group chat successfully. * * Note that the method is not thread-safe since it's always called from the * UI and Android uses single thread mode for UI. */ public void convertToGroupChat() { if (mIsGroupChat || mConvertingToGroupChat) { return; } mConvertingToGroupChat = true; new ChatConvertor().convertToGroupChat(); } public boolean isGroupChatSession() { return mIsGroupChat; } public String getName() { return mChatSession.getParticipant().getAddress().getUser(); } public String getAddress() { return mChatSession.getParticipant().getAddress().getAddress(); } public long getId() { return ContentUris.parseId(mChatURI); } public void inviteContact(String contact) { if (!mIsGroupChat) { return; } ContactListManagerAdapter listManager = (ContactListManagerAdapter) mConnection .getContactListManager(); Contact invitee = listManager.getContactByAddress(contact); if (invitee == null) { ImErrorInfo error = new ImErrorInfo(ImErrorInfo.ILLEGAL_CONTACT_ADDRESS, "Cannot find contact with address: " + contact); mListenerAdapter.onError((ChatGroup) mChatSession.getParticipant(), error); } else { getGroupManager().inviteUserAsync((ChatGroup) mChatSession.getParticipant(), invitee); } } public void leave() { if (mIsGroupChat) { getGroupManager().leaveChatGroupAsync((ChatGroup) mChatSession.getParticipant()); } mContentResolver.delete(mMessageURI, null, null); mContentResolver.delete(mChatURI, null, null); mStatusBarNotifier.dismissChatNotification(mConnection.getProviderId(), getAddress()); mChatSessionManager.closeChatSession(this); } public void leaveIfInactive() { if (mChatSession.getHistoryMessages().isEmpty()) { leave(); } } public void sendMessage(String text) { if (mConnection.getState() == ImConnection.SUSPENDED) { // connection has been suspended, save the message without send it insertMessageInDb(null, text, -1, Imps.MessageType.POSTPONED); return; } Message msg = new Message(text); // TODO OTRCHAT move setFrom() to ChatSession.sendMessageAsync() msg.setFrom(mConnection.getLoginUser().getAddress()); msg.setType(Imps.MessageType.OUTGOING); mChatSession.sendMessageAsync(msg); long now = System.currentTimeMillis(); if (!isGroupChatSession()) insertMessageInDb(null, text, now, msg.getType(), 0, msg.getID()); } public void offerData(String url, String type) { if (mConnection.getState() == ImConnection.SUSPENDED) { // TODO send later return; } HashMap<String, String> headers = null; if (type != null) { headers = Maps.newHashMap(); headers.put("Mime-Type", type); } mDataHandler.offerData(mConnection.getLoginUser().getAddress(), url, headers); } /** * Sends a message to other participant(s) in this session without adding it * to the history. * * @param msg the message to send. */ /* public void sendMessageWithoutHistory(String text) { Message msg = new Message(text); // TODO OTRCHAT use a lower level method mChatSession.sendMessageAsync(msg); }*/ void sendPostponedMessages() { String[] projection = new String[] { BaseColumns._ID, Imps.Messages.BODY, Imps.Messages.PACKET_ID, Imps.Messages.DATE, Imps.Messages.TYPE, }; String selection = Imps.Messages.TYPE + "=?"; Cursor c = mContentResolver.query(mMessageURI, projection, selection, new String[] { Integer.toString(Imps.MessageType.POSTPONED) }, null); if (c == null) { RemoteImService.debug("Query error while querying postponed messages"); return; } while (c.moveToNext()) { String body = c.getString(1); String id = c.getString(2); Message msg = new Message(body); // TODO OTRCHAT move setFrom() to ChatSession.sendMessageAsync() msg.setFrom(mConnection.getLoginUser().getAddress()); msg.setID(id); msg.setType(Imps.MessageType.OUTGOING); mChatSession.sendMessageAsync(msg); updateMessageInDb(id, msg.getType(), System.currentTimeMillis()); } //c.commitUpdates(); c.close(); } public void registerChatListener(IChatListener listener) { if (listener != null) { mRemoteListeners.register(listener); } } public void unregisterChatListener(IChatListener listener) { if (listener != null) { mRemoteListeners.unregister(listener); } } public void markAsRead() { if (mHasUnreadMessages) { ContentValues values = new ContentValues(1); values.put(Imps.Chats.LAST_UNREAD_MESSAGE, (String) null); mConnection.getContext().getContentResolver().update(mChatURI, values, null, null); mStatusBarNotifier.dismissChatNotification(mConnection.getProviderId(), getAddress()); mHasUnreadMessages = false; } } String getNickName(String username) { ImEntity participant = mChatSession.getParticipant(); if (mIsGroupChat) { ChatGroup group = (ChatGroup) participant; List<Contact> members = group.getMembers(); for (Contact c : members) { if (username.equals(c.getAddress().getAddress())) { return c.getName(); } } // not found, impossible return username; } else { return ((Contact) participant).getName(); } } void onConvertToGroupChatSuccess(ChatGroup group) { Contact oldParticipant = (Contact) mChatSession.getParticipant(); String oldAddress = getAddress(); mChatSession.setParticipant(group); mChatSessionManager.updateChatSession(oldAddress, this); Uri oldChatUri = mChatURI; Uri oldMessageUri = mMessageURI; init(group); copyHistoryMessages(oldParticipant); mContentResolver.delete(oldMessageUri, NON_CHAT_MESSAGE_SELECTION, null); mContentResolver.delete(oldChatUri, null, null); mListenerAdapter.notifyChatSessionConverted(); mConvertingToGroupChat = false; } private void copyHistoryMessages(Contact oldParticipant) { List<Message> historyMessages = mChatSession.getHistoryMessages(); int total = historyMessages.size(); int start = total > MAX_HISTORY_COPY_COUNT ? total - MAX_HISTORY_COPY_COUNT : 0; for (int i = start; i < total; i++) { Message msg = historyMessages.get(i); boolean incoming = msg.getFrom().equals(oldParticipant.getAddress()); String contact = incoming ? oldParticipant.getName() : null; long time = msg.getDateTime().getTime(); insertMessageInDb(contact, msg.getBody(), time, incoming ? Imps.MessageType.INCOMING : Imps.MessageType.OUTGOING); } } void insertOrUpdateChat(String message) { ContentValues values = new ContentValues(2); values.put(Imps.Chats.LAST_MESSAGE_DATE, System.currentTimeMillis()); values.put(Imps.Chats.LAST_UNREAD_MESSAGE, message); // ImProvider.insert() will replace the chat if it already exist. mContentResolver.insert(mChatURI, values); } private long insertGroupContactInDb(ChatGroup group) { // Insert a record in contacts table ContentValues values = new ContentValues(4); values.put(Imps.Contacts.USERNAME, group.getAddress().getAddress()); values.put(Imps.Contacts.NICKNAME, group.getName()); values.put(Imps.Contacts.CONTACTLIST, ContactListManagerAdapter.FAKE_TEMPORARY_LIST_ID); values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_GROUP); Uri contactUri = ContentUris.withAppendedId( ContentUris.withAppendedId(Imps.Contacts.CONTENT_URI, mConnection.mProviderId), mConnection.mAccountId); long id = ContentUris.parseId(mContentResolver.insert(contactUri, values)); ArrayList<ContentValues> memberValues = new ArrayList<ContentValues>(); Contact self = mConnection.getLoginUser(); for (Contact member : group.getMembers()) { if (!member.equals(self)) { // avoid to insert the user himself ContentValues memberValue = new ContentValues(2); memberValue.put(Imps.GroupMembers.USERNAME, member.getAddress().getAddress()); memberValue.put(Imps.GroupMembers.NICKNAME, member.getName()); memberValues.add(memberValue); } } if (!memberValues.isEmpty()) { ContentValues[] result = new ContentValues[memberValues.size()]; memberValues.toArray(result); Uri memberUri = ContentUris.withAppendedId(Imps.GroupMembers.CONTENT_URI, id); mContentResolver.bulkInsert(memberUri, result); } return id; } void insertGroupMemberInDb(Contact member) { ContentValues values1 = new ContentValues(2); values1.put(Imps.GroupMembers.USERNAME, member.getAddress().getAddress()); values1.put(Imps.GroupMembers.NICKNAME, member.getName()); ContentValues values = values1; long groupId = ContentUris.parseId(mChatURI); Uri uri = ContentUris.withAppendedId(Imps.GroupMembers.CONTENT_URI, groupId); mContentResolver.insert(uri, values); insertMessageInDb(member.getName(), null, System.currentTimeMillis(), Imps.MessageType.PRESENCE_AVAILABLE); } void deleteGroupMemberInDb(Contact member) { String where = Imps.GroupMembers.USERNAME + "=?"; String[] selectionArgs = { member.getAddress().getAddress() }; long groupId = ContentUris.parseId(mChatURI); Uri uri = ContentUris.withAppendedId(Imps.GroupMembers.CONTENT_URI, groupId); mContentResolver.delete(uri, where, selectionArgs); insertMessageInDb(member.getName(), null, System.currentTimeMillis(), Imps.MessageType.PRESENCE_UNAVAILABLE); } void insertPresenceUpdatesMsg(String contact, Presence presence) { int status = presence.getStatus(); Integer previousStatus = mContactStatusMap.get(contact); if (previousStatus != null && previousStatus == status) { // don't insert the presence message if it's the same status // with the previous presence update notification return; } mContactStatusMap.put(contact, status); int messageType; switch (status) { case Presence.AVAILABLE: messageType = Imps.MessageType.PRESENCE_AVAILABLE; break; case Presence.AWAY: case Presence.IDLE: messageType = Imps.MessageType.PRESENCE_AWAY; break; case Presence.DO_NOT_DISTURB: messageType = Imps.MessageType.PRESENCE_DND; break; default: messageType = Imps.MessageType.PRESENCE_UNAVAILABLE; break; } if (mIsGroupChat) { insertMessageInDb(contact, null, System.currentTimeMillis(), messageType); } else { insertMessageInDb(null, null, System.currentTimeMillis(), messageType); } } void removeMessageInDb(int type) { mContentResolver.delete(mMessageURI, Imps.Messages.TYPE + "=?", new String[] { Integer.toString(type) }); } Uri insertMessageInDb(String contact, String body, long time, int type) { return insertMessageInDb(contact, body, time, type, 0/*No error*/, Packet.nextID()); } Uri insertMessageInDb(String contact, String body, long time, int type, int errCode, String id) { ContentValues values = new ContentValues(mIsGroupChat ? 4 : 3); values.put(Imps.Messages.BODY, body); values.put(Imps.Messages.DATE, time); values.put(Imps.Messages.TYPE, type); values.put(Imps.Messages.ERROR_CODE, errCode); if (mIsGroupChat) { values.put(Imps.Messages.NICKNAME, contact); values.put(Imps.Messages.IS_GROUP_CHAT, 1); } values.put(Imps.Messages.IS_DELIVERED, 0); values.put(Imps.Messages.PACKET_ID, id); boolean isEncrypted = true; try { isEncrypted = mOtrChatSession.isChatEncrypted(); } catch (RemoteException e) { // Leave it as encrypted so it gets stored in memory // TODO(miron) } return mContentResolver.insert(isEncrypted ? mOtrMessageURI : mMessageURI, values); } int updateConfirmInDb(String id, int value) { Uri.Builder builder = Imps.Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon(); builder.appendPath(id); ContentValues values = new ContentValues(1); values.put(Imps.Messages.IS_DELIVERED, value); return mContentResolver.update(builder.build(), values, null, null); } int updateMessageInDb(String id, int type, long time) { Uri.Builder builder = Imps.Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon(); builder.appendPath(id); ContentValues values = new ContentValues(1); values.put(Imps.Messages.TYPE, type); values.put(Imps.Messages.DATE, time); return mContentResolver.update(builder.build(), values, null, null); } class ListenerAdapter implements MessageListener, GroupMemberListener { public boolean onIncomingMessage(ChatSession ses, final Message msg) { String body = msg.getBody(); String username = msg.getFrom().getAddress(); String bareUsername = msg.getFrom().getBareAddress(); String nickname = getNickName(username); long time = msg.getDateTime().getTime(); insertOrUpdateChat(body); insertMessageInDb(username, body, time, msg.getType()); boolean wasMessageSeen = false; int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { boolean wasSeen = listener.onIncomingMessage(ChatSessionAdapter.this, msg); - if (!wasMessageSeen) + if (wasSeen) wasMessageSeen = wasSeen; } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); // Due to the move to fragments, we could have listeners for ChatViews that are not visible on the screen. // This is for fragments adjacent to the current one. Therefore we can't use the existence of listeners // as a filter on notifications. if (!wasMessageSeen) { //reinstated body display here in the notification; perhaps add preferences to turn that off mStatusBarNotifier.notifyChat(mConnection.getProviderId(), mConnection.getAccountId(), getId(), bareUsername, nickname, body, false); } mHasUnreadMessages = true; return true; } public void onSendMessageError(ChatSession ses, final Message msg, final ImErrorInfo error) { insertMessageInDb(null, null, System.currentTimeMillis(), Imps.MessageType.OUTGOING, error.getCode(), null); final int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onSendMessageError(ChatSessionAdapter.this, msg, error); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); } public void onMemberJoined(ChatGroup group, final Contact contact) { insertGroupMemberInDb(contact); final int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onContactJoined(ChatSessionAdapter.this, contact); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); } public void onMemberLeft(ChatGroup group, final Contact contact) { deleteGroupMemberInDb(contact); final int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onContactLeft(ChatSessionAdapter.this, contact); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); } public void onError(ChatGroup group, final ImErrorInfo error) { // TODO: insert an error message? final int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onInviteError(ChatSessionAdapter.this, error); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); } public void notifyChatSessionConverted() { final int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onConvertedToGroupChat(ChatSessionAdapter.this); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); } @Override public void onIncomingReceipt(ChatSession ses, String id) { updateConfirmInDb(id, 1); int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onIncomingReceipt(ChatSessionAdapter.this, id); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); } @Override public void onMessagePostponed(ChatSession ses, String id) { updateMessageInDb(id, Imps.MessageType.POSTPONED, -1); } @Override public void onReceiptsExpected(ChatSession ses) { // TODO } @Override public void onStatusChanged(ChatSession session) { final int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { listener.onStatusChanged(ChatSessionAdapter.this); } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. // TODO Auto-generated method stub } } mRemoteListeners.finishBroadcast(); } @Override public void onIncomingDataRequest(ChatSession session, Message msg, byte[] value) { mDataHandler.onIncomingRequest(msg.getFrom(),msg.getTo(), value); } @Override public void onIncomingDataResponse(ChatSession session, Message msg, byte[] value) { mDataHandler.onIncomingResponse(msg.getFrom(),msg.getTo(), value); } @Override public void onIncomingTransferRequest(final Transfer transfer) { } } class ChatConvertor implements GroupListener, GroupMemberListener { private ChatGroupManager mGroupMgr; private String mGroupName; public ChatConvertor() { mGroupMgr = mConnection.mGroupManager; } public void convertToGroupChat() { mGroupMgr.addGroupListener(this); mGroupName = "G" + System.currentTimeMillis(); try { mGroupMgr.createChatGroupAsync(mGroupName); } catch (Exception e){ e.printStackTrace(); } } public void onGroupCreated(ChatGroup group) { if (mGroupName.equalsIgnoreCase(group.getName())) { mGroupMgr.removeGroupListener(this); group.addMemberListener(this); mGroupMgr.inviteUserAsync(group, (Contact) mChatSession.getParticipant()); } } public void onMemberJoined(ChatGroup group, Contact contact) { if (mChatSession.getParticipant().equals(contact)) { onConvertToGroupChatSuccess(group); } mContactStatusMap.put(contact.getName(), contact.getPresence().getStatus()); } public void onGroupDeleted(ChatGroup group) { } public void onGroupError(int errorType, String groupName, ImErrorInfo error) { } public void onJoinedGroup(ChatGroup group) { } public void onLeftGroup(ChatGroup group) { } public void onError(ChatGroup group, ImErrorInfo error) { } public void onMemberLeft(ChatGroup group, Contact contact) { mContactStatusMap.remove(contact.getName()); } } @Override public void setDataListener(IDataListener dataListener) throws RemoteException { mDataListener = dataListener; mDataHandler.setDataListener(mDataListener); } }
true
true
public boolean onIncomingMessage(ChatSession ses, final Message msg) { String body = msg.getBody(); String username = msg.getFrom().getAddress(); String bareUsername = msg.getFrom().getBareAddress(); String nickname = getNickName(username); long time = msg.getDateTime().getTime(); insertOrUpdateChat(body); insertMessageInDb(username, body, time, msg.getType()); boolean wasMessageSeen = false; int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { boolean wasSeen = listener.onIncomingMessage(ChatSessionAdapter.this, msg); if (!wasMessageSeen) wasMessageSeen = wasSeen; } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); // Due to the move to fragments, we could have listeners for ChatViews that are not visible on the screen. // This is for fragments adjacent to the current one. Therefore we can't use the existence of listeners // as a filter on notifications. if (!wasMessageSeen) { //reinstated body display here in the notification; perhaps add preferences to turn that off mStatusBarNotifier.notifyChat(mConnection.getProviderId(), mConnection.getAccountId(), getId(), bareUsername, nickname, body, false); } mHasUnreadMessages = true; return true; }
public boolean onIncomingMessage(ChatSession ses, final Message msg) { String body = msg.getBody(); String username = msg.getFrom().getAddress(); String bareUsername = msg.getFrom().getBareAddress(); String nickname = getNickName(username); long time = msg.getDateTime().getTime(); insertOrUpdateChat(body); insertMessageInDb(username, body, time, msg.getType()); boolean wasMessageSeen = false; int N = mRemoteListeners.beginBroadcast(); for (int i = 0; i < N; i++) { IChatListener listener = mRemoteListeners.getBroadcastItem(i); try { boolean wasSeen = listener.onIncomingMessage(ChatSessionAdapter.this, msg); if (wasSeen) wasMessageSeen = wasSeen; } catch (RemoteException e) { // The RemoteCallbackList will take care of removing the // dead listeners. } } mRemoteListeners.finishBroadcast(); // Due to the move to fragments, we could have listeners for ChatViews that are not visible on the screen. // This is for fragments adjacent to the current one. Therefore we can't use the existence of listeners // as a filter on notifications. if (!wasMessageSeen) { //reinstated body display here in the notification; perhaps add preferences to turn that off mStatusBarNotifier.notifyChat(mConnection.getProviderId(), mConnection.getAccountId(), getId(), bareUsername, nickname, body, false); } mHasUnreadMessages = true; return true; }
diff --git a/pingpongnet/src/test/java/ping/pong/net/connection/io/WriteByteArrayDataWriterTest.java b/pingpongnet/src/test/java/ping/pong/net/connection/io/WriteByteArrayDataWriterTest.java index 5c3d7f7..dcab355 100644 --- a/pingpongnet/src/test/java/ping/pong/net/connection/io/WriteByteArrayDataWriterTest.java +++ b/pingpongnet/src/test/java/ping/pong/net/connection/io/WriteByteArrayDataWriterTest.java @@ -1,113 +1,113 @@ package ping.pong.net.connection.io; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.*; /** * * @author mfullen */ public class WriteByteArrayDataWriterTest { private static final Logger LOGGER = LoggerFactory.getLogger(WriteByteArrayDataWriterTest.class); public WriteByteArrayDataWriterTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Test public void testWriteByteArrayDataWriter() throws InterruptedException { Runnable serverSocket = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(10122); Socket acceptingSocket = serverSocket.accept(); WriteByteArrayDataWriter writeByteArrayDataWriter = new WriteByteArrayDataWriter(); writeByteArrayDataWriter.init(acceptingSocket); for (int i = 0; i < 10; i++) { String messageString = "Test" + i; writeByteArrayDataWriter.writeData(messageString.getBytes()); } } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread serverThread = new Thread(serverSocket); serverThread.start(); final String[] results = new String[10]; Runnable reader = new Runnable() { boolean running = true; @Override public void run() { try { ReadFullyDataReader readFullyDataReader = new ReadFullyDataReader(); readFullyDataReader.init(SocketFactory.getDefault().createSocket("localhost", 10122)); int i = 0; - while (running) + while (i <= 9) { byte[] readData = readFullyDataReader.readData(); LOGGER.debug("ReadData: " + readData); results[i] = new String(readData); i++; } } catch (UnknownHostException ex) { LOGGER.error("Error", ex); } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread readerThread = new Thread(reader); readerThread.start(); - serverThread.join(100); - readerThread.join(150); + serverThread.join(); + readerThread.join(); int i = 0; for (int j = 0; j < results.length; j++, i++) { String result = results[j]; String expected = "Test" + i; assertEquals(expected, result); } } }
false
true
public void testWriteByteArrayDataWriter() throws InterruptedException { Runnable serverSocket = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(10122); Socket acceptingSocket = serverSocket.accept(); WriteByteArrayDataWriter writeByteArrayDataWriter = new WriteByteArrayDataWriter(); writeByteArrayDataWriter.init(acceptingSocket); for (int i = 0; i < 10; i++) { String messageString = "Test" + i; writeByteArrayDataWriter.writeData(messageString.getBytes()); } } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread serverThread = new Thread(serverSocket); serverThread.start(); final String[] results = new String[10]; Runnable reader = new Runnable() { boolean running = true; @Override public void run() { try { ReadFullyDataReader readFullyDataReader = new ReadFullyDataReader(); readFullyDataReader.init(SocketFactory.getDefault().createSocket("localhost", 10122)); int i = 0; while (running) { byte[] readData = readFullyDataReader.readData(); LOGGER.debug("ReadData: " + readData); results[i] = new String(readData); i++; } } catch (UnknownHostException ex) { LOGGER.error("Error", ex); } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread readerThread = new Thread(reader); readerThread.start(); serverThread.join(100); readerThread.join(150); int i = 0; for (int j = 0; j < results.length; j++, i++) { String result = results[j]; String expected = "Test" + i; assertEquals(expected, result); } }
public void testWriteByteArrayDataWriter() throws InterruptedException { Runnable serverSocket = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(10122); Socket acceptingSocket = serverSocket.accept(); WriteByteArrayDataWriter writeByteArrayDataWriter = new WriteByteArrayDataWriter(); writeByteArrayDataWriter.init(acceptingSocket); for (int i = 0; i < 10; i++) { String messageString = "Test" + i; writeByteArrayDataWriter.writeData(messageString.getBytes()); } } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread serverThread = new Thread(serverSocket); serverThread.start(); final String[] results = new String[10]; Runnable reader = new Runnable() { boolean running = true; @Override public void run() { try { ReadFullyDataReader readFullyDataReader = new ReadFullyDataReader(); readFullyDataReader.init(SocketFactory.getDefault().createSocket("localhost", 10122)); int i = 0; while (i <= 9) { byte[] readData = readFullyDataReader.readData(); LOGGER.debug("ReadData: " + readData); results[i] = new String(readData); i++; } } catch (UnknownHostException ex) { LOGGER.error("Error", ex); } catch (IOException ex) { LOGGER.error("Error", ex); } } }; Thread readerThread = new Thread(reader); readerThread.start(); serverThread.join(); readerThread.join(); int i = 0; for (int j = 0; j < results.length; j++, i++) { String result = results[j]; String expected = "Test" + i; assertEquals(expected, result); } }
diff --git a/api/src/test/java/org/openmrs/module/emr/consult/ConsultServiceTest.java b/api/src/test/java/org/openmrs/module/emr/consult/ConsultServiceTest.java index ef6889e4..187c1f92 100644 --- a/api/src/test/java/org/openmrs/module/emr/consult/ConsultServiceTest.java +++ b/api/src/test/java/org/openmrs/module/emr/consult/ConsultServiceTest.java @@ -1,426 +1,428 @@ /* * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.emr.consult; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.openmrs.Concept; import org.openmrs.ConceptAnswer; import org.openmrs.ConceptMap; import org.openmrs.ConceptMapType; import org.openmrs.ConceptName; import org.openmrs.ConceptReferenceTerm; import org.openmrs.ConceptSource; import org.openmrs.Encounter; import org.openmrs.EncounterRole; import org.openmrs.Location; import org.openmrs.Obs; import org.openmrs.Patient; import org.openmrs.Provider; import org.openmrs.User; import org.openmrs.api.EncounterService; import org.openmrs.api.PatientService; import org.openmrs.api.context.Context; import org.openmrs.module.emrapi.EmrApiConstants; import org.openmrs.module.emrapi.EmrApiProperties; import org.openmrs.module.emrapi.concept.EmrConceptService; import org.openmrs.module.emrapi.diagnosis.CodedOrFreeTextAnswer; import org.openmrs.module.emrapi.diagnosis.Diagnosis; import org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata; import org.openmrs.module.emrapi.disposition.Disposition; import org.openmrs.module.emrapi.disposition.DispositionDescriptor; import org.openmrs.module.emrapi.disposition.actions.DispositionAction; import org.openmrs.module.emrapi.disposition.actions.MarkPatientDeadDispositionAction; import org.openmrs.module.reporting.common.DateUtil; import org.openmrs.util.OpenmrsUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.context.ApplicationContext; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; /** * */ @RunWith(PowerMockRunner.class) @PrepareForTest(Context.class) public class ConsultServiceTest { private ConsultServiceImpl consultService; private EmrApiProperties emrApiProperties; private EncounterService encounterService; private PatientService patientService; private Patient patient; private Concept diabetes; private Concept malaria; private ConceptName malariaSynonym; private Location mirebalaisHospital; private EncounterRole clinician; private Provider drBob; private User currentUser; private Concept diagnosisGroupingConcept; private Concept codedDiagnosis; private Concept nonCodedDiagnosis; private Concept diagnosisOrder; private Concept primary; private Concept secondary; private Concept freeTextComments; private Concept diagnosisCertainty; private Concept confirmed; private Concept presumed; private Concept dispositionGroupingConcept; private Concept disposition; private Concept patientDied; private Disposition death; private EmrConceptService emrConceptService; @Before public void setUp() throws Exception { currentUser = new User(); mockStatic(Context.class); PowerMockito.when(Context.getAuthenticatedUser()).thenReturn(currentUser); patient = new Patient(123); diabetes = buildConcept(1, "Diabetes"); malaria = buildConcept(2, "Malaria"); malariaSynonym = new ConceptName(); malaria.addName(malariaSynonym); mirebalaisHospital = new Location(); clinician = new EncounterRole(); drBob = new Provider(); freeTextComments = buildConcept(3, "Comments"); ConceptSource emrConceptSource = new ConceptSource(); emrConceptSource.setName(EmrApiConstants.EMR_CONCEPT_SOURCE_NAME); ConceptMapType sameAs = new ConceptMapType(); primary = buildConcept(4, "Primary"); primary.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_ORDER_PRIMARY, null), sameAs)); secondary = buildConcept(5, "Secondary"); secondary.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_ORDER_SECONDARY, null), sameAs)); diagnosisOrder = buildConcept(6, "Diagnosis Order"); diagnosisOrder.addAnswer(new ConceptAnswer(primary)); diagnosisOrder.addAnswer(new ConceptAnswer(secondary)); codedDiagnosis = buildConcept(7, "Diagnosis (Coded)"); nonCodedDiagnosis = buildConcept(8, "Diagnosis (Non-Coded)"); confirmed = buildConcept(11, "Confirmed"); confirmed.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_CERTAINTY_CONFIRMED, null), sameAs)); presumed = buildConcept(12, "Presumed"); presumed.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_CERTAINTY_PRESUMED, null), sameAs)); diagnosisCertainty = buildConcept(10, "Diagnosis Certainty"); diagnosisCertainty.addAnswer(new ConceptAnswer(confirmed)); diagnosisCertainty.addAnswer(new ConceptAnswer(presumed)); diagnosisGroupingConcept = buildConcept(9, "Grouping for Diagnosis"); diagnosisGroupingConcept.addSetMember(diagnosisOrder); diagnosisGroupingConcept.addSetMember(codedDiagnosis); diagnosisGroupingConcept.addSetMember(nonCodedDiagnosis); diagnosisGroupingConcept.addSetMember(diagnosisCertainty); DiagnosisMetadata diagnosisMetadata = new DiagnosisMetadata(); diagnosisMetadata.setDiagnosisSetConcept(diagnosisGroupingConcept); diagnosisMetadata.setCodedDiagnosisConcept(codedDiagnosis); diagnosisMetadata.setNonCodedDiagnosisConcept(nonCodedDiagnosis); diagnosisMetadata.setDiagnosisOrderConcept(diagnosisOrder); diagnosisMetadata.setDiagnosisCertaintyConcept(diagnosisCertainty); patientDied = buildConcept(13, "Patient Died"); disposition = buildConcept(14, "Disposition"); disposition.addAnswer(new ConceptAnswer(patientDied)); dispositionGroupingConcept = buildConcept(15, "Grouping for Disposition"); dispositionGroupingConcept.addSetMember(disposition); DispositionDescriptor dispositionDescriptor = new DispositionDescriptor(); dispositionDescriptor.setDispositionSetConcept(dispositionGroupingConcept); dispositionDescriptor.setDispositionConcept(disposition); emrApiProperties = mock(EmrApiProperties.class); when(emrApiProperties.getConsultFreeTextCommentsConcept()).thenReturn(freeTextComments); when(emrApiProperties.getDiagnosisMetadata()).thenReturn(diagnosisMetadata); when(emrApiProperties.getDispositionDescriptor()).thenReturn(dispositionDescriptor); when(emrApiProperties.getClinicianEncounterRole()).thenReturn(clinician); + when(emrApiProperties.getUnknownCauseOfDeathConcept()).thenReturn(new Concept()); encounterService = mock(EncounterService.class); when(encounterService.saveEncounter(any(Encounter.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { return invocationOnMock.getArguments()[0]; } }); patientService = mock(PatientService.class); when(patientService.savePatient(any(Patient.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); String snomedDiedCode = "SNOMED CT:397709008"; emrConceptService = mock(EmrConceptService.class); when(emrConceptService.getConcept(snomedDiedCode)).thenReturn(patientDied); MarkPatientDeadDispositionAction markPatientDeadAction = new MarkPatientDeadDispositionAction(); markPatientDeadAction.setPatientService(patientService); + markPatientDeadAction.setEmrApiProperties(emrApiProperties); ApplicationContext applicationContext = mock(ApplicationContext.class); when(applicationContext.getBean("markPatientDeadAction", DispositionAction.class)).thenReturn(markPatientDeadAction); consultService = new ConsultServiceImpl(); consultService.setEncounterService(encounterService); consultService.setEmrApiProperties(emrApiProperties); consultService.setEmrConceptService(emrConceptService); consultService.setApplicationContext(applicationContext); death = new Disposition("patientDied", "Patient Died", snomedDiedCode, Arrays.asList("markPatientDeadAction"), null); PowerMockito.when(Context.getPatientService()).thenReturn(patientService); } private Concept buildConcept(int conceptId, String name) { Concept concept = new Concept(); concept.setConceptId(conceptId); concept.addName(new ConceptName(name, Locale.ENGLISH)); return concept; } @Test public void saveConsultNote_shouldHandleCodedPrimaryDiagnosis() { ConsultNote consultNote = buildConsultNote(); consultNote.addPrimaryDiagnosis(new Diagnosis(new CodedOrFreeTextAnswer(malaria))); Encounter encounter = consultService.saveConsultNote(consultNote); assertNotNull(encounter); verify(encounterService).saveEncounter(encounter); Set<Obs> obsAtTopLevel = encounter.getObsAtTopLevel(false); assertThat(obsAtTopLevel.size(), is(1)); Obs primaryDiagnosis = obsAtTopLevel.iterator().next(); assertThat(primaryDiagnosis, diagnosisMatcher(primary, presumed, malaria, null)); } @Test public void saveConsultNote_shouldHandleCodedPrimaryDiagnosisWithSpecificName() { ConsultNote consultNote = buildConsultNote(); Diagnosis diag = new Diagnosis(new CodedOrFreeTextAnswer(malariaSynonym)); diag.setCertainty(Diagnosis.Certainty.CONFIRMED); consultNote.addPrimaryDiagnosis(diag); Encounter encounter = consultService.saveConsultNote(consultNote); assertNotNull(encounter); verify(encounterService).saveEncounter(encounter); Set<Obs> obsAtTopLevel = encounter.getObsAtTopLevel(false); assertThat(obsAtTopLevel.size(), is(1)); Obs primaryDiagnosis = obsAtTopLevel.iterator().next(); assertThat(primaryDiagnosis, diagnosisMatcher(primary, confirmed, malaria, malariaSynonym)); } @Test public void saveConsultNote_shouldHandleNonCodedPrimaryDiagnosis() { String nonCodedAnswer = "New disease we've never heard of"; ConsultNote consultNote = buildConsultNote(); consultNote.addPrimaryDiagnosis(new Diagnosis(new CodedOrFreeTextAnswer(nonCodedAnswer))); Encounter encounter = consultService.saveConsultNote(consultNote); assertNotNull(encounter); verify(encounterService).saveEncounter(encounter); Set<Obs> obsAtTopLevel = encounter.getObsAtTopLevel(false); assertThat(obsAtTopLevel.size(), is(1)); Obs primaryDiagnosis = obsAtTopLevel.iterator().next(); assertThat(primaryDiagnosis, diagnosisMatcher(primary, presumed, nonCodedAnswer)); } @Test public void saveConsultNote_shouldHandleDisposition() { Map<String, String[]> requestParameters = new HashMap<String, String[]>(); String deathDate = "2013-04-05"; requestParameters.put("deathDate", new String[]{deathDate}); ConsultNote consultNote = buildConsultNote(); consultNote.addPrimaryDiagnosis(new Diagnosis(new CodedOrFreeTextAnswer("Doesn't matter for this test"))); consultNote.setDisposition(death); consultNote.setDispositionParameters(requestParameters); Encounter encounter = consultService.saveConsultNote(consultNote); assertNotNull(encounter); verify(encounterService).saveEncounter(encounter); Set<Obs> obsAtTopLevel = encounter.getObsAtTopLevel(false); assertThat(obsAtTopLevel, hasItem((Matcher) dispositionMatcher(patientDied))); verify(patientService).savePatient(patient); assertThat(patient.isDead(), is(true)); assertThat(patient.getDeathDate(), is(DateUtil.parseDate(deathDate, "yyyy-MM-dd"))); } @Test public void saveConsultNote_shouldHandleAllFields() { String nonCodedAnswer = "New disease we've never heard of"; final String comments = "This is a very interesting case"; ConsultNote consultNote = buildConsultNote(); consultNote.addPrimaryDiagnosis(new Diagnosis(new CodedOrFreeTextAnswer(malaria))); Diagnosis diag = new Diagnosis(new CodedOrFreeTextAnswer(diabetes)); diag.setCertainty(Diagnosis.Certainty.CONFIRMED); consultNote.addSecondaryDiagnosis(diag); consultNote.addSecondaryDiagnosis(new Diagnosis(new CodedOrFreeTextAnswer(nonCodedAnswer))); consultNote.setComments(comments); Encounter encounter = consultService.saveConsultNote(consultNote); assertNotNull(encounter); verify(encounterService).saveEncounter(encounter); Set<Obs> obsAtTopLevel = encounter.getObsAtTopLevel(false); assertThat(obsAtTopLevel.size(), is(4)); assertThat(obsAtTopLevel, containsInAnyOrder( diagnosisMatcher(primary, presumed, malaria, null), diagnosisMatcher(secondary, confirmed, diabetes, null), diagnosisMatcher(secondary, presumed, nonCodedAnswer), new ArgumentMatcher<Obs>() { @Override public boolean matches(Object o) { Obs obs = (Obs) o; return obs.getConcept().equals(freeTextComments) && obs.getValueText().equals(comments); } })); } private ConsultNote buildConsultNote() { ConsultNote consultNote = new ConsultNote(); consultNote.setPatient(patient); consultNote.setEncounterLocation(mirebalaisHospital); consultNote.setClinician(drBob); return consultNote; } private ArgumentMatcher<Obs> diagnosisMatcher(final Concept order, final Concept certainty, final Concept diagnosis, final ConceptName specificName) { return new ArgumentMatcher<Obs>() { @Override public boolean matches(Object o) { Obs obsGroup = (Obs) o; return obsGroup.getConcept().equals(diagnosisGroupingConcept) && containsInAnyOrder(new CodedObsMatcher(diagnosisOrder, order), new CodedObsMatcher(diagnosisCertainty, certainty), new CodedObsMatcher(codedDiagnosis, diagnosis, specificName)).matches(obsGroup.getGroupMembers()); } @Override public String toString() { return "Diagnosis matcher for " + order + " = (coded) " + diagnosis; } }; } private ArgumentMatcher<Obs> diagnosisMatcher(final Concept order, final Concept certainty, final String nonCodedAnswer) { return new ArgumentMatcher<Obs>() { @Override public boolean matches(Object o) { Obs obsGroup = (Obs) o; return obsGroup.getConcept().equals(diagnosisGroupingConcept) && containsInAnyOrder(new CodedObsMatcher(diagnosisOrder, order), new CodedObsMatcher(diagnosisCertainty, certainty), new TextObsMatcher(nonCodedDiagnosis, nonCodedAnswer)).matches(obsGroup.getGroupMembers()); } }; } private ArgumentMatcher<Obs> dispositionMatcher(Concept dispositionConcept) { return new ArgumentMatcher<Obs>() { @Override public boolean matches(Object o) { Obs obsGroup = (Obs) o; return obsGroup.getConcept().equals(dispositionGroupingConcept) && containsInAnyOrder(new CodedObsMatcher(disposition, patientDied)) .matches(obsGroup.getGroupMembers()); } }; } private class CodedObsMatcher extends ArgumentMatcher<Obs> { private Concept question; private Concept answer; private ConceptName specificAnswer; public CodedObsMatcher(Concept question, Concept answer) { this.question = question; this.answer = answer; } public CodedObsMatcher(Concept question, Concept answer, ConceptName specificAnswer) { this.question = question; this.answer = answer; this.specificAnswer = specificAnswer; } @Override public boolean matches(Object o) { Obs obs = (Obs) o; return obs.getConcept().equals(question) && obs.getValueCoded().equals(answer) && OpenmrsUtil.nullSafeEquals(obs.getValueCodedName(), specificAnswer); } } private class TextObsMatcher extends ArgumentMatcher<Obs> { private Concept question; private String answer; public TextObsMatcher(Concept question, String answer) { this.question = question; this.answer = answer; } @Override public boolean matches(Object o) { Obs obs = (Obs) o; return obs.getConcept().equals(question) && obs.getValueText().equals(answer); } } }
false
true
public void setUp() throws Exception { currentUser = new User(); mockStatic(Context.class); PowerMockito.when(Context.getAuthenticatedUser()).thenReturn(currentUser); patient = new Patient(123); diabetes = buildConcept(1, "Diabetes"); malaria = buildConcept(2, "Malaria"); malariaSynonym = new ConceptName(); malaria.addName(malariaSynonym); mirebalaisHospital = new Location(); clinician = new EncounterRole(); drBob = new Provider(); freeTextComments = buildConcept(3, "Comments"); ConceptSource emrConceptSource = new ConceptSource(); emrConceptSource.setName(EmrApiConstants.EMR_CONCEPT_SOURCE_NAME); ConceptMapType sameAs = new ConceptMapType(); primary = buildConcept(4, "Primary"); primary.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_ORDER_PRIMARY, null), sameAs)); secondary = buildConcept(5, "Secondary"); secondary.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_ORDER_SECONDARY, null), sameAs)); diagnosisOrder = buildConcept(6, "Diagnosis Order"); diagnosisOrder.addAnswer(new ConceptAnswer(primary)); diagnosisOrder.addAnswer(new ConceptAnswer(secondary)); codedDiagnosis = buildConcept(7, "Diagnosis (Coded)"); nonCodedDiagnosis = buildConcept(8, "Diagnosis (Non-Coded)"); confirmed = buildConcept(11, "Confirmed"); confirmed.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_CERTAINTY_CONFIRMED, null), sameAs)); presumed = buildConcept(12, "Presumed"); presumed.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_CERTAINTY_PRESUMED, null), sameAs)); diagnosisCertainty = buildConcept(10, "Diagnosis Certainty"); diagnosisCertainty.addAnswer(new ConceptAnswer(confirmed)); diagnosisCertainty.addAnswer(new ConceptAnswer(presumed)); diagnosisGroupingConcept = buildConcept(9, "Grouping for Diagnosis"); diagnosisGroupingConcept.addSetMember(diagnosisOrder); diagnosisGroupingConcept.addSetMember(codedDiagnosis); diagnosisGroupingConcept.addSetMember(nonCodedDiagnosis); diagnosisGroupingConcept.addSetMember(diagnosisCertainty); DiagnosisMetadata diagnosisMetadata = new DiagnosisMetadata(); diagnosisMetadata.setDiagnosisSetConcept(diagnosisGroupingConcept); diagnosisMetadata.setCodedDiagnosisConcept(codedDiagnosis); diagnosisMetadata.setNonCodedDiagnosisConcept(nonCodedDiagnosis); diagnosisMetadata.setDiagnosisOrderConcept(diagnosisOrder); diagnosisMetadata.setDiagnosisCertaintyConcept(diagnosisCertainty); patientDied = buildConcept(13, "Patient Died"); disposition = buildConcept(14, "Disposition"); disposition.addAnswer(new ConceptAnswer(patientDied)); dispositionGroupingConcept = buildConcept(15, "Grouping for Disposition"); dispositionGroupingConcept.addSetMember(disposition); DispositionDescriptor dispositionDescriptor = new DispositionDescriptor(); dispositionDescriptor.setDispositionSetConcept(dispositionGroupingConcept); dispositionDescriptor.setDispositionConcept(disposition); emrApiProperties = mock(EmrApiProperties.class); when(emrApiProperties.getConsultFreeTextCommentsConcept()).thenReturn(freeTextComments); when(emrApiProperties.getDiagnosisMetadata()).thenReturn(diagnosisMetadata); when(emrApiProperties.getDispositionDescriptor()).thenReturn(dispositionDescriptor); when(emrApiProperties.getClinicianEncounterRole()).thenReturn(clinician); encounterService = mock(EncounterService.class); when(encounterService.saveEncounter(any(Encounter.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { return invocationOnMock.getArguments()[0]; } }); patientService = mock(PatientService.class); when(patientService.savePatient(any(Patient.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); String snomedDiedCode = "SNOMED CT:397709008"; emrConceptService = mock(EmrConceptService.class); when(emrConceptService.getConcept(snomedDiedCode)).thenReturn(patientDied); MarkPatientDeadDispositionAction markPatientDeadAction = new MarkPatientDeadDispositionAction(); markPatientDeadAction.setPatientService(patientService); ApplicationContext applicationContext = mock(ApplicationContext.class); when(applicationContext.getBean("markPatientDeadAction", DispositionAction.class)).thenReturn(markPatientDeadAction); consultService = new ConsultServiceImpl(); consultService.setEncounterService(encounterService); consultService.setEmrApiProperties(emrApiProperties); consultService.setEmrConceptService(emrConceptService); consultService.setApplicationContext(applicationContext); death = new Disposition("patientDied", "Patient Died", snomedDiedCode, Arrays.asList("markPatientDeadAction"), null); PowerMockito.when(Context.getPatientService()).thenReturn(patientService); }
public void setUp() throws Exception { currentUser = new User(); mockStatic(Context.class); PowerMockito.when(Context.getAuthenticatedUser()).thenReturn(currentUser); patient = new Patient(123); diabetes = buildConcept(1, "Diabetes"); malaria = buildConcept(2, "Malaria"); malariaSynonym = new ConceptName(); malaria.addName(malariaSynonym); mirebalaisHospital = new Location(); clinician = new EncounterRole(); drBob = new Provider(); freeTextComments = buildConcept(3, "Comments"); ConceptSource emrConceptSource = new ConceptSource(); emrConceptSource.setName(EmrApiConstants.EMR_CONCEPT_SOURCE_NAME); ConceptMapType sameAs = new ConceptMapType(); primary = buildConcept(4, "Primary"); primary.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_ORDER_PRIMARY, null), sameAs)); secondary = buildConcept(5, "Secondary"); secondary.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_ORDER_SECONDARY, null), sameAs)); diagnosisOrder = buildConcept(6, "Diagnosis Order"); diagnosisOrder.addAnswer(new ConceptAnswer(primary)); diagnosisOrder.addAnswer(new ConceptAnswer(secondary)); codedDiagnosis = buildConcept(7, "Diagnosis (Coded)"); nonCodedDiagnosis = buildConcept(8, "Diagnosis (Non-Coded)"); confirmed = buildConcept(11, "Confirmed"); confirmed.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_CERTAINTY_CONFIRMED, null), sameAs)); presumed = buildConcept(12, "Presumed"); presumed.addConceptMapping(new ConceptMap(new ConceptReferenceTerm(emrConceptSource, EmrApiConstants.CONCEPT_CODE_DIAGNOSIS_CERTAINTY_PRESUMED, null), sameAs)); diagnosisCertainty = buildConcept(10, "Diagnosis Certainty"); diagnosisCertainty.addAnswer(new ConceptAnswer(confirmed)); diagnosisCertainty.addAnswer(new ConceptAnswer(presumed)); diagnosisGroupingConcept = buildConcept(9, "Grouping for Diagnosis"); diagnosisGroupingConcept.addSetMember(diagnosisOrder); diagnosisGroupingConcept.addSetMember(codedDiagnosis); diagnosisGroupingConcept.addSetMember(nonCodedDiagnosis); diagnosisGroupingConcept.addSetMember(diagnosisCertainty); DiagnosisMetadata diagnosisMetadata = new DiagnosisMetadata(); diagnosisMetadata.setDiagnosisSetConcept(diagnosisGroupingConcept); diagnosisMetadata.setCodedDiagnosisConcept(codedDiagnosis); diagnosisMetadata.setNonCodedDiagnosisConcept(nonCodedDiagnosis); diagnosisMetadata.setDiagnosisOrderConcept(diagnosisOrder); diagnosisMetadata.setDiagnosisCertaintyConcept(diagnosisCertainty); patientDied = buildConcept(13, "Patient Died"); disposition = buildConcept(14, "Disposition"); disposition.addAnswer(new ConceptAnswer(patientDied)); dispositionGroupingConcept = buildConcept(15, "Grouping for Disposition"); dispositionGroupingConcept.addSetMember(disposition); DispositionDescriptor dispositionDescriptor = new DispositionDescriptor(); dispositionDescriptor.setDispositionSetConcept(dispositionGroupingConcept); dispositionDescriptor.setDispositionConcept(disposition); emrApiProperties = mock(EmrApiProperties.class); when(emrApiProperties.getConsultFreeTextCommentsConcept()).thenReturn(freeTextComments); when(emrApiProperties.getDiagnosisMetadata()).thenReturn(diagnosisMetadata); when(emrApiProperties.getDispositionDescriptor()).thenReturn(dispositionDescriptor); when(emrApiProperties.getClinicianEncounterRole()).thenReturn(clinician); when(emrApiProperties.getUnknownCauseOfDeathConcept()).thenReturn(new Concept()); encounterService = mock(EncounterService.class); when(encounterService.saveEncounter(any(Encounter.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { return invocationOnMock.getArguments()[0]; } }); patientService = mock(PatientService.class); when(patientService.savePatient(any(Patient.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); String snomedDiedCode = "SNOMED CT:397709008"; emrConceptService = mock(EmrConceptService.class); when(emrConceptService.getConcept(snomedDiedCode)).thenReturn(patientDied); MarkPatientDeadDispositionAction markPatientDeadAction = new MarkPatientDeadDispositionAction(); markPatientDeadAction.setPatientService(patientService); markPatientDeadAction.setEmrApiProperties(emrApiProperties); ApplicationContext applicationContext = mock(ApplicationContext.class); when(applicationContext.getBean("markPatientDeadAction", DispositionAction.class)).thenReturn(markPatientDeadAction); consultService = new ConsultServiceImpl(); consultService.setEncounterService(encounterService); consultService.setEmrApiProperties(emrApiProperties); consultService.setEmrConceptService(emrConceptService); consultService.setApplicationContext(applicationContext); death = new Disposition("patientDied", "Patient Died", snomedDiedCode, Arrays.asList("markPatientDeadAction"), null); PowerMockito.when(Context.getPatientService()).thenReturn(patientService); }
diff --git a/src/ru/phsystems/irisx/web/AudioHandler.java b/src/ru/phsystems/irisx/web/AudioHandler.java index 3ae040d..568a458 100644 --- a/src/ru/phsystems/irisx/web/AudioHandler.java +++ b/src/ru/phsystems/irisx/web/AudioHandler.java @@ -1,74 +1,75 @@ package ru.phsystems.irisx.web; /** * Created with IntelliJ IDEA. * Author: Nikolay A. Viguro * Date: 09.09.12 * Time: 17:45 * License: GPL v3 * * Этот класс является proxy для mjpeg потока с камер * */ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; public class AudioHandler extends HttpServlet { public AudioHandler() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // правильный boundary - самое главное response.setContentType("audio/wav"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Cache-Control", "no-cache"); ////////////////////////////////////// InputStream in = null; OutputStream out = null; try { System.err.println("[audio] Get stream!"); // URL = http://localhost:8080/control/audio?cam=10 URL cam = new URL("http://192.168.10." + request.getParameter("cam") + "/audio.cgi"); URLConnection uc = cam.openConnection(); out = new BufferedOutputStream(response.getOutputStream()); in = uc.getInputStream(); byte[] bytes = new byte[8192]; int bytesRead; while ((bytesRead = in.read(bytes)) != -1) { out.write(bytes, 0, bytesRead); + out.flush(); } } catch (IOException ex) { // Disconnect detected System.err.println("[audio " + request.getParameter("cam") + "] Audio client disconnected"); // Прерываем поток, иначе передача не будет остановена Thread.currentThread().interrupt(); } } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // правильный boundary - самое главное response.setContentType("audio/wav"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Cache-Control", "no-cache"); ////////////////////////////////////// InputStream in = null; OutputStream out = null; try { System.err.println("[audio] Get stream!"); // URL = http://localhost:8080/control/audio?cam=10 URL cam = new URL("http://192.168.10." + request.getParameter("cam") + "/audio.cgi"); URLConnection uc = cam.openConnection(); out = new BufferedOutputStream(response.getOutputStream()); in = uc.getInputStream(); byte[] bytes = new byte[8192]; int bytesRead; while ((bytesRead = in.read(bytes)) != -1) { out.write(bytes, 0, bytesRead); } } catch (IOException ex) { // Disconnect detected System.err.println("[audio " + request.getParameter("cam") + "] Audio client disconnected"); // Прерываем поток, иначе передача не будет остановена Thread.currentThread().interrupt(); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // правильный boundary - самое главное response.setContentType("audio/wav"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Cache-Control", "no-cache"); ////////////////////////////////////// InputStream in = null; OutputStream out = null; try { System.err.println("[audio] Get stream!"); // URL = http://localhost:8080/control/audio?cam=10 URL cam = new URL("http://192.168.10." + request.getParameter("cam") + "/audio.cgi"); URLConnection uc = cam.openConnection(); out = new BufferedOutputStream(response.getOutputStream()); in = uc.getInputStream(); byte[] bytes = new byte[8192]; int bytesRead; while ((bytesRead = in.read(bytes)) != -1) { out.write(bytes, 0, bytesRead); out.flush(); } } catch (IOException ex) { // Disconnect detected System.err.println("[audio " + request.getParameter("cam") + "] Audio client disconnected"); // Прерываем поток, иначе передача не будет остановена Thread.currentThread().interrupt(); } }
diff --git a/org/freedesktop/dbus/test/profile.java b/org/freedesktop/dbus/test/profile.java index cab5417..ef8b031 100644 --- a/org/freedesktop/dbus/test/profile.java +++ b/org/freedesktop/dbus/test/profile.java @@ -1,333 +1,340 @@ /* D-Bus Java Implementation Copyright (c) 2005-2006 Matthew Johnson This program is free software; you can redistribute it and/or modify it under the terms of either the GNU General Public License Version 2 or the Academic Free Licence Version 2.1. Full licence texts are included in the COPYING file with this program. */ package org.freedesktop.dbus.test; import java.util.Random; import java.util.HashMap; import java.util.Vector; import org.freedesktop.DBus.Peer; import org.freedesktop.DBus.Introspectable; import org.freedesktop.dbus.DBusConnection; import org.freedesktop.dbus.DBusInterface; import org.freedesktop.dbus.DBusSigHandler; import org.freedesktop.dbus.UInt32; import org.freedesktop.dbus.exceptions.DBusException; class ProfileHandler implements DBusSigHandler<Profiler.ProfileSignal> { public int c = 0; public void handle(Profiler.ProfileSignal s) { if (0 == (c++%profile.SIGNAL_INNER)) System.out.print("-"); } } /** * Profiling tests. */ public class profile { public static final int SIGNAL_INNER = 100; public static final int SIGNAL_OUTER = 100; public static final int PING_INNER = 100; public static final int PING_OUTER = 100; public static final int BYTES = 2000000; public static final int INTROSPECTION_OUTER = 100; public static final int INTROSPECTION_INNER = 10; public static final int STRUCT_OUTER = 100; public static final int STRUCT_INNER = 10; public static final int LIST_OUTER = 100; public static final int LIST_INNER = 10; public static final int LIST_LENGTH = 100; public static final int MAP_OUTER = 100; public static final int MAP_INNER = 10; public static final int MAP_LENGTH = 100; public static final int ARRAY_OUTER = 100; public static final int ARRAY_INNER = 10; public static final int ARRAY_LENGTH = 1000; public static class Log { private long last; private int[] deltas; private int current = 0; public Log(int size) { deltas = new int[size]; } public void start() { last = System.currentTimeMillis(); } public void stop() { deltas[current] = (int) (System.currentTimeMillis()-last); current++; } public double mean() { if (0 == current) return 0; long sum = 0; for (int i = 0; i < current; i++) sum+=deltas[i]; return sum /= current; } public long min() { int m = Integer.MAX_VALUE; for (int i = 0; i < current; i++) if (deltas[i] < m) m = deltas[i]; return m; } public long max() { int m = 0; for (int i = 0; i < current; i++) if (deltas[i] > m) m = deltas[i]; return m; } public double stddev() { double mean = mean(); double sum = 0; for (int i=0; i < current; i++) sum += (deltas[i]-mean)*(deltas[i]-mean); return Math.sqrt(sum / (current-1)); } } public static void main(String[] args) throws DBusException { if (0==args.length) { System.out.println("You must specify a profile type."); System.out.println("Syntax: profile <pings|arrays|introspect|maps|bytes|lists|structs|signals>"); System.exit(1); } DBusConnection conn = DBusConnection.getConnection(DBusConnection.SESSION); conn.requestBusName("org.freedesktop.DBus.java.profiler"); if ("pings".equals(args[0])) { int count = PING_INNER*PING_OUTER; System.out.print("Sending "+count+" pings..."); Peer p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Peer.class); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < PING_OUTER; i++) { for (int j = 0; j < PING_INNER; j++) { l.start(); p.Ping(); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("arrays".equals(args[0])) { int count = ARRAY_INNER*ARRAY_OUTER; System.out.print("Sending array of "+ARRAY_LENGTH+" ints "+count+" times."); - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); int[] v = new int[ARRAY_LENGTH]; Random r = new Random(); for (int i = 0; i < ARRAY_LENGTH; i++) v[i] = r.nextInt(); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < ARRAY_OUTER; i++) { for (int j = 0; j < ARRAY_INNER; j++) { l.start(); p.array(v); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("maps".equals(args[0])) { int count = MAP_INNER*MAP_OUTER; System.out.print("Sending map of "+MAP_LENGTH+" string=>strings "+count+" times."); - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); HashMap<String,String> m = new HashMap<String,String>(); for (int i = 0; i < MAP_LENGTH; i++) m.put(""+i, "hello"); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < MAP_OUTER; i++) { for (int j=0; j < MAP_INNER; j++) { l.start(); p.map(m); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("lists".equals(args[0])) { int count = LIST_OUTER*LIST_INNER; System.out.print("Sending list of "+LIST_LENGTH+" strings "+count+" times."); - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); Vector<String> v = new Vector<String>(); for (int i = 0; i < LIST_LENGTH; i++) v.add("hello "+i); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < LIST_OUTER; i++) { for (int j=0; j < LIST_INNER; j++) { l.start(); p.list(v); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("structs".equals(args[0])) { int count = STRUCT_OUTER*STRUCT_INNER; System.out.print("Sending a struct "+count+" times."); - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); ProfileStruct ps = new ProfileStruct("hello", new UInt32(18), 500L); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < STRUCT_OUTER; i++) { for (int j=0; j < STRUCT_INNER; j++) { l.start(); p.struct(ps); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("introspect".equals(args[0])) { int count = INTROSPECTION_OUTER*INTROSPECTION_INNER; System.out.print("Recieving introspection data "+count+" times."); - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Introspectable is = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Introspectable.class); Log l = new Log(count); long t = System.currentTimeMillis(); String s = null; for (int i = 0; i < INTROSPECTION_OUTER; i++) { for (int j = 0; j < INTROSPECTION_INNER; j++) { l.start(); s = is.Introspect(); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); System.out.println("Introspect data: "+s); } else if ("bytes".equals(args[0])) { System.out.print("Sending "+BYTES+" bytes"); - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); byte[] bs = new byte[BYTES]; for (int i = 0; i < BYTES; i++) bs[i] = (byte) i; long t = System.currentTimeMillis(); p.bytes(bs); System.out.println(" done in "+(System.currentTimeMillis()-t)+"ms."); } else if ("rate".equals(args[0])) { - conn.exportObject("/Profiler", new ProfilerInstance()); + ProfilerInstance pi = new ProfilerInstance(); + conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); Peer peer = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Peer.class); long start = System.currentTimeMillis(); int count = 0; do { peer.Ping(); count++; } while(count < 10000); long end = System.currentTimeMillis(); System.out.println("No payload: "+((count*1000)/(end-start))+" RT/second"); int len = 256; while (len <= 32768) { byte[] bs = new byte[len]; count = 0; start = System.currentTimeMillis(); do { p.bytes(bs); count++; } while(count < 1000); end = System.currentTimeMillis(); long ms = end-start; double cps = (count*1000)/ms; double rate = (len*cps)/(1024.0*1024.0); System.out.println(len+" byte array) "+(count*len)+" bytes in "+ms+"ms (in "+count+" calls / "+(int)cps+" CPS): "+rate+"MB/s"); len <<= 1; } len = 256; while (len <= 32768) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) sb.append('a'); String s = sb.toString(); end = System.currentTimeMillis()+500; count = 0; do { p.string(s); count++; } while(count < 1000); long ms = end-start; double cps = (count*1000)/ms; double rate = (len*cps)/(1024.0*1024.0); System.out.println(len+" string) "+(count*len)+" bytes in "+ms+"ms (in "+count+" calls / "+(int)cps+" CPS): "+rate+"MB/s"); len <<= 1; } } else if ("signals".equals(args[0])) { int count = SIGNAL_OUTER*SIGNAL_INNER; System.out.print("Sending "+count+" signals"); ProfileHandler ph = new ProfileHandler(); conn.addSigHandler(Profiler.ProfileSignal.class, ph); Log l = new Log(count); Profiler.ProfileSignal ps = new Profiler.ProfileSignal("/"); long t = System.currentTimeMillis(); for (int i = 0; i < SIGNAL_OUTER; i++) { for (int j = 0; j < SIGNAL_INNER; j++) { l.start(); conn.sendSignal(ps); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); while (ph.c < count) try { Thread.sleep(100); } catch (InterruptedException Ie) {}; } else { conn.disconnect(); System.out.println("Invalid profile ``"+args[0]+"''."); System.out.println("Syntax: profile <pings|arrays|introspect|maps|bytes|lists|structs|signals>"); System.exit(1); } conn.disconnect(); } }
false
true
public static void main(String[] args) throws DBusException { if (0==args.length) { System.out.println("You must specify a profile type."); System.out.println("Syntax: profile <pings|arrays|introspect|maps|bytes|lists|structs|signals>"); System.exit(1); } DBusConnection conn = DBusConnection.getConnection(DBusConnection.SESSION); conn.requestBusName("org.freedesktop.DBus.java.profiler"); if ("pings".equals(args[0])) { int count = PING_INNER*PING_OUTER; System.out.print("Sending "+count+" pings..."); Peer p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Peer.class); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < PING_OUTER; i++) { for (int j = 0; j < PING_INNER; j++) { l.start(); p.Ping(); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("arrays".equals(args[0])) { int count = ARRAY_INNER*ARRAY_OUTER; System.out.print("Sending array of "+ARRAY_LENGTH+" ints "+count+" times."); conn.exportObject("/Profiler", new ProfilerInstance()); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); int[] v = new int[ARRAY_LENGTH]; Random r = new Random(); for (int i = 0; i < ARRAY_LENGTH; i++) v[i] = r.nextInt(); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < ARRAY_OUTER; i++) { for (int j = 0; j < ARRAY_INNER; j++) { l.start(); p.array(v); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("maps".equals(args[0])) { int count = MAP_INNER*MAP_OUTER; System.out.print("Sending map of "+MAP_LENGTH+" string=>strings "+count+" times."); conn.exportObject("/Profiler", new ProfilerInstance()); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); HashMap<String,String> m = new HashMap<String,String>(); for (int i = 0; i < MAP_LENGTH; i++) m.put(""+i, "hello"); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < MAP_OUTER; i++) { for (int j=0; j < MAP_INNER; j++) { l.start(); p.map(m); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("lists".equals(args[0])) { int count = LIST_OUTER*LIST_INNER; System.out.print("Sending list of "+LIST_LENGTH+" strings "+count+" times."); conn.exportObject("/Profiler", new ProfilerInstance()); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); Vector<String> v = new Vector<String>(); for (int i = 0; i < LIST_LENGTH; i++) v.add("hello "+i); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < LIST_OUTER; i++) { for (int j=0; j < LIST_INNER; j++) { l.start(); p.list(v); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("structs".equals(args[0])) { int count = STRUCT_OUTER*STRUCT_INNER; System.out.print("Sending a struct "+count+" times."); conn.exportObject("/Profiler", new ProfilerInstance()); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); ProfileStruct ps = new ProfileStruct("hello", new UInt32(18), 500L); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < STRUCT_OUTER; i++) { for (int j=0; j < STRUCT_INNER; j++) { l.start(); p.struct(ps); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("introspect".equals(args[0])) { int count = INTROSPECTION_OUTER*INTROSPECTION_INNER; System.out.print("Recieving introspection data "+count+" times."); conn.exportObject("/Profiler", new ProfilerInstance()); Introspectable is = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Introspectable.class); Log l = new Log(count); long t = System.currentTimeMillis(); String s = null; for (int i = 0; i < INTROSPECTION_OUTER; i++) { for (int j = 0; j < INTROSPECTION_INNER; j++) { l.start(); s = is.Introspect(); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); System.out.println("Introspect data: "+s); } else if ("bytes".equals(args[0])) { System.out.print("Sending "+BYTES+" bytes"); conn.exportObject("/Profiler", new ProfilerInstance()); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); byte[] bs = new byte[BYTES]; for (int i = 0; i < BYTES; i++) bs[i] = (byte) i; long t = System.currentTimeMillis(); p.bytes(bs); System.out.println(" done in "+(System.currentTimeMillis()-t)+"ms."); } else if ("rate".equals(args[0])) { conn.exportObject("/Profiler", new ProfilerInstance()); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); Peer peer = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Peer.class); long start = System.currentTimeMillis(); int count = 0; do { peer.Ping(); count++; } while(count < 10000); long end = System.currentTimeMillis(); System.out.println("No payload: "+((count*1000)/(end-start))+" RT/second"); int len = 256; while (len <= 32768) { byte[] bs = new byte[len]; count = 0; start = System.currentTimeMillis(); do { p.bytes(bs); count++; } while(count < 1000); end = System.currentTimeMillis(); long ms = end-start; double cps = (count*1000)/ms; double rate = (len*cps)/(1024.0*1024.0); System.out.println(len+" byte array) "+(count*len)+" bytes in "+ms+"ms (in "+count+" calls / "+(int)cps+" CPS): "+rate+"MB/s"); len <<= 1; } len = 256; while (len <= 32768) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) sb.append('a'); String s = sb.toString(); end = System.currentTimeMillis()+500; count = 0; do { p.string(s); count++; } while(count < 1000); long ms = end-start; double cps = (count*1000)/ms; double rate = (len*cps)/(1024.0*1024.0); System.out.println(len+" string) "+(count*len)+" bytes in "+ms+"ms (in "+count+" calls / "+(int)cps+" CPS): "+rate+"MB/s"); len <<= 1; } } else if ("signals".equals(args[0])) { int count = SIGNAL_OUTER*SIGNAL_INNER; System.out.print("Sending "+count+" signals"); ProfileHandler ph = new ProfileHandler(); conn.addSigHandler(Profiler.ProfileSignal.class, ph); Log l = new Log(count); Profiler.ProfileSignal ps = new Profiler.ProfileSignal("/"); long t = System.currentTimeMillis(); for (int i = 0; i < SIGNAL_OUTER; i++) { for (int j = 0; j < SIGNAL_INNER; j++) { l.start(); conn.sendSignal(ps); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); while (ph.c < count) try { Thread.sleep(100); } catch (InterruptedException Ie) {}; } else { conn.disconnect(); System.out.println("Invalid profile ``"+args[0]+"''."); System.out.println("Syntax: profile <pings|arrays|introspect|maps|bytes|lists|structs|signals>"); System.exit(1); } conn.disconnect(); }
public static void main(String[] args) throws DBusException { if (0==args.length) { System.out.println("You must specify a profile type."); System.out.println("Syntax: profile <pings|arrays|introspect|maps|bytes|lists|structs|signals>"); System.exit(1); } DBusConnection conn = DBusConnection.getConnection(DBusConnection.SESSION); conn.requestBusName("org.freedesktop.DBus.java.profiler"); if ("pings".equals(args[0])) { int count = PING_INNER*PING_OUTER; System.out.print("Sending "+count+" pings..."); Peer p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Peer.class); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < PING_OUTER; i++) { for (int j = 0; j < PING_INNER; j++) { l.start(); p.Ping(); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("arrays".equals(args[0])) { int count = ARRAY_INNER*ARRAY_OUTER; System.out.print("Sending array of "+ARRAY_LENGTH+" ints "+count+" times."); ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); int[] v = new int[ARRAY_LENGTH]; Random r = new Random(); for (int i = 0; i < ARRAY_LENGTH; i++) v[i] = r.nextInt(); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < ARRAY_OUTER; i++) { for (int j = 0; j < ARRAY_INNER; j++) { l.start(); p.array(v); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("maps".equals(args[0])) { int count = MAP_INNER*MAP_OUTER; System.out.print("Sending map of "+MAP_LENGTH+" string=>strings "+count+" times."); ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); HashMap<String,String> m = new HashMap<String,String>(); for (int i = 0; i < MAP_LENGTH; i++) m.put(""+i, "hello"); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < MAP_OUTER; i++) { for (int j=0; j < MAP_INNER; j++) { l.start(); p.map(m); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("lists".equals(args[0])) { int count = LIST_OUTER*LIST_INNER; System.out.print("Sending list of "+LIST_LENGTH+" strings "+count+" times."); ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); Vector<String> v = new Vector<String>(); for (int i = 0; i < LIST_LENGTH; i++) v.add("hello "+i); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < LIST_OUTER; i++) { for (int j=0; j < LIST_INNER; j++) { l.start(); p.list(v); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("structs".equals(args[0])) { int count = STRUCT_OUTER*STRUCT_INNER; System.out.print("Sending a struct "+count+" times."); ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); ProfileStruct ps = new ProfileStruct("hello", new UInt32(18), 500L); Log l = new Log(count); long t = System.currentTimeMillis(); for (int i = 0; i < STRUCT_OUTER; i++) { for (int j=0; j < STRUCT_INNER; j++) { l.start(); p.struct(ps); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); } else if ("introspect".equals(args[0])) { int count = INTROSPECTION_OUTER*INTROSPECTION_INNER; System.out.print("Recieving introspection data "+count+" times."); ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Introspectable is = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Introspectable.class); Log l = new Log(count); long t = System.currentTimeMillis(); String s = null; for (int i = 0; i < INTROSPECTION_OUTER; i++) { for (int j = 0; j < INTROSPECTION_INNER; j++) { l.start(); s = is.Introspect(); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); System.out.println("Introspect data: "+s); } else if ("bytes".equals(args[0])) { System.out.print("Sending "+BYTES+" bytes"); ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); byte[] bs = new byte[BYTES]; for (int i = 0; i < BYTES; i++) bs[i] = (byte) i; long t = System.currentTimeMillis(); p.bytes(bs); System.out.println(" done in "+(System.currentTimeMillis()-t)+"ms."); } else if ("rate".equals(args[0])) { ProfilerInstance pi = new ProfilerInstance(); conn.exportObject("/Profiler", pi); Profiler p = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Profiler.class); Peer peer = conn.getRemoteObject("org.freedesktop.DBus.java.profiler", "/Profiler", Peer.class); long start = System.currentTimeMillis(); int count = 0; do { peer.Ping(); count++; } while(count < 10000); long end = System.currentTimeMillis(); System.out.println("No payload: "+((count*1000)/(end-start))+" RT/second"); int len = 256; while (len <= 32768) { byte[] bs = new byte[len]; count = 0; start = System.currentTimeMillis(); do { p.bytes(bs); count++; } while(count < 1000); end = System.currentTimeMillis(); long ms = end-start; double cps = (count*1000)/ms; double rate = (len*cps)/(1024.0*1024.0); System.out.println(len+" byte array) "+(count*len)+" bytes in "+ms+"ms (in "+count+" calls / "+(int)cps+" CPS): "+rate+"MB/s"); len <<= 1; } len = 256; while (len <= 32768) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) sb.append('a'); String s = sb.toString(); end = System.currentTimeMillis()+500; count = 0; do { p.string(s); count++; } while(count < 1000); long ms = end-start; double cps = (count*1000)/ms; double rate = (len*cps)/(1024.0*1024.0); System.out.println(len+" string) "+(count*len)+" bytes in "+ms+"ms (in "+count+" calls / "+(int)cps+" CPS): "+rate+"MB/s"); len <<= 1; } } else if ("signals".equals(args[0])) { int count = SIGNAL_OUTER*SIGNAL_INNER; System.out.print("Sending "+count+" signals"); ProfileHandler ph = new ProfileHandler(); conn.addSigHandler(Profiler.ProfileSignal.class, ph); Log l = new Log(count); Profiler.ProfileSignal ps = new Profiler.ProfileSignal("/"); long t = System.currentTimeMillis(); for (int i = 0; i < SIGNAL_OUTER; i++) { for (int j = 0; j < SIGNAL_INNER; j++) { l.start(); conn.sendSignal(ps); l.stop(); } System.out.print("."); } t = System.currentTimeMillis()-t; System.out.println(" done."); System.out.println("min/max/avg (ms): "+l.min()+"/"+l.max()+"/"+l.mean()); System.out.println("deviation: "+l.stddev()); System.out.println("Total time: "+t+"ms"); while (ph.c < count) try { Thread.sleep(100); } catch (InterruptedException Ie) {}; } else { conn.disconnect(); System.out.println("Invalid profile ``"+args[0]+"''."); System.out.println("Syntax: profile <pings|arrays|introspect|maps|bytes|lists|structs|signals>"); System.exit(1); } conn.disconnect(); }
diff --git a/fcrepo-server/src/main/java/org/fcrepo/server/security/ContextAttributeFinderModule.java b/fcrepo-server/src/main/java/org/fcrepo/server/security/ContextAttributeFinderModule.java index c0333bf1..d15e7ab7 100755 --- a/fcrepo-server/src/main/java/org/fcrepo/server/security/ContextAttributeFinderModule.java +++ b/fcrepo-server/src/main/java/org/fcrepo/server/security/ContextAttributeFinderModule.java @@ -1,290 +1,293 @@ /* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.security; import java.net.URI; import java.net.URISyntaxException; import org.fcrepo.common.Constants; import org.fcrepo.server.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.xacml.EvaluationCtx; import com.sun.xacml.attr.AttributeDesignator; import com.sun.xacml.attr.StringAttribute; import com.sun.xacml.cond.EvaluationResult; /** * @author Bill Niebel */ class ContextAttributeFinderModule extends AttributeFinderModule { private static final Logger logger = LoggerFactory.getLogger(ContextAttributeFinderModule.class); @Override protected boolean canHandleAdhoc() { return true; } private final ContextRegistry m_contexts; private ContextAttributeFinderModule(ContextRegistry contexts) { super(); m_contexts = contexts; try { registerSupportedDesignatorType(AttributeDesignator.SUBJECT_TARGET); registerSupportedDesignatorType(AttributeDesignator.ACTION_TARGET); //<<?????? registerSupportedDesignatorType(AttributeDesignator.RESOURCE_TARGET); //<<????? registerSupportedDesignatorType(AttributeDesignator.ENVIRONMENT_TARGET); registerAttribute(Constants.ENVIRONMENT.CURRENT_DATE_TIME.uri, Constants.ENVIRONMENT.CURRENT_DATE_TIME.datatype); registerAttribute(Constants.ENVIRONMENT.CURRENT_DATE.uri, Constants.ENVIRONMENT.CURRENT_DATE.datatype); registerAttribute(Constants.ENVIRONMENT.CURRENT_TIME.uri, Constants.ENVIRONMENT.CURRENT_TIME.datatype); registerAttribute(Constants.HTTP_REQUEST.PROTOCOL.uri, Constants.HTTP_REQUEST.PROTOCOL.datatype); registerAttribute(Constants.HTTP_REQUEST.SCHEME.uri, Constants.HTTP_REQUEST.SCHEME.datatype); registerAttribute(Constants.HTTP_REQUEST.SECURITY.uri, Constants.HTTP_REQUEST.SECURITY.datatype); registerAttribute(Constants.HTTP_REQUEST.AUTHTYPE.uri, Constants.HTTP_REQUEST.AUTHTYPE.datatype); registerAttribute(Constants.HTTP_REQUEST.METHOD.uri, Constants.HTTP_REQUEST.METHOD.datatype); registerAttribute(Constants.HTTP_REQUEST.SESSION_ENCODING.uri, Constants.HTTP_REQUEST.SESSION_ENCODING.datatype); registerAttribute(Constants.HTTP_REQUEST.SESSION_STATUS.uri, Constants.HTTP_REQUEST.SESSION_STATUS.datatype); registerAttribute(Constants.HTTP_REQUEST.CONTENT_LENGTH.uri, Constants.HTTP_REQUEST.CONTENT_LENGTH.datatype); registerAttribute(Constants.HTTP_REQUEST.CONTENT_TYPE.uri, Constants.HTTP_REQUEST.CONTENT_TYPE.datatype); registerAttribute(Constants.HTTP_REQUEST.CLIENT_FQDN.uri, Constants.HTTP_REQUEST.CLIENT_FQDN.datatype); registerAttribute(Constants.HTTP_REQUEST.CLIENT_IP_ADDRESS.uri, Constants.HTTP_REQUEST.CLIENT_IP_ADDRESS.datatype); registerAttribute(Constants.HTTP_REQUEST.SERVER_FQDN.uri, Constants.HTTP_REQUEST.SERVER_FQDN.datatype); registerAttribute(Constants.HTTP_REQUEST.SERVER_IP_ADDRESS.uri, Constants.HTTP_REQUEST.SERVER_IP_ADDRESS.datatype); registerAttribute(Constants.HTTP_REQUEST.SERVER_PORT.uri, Constants.HTTP_REQUEST.SERVER_PORT.datatype); attributesDenied.add(PolicyEnforcementPoint.XACML_SUBJECT_ID); attributesDenied.add(PolicyEnforcementPoint.XACML_ACTION_ID); attributesDenied.add(PolicyEnforcementPoint.XACML_RESOURCE_ID); attributesDenied.add(Constants.ACTION.CONTEXT_ID.uri); attributesDenied.add(Constants.SUBJECT.LOGIN_ID.uri); attributesDenied.add(Constants.ACTION.ID.uri); attributesDenied.add(Constants.ACTION.API.uri); setInstantiatedOk(true); } catch (URISyntaxException e1) { setInstantiatedOk(false); } } private final String getContextId(EvaluationCtx context) { URI contextIdType = null; URI contextIdId = null; try { contextIdType = new URI(StringAttribute.identifier); } catch (URISyntaxException e) { logger.debug("ContextAttributeFinder:getContextId" + " exit on " + "couldn't make URI for contextId type"); } try { contextIdId = new URI(Constants.ACTION.CONTEXT_ID.uri); } catch (URISyntaxException e) { logger.debug("ContextAttributeFinder:getContextId" + " exit on " + "couldn't make URI for contextId itself"); } logger.debug("ContextAttributeFinder:findAttribute" + " about to call getAttributeFromEvaluationCtx"); EvaluationResult attribute = context.getActionAttribute(contextIdType, contextIdId, null); Object element = getAttributeFromEvaluationResult(attribute); if (element == null) { logger.debug("ContextAttributeFinder:getContextId" + " exit on " + "can't get contextId on request callback"); return null; } if (!(element instanceof StringAttribute)) { logger.debug("ContextAttributeFinder:getContextId" + " exit on " + "couldn't get contextId from xacml request " + "non-string returned"); return null; } String contextId = ((StringAttribute) element).getValue(); if (contextId == null) { logger.debug("ContextAttributeFinder:getContextId" + " exit on " + "null contextId"); return null; } if (!validContextId(contextId)) { logger.debug("ContextAttributeFinder:getContextId" + " exit on " + "invalid context-id"); return null; } return contextId; } private final boolean validContextId(String contextId) { if (contextId == null) { return false; } if ("".equals(contextId)) { return false; } if (" ".equals(contextId)) { return false; } return true; } @Override protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx ctx) { logger.debug("getAttributeLocally context"); String contextId = getContextId(ctx); logger.debug("contextId=" + contextId + " attributeId=" + attributeId); + if (contextId == null || contextId.equals("")) { + return null; + } Context context = m_contexts.getContext(contextId); logger.debug("got context"); Object values = null; logger.debug("designatorType" + designatorType); switch (designatorType) { case AttributeDesignator.SUBJECT_TARGET: if (0 > context.nSubjectValues(attributeId)) { values = null; } else { logger.debug("getting n values for " + attributeId + "=" + context.nSubjectValues(attributeId)); switch (context.nSubjectValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getSubjectValue(attributeId); break; default: values = context.getSubjectValues(attributeId); } if (logger.isDebugEnabled()) { if (values == null) { logger.debug("RETURNING NO VALUES FOR " + attributeId); } else { StringBuffer sb = new StringBuffer(); sb.append("RETURNING " + ((String[]) values).length + " VALUES FOR " + attributeId + " =="); for (int i = 0; i < ((String[]) values).length; i++) { sb.append(" " + ((String[]) values)[i]); } logger.debug(sb.toString()); } } } break; case AttributeDesignator.ACTION_TARGET: if (0 > context.nActionValues(attributeId)) { values = null; } else { switch (context.nActionValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getActionValue(attributeId); break; default: values = context.getActionValues(attributeId); } } break; case AttributeDesignator.RESOURCE_TARGET: if (0 > context.nResourceValues(attributeId)) { values = null; } else { switch (context.nResourceValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getResourceValue(attributeId); break; default: values = context.getResourceValues(attributeId); } } break; case AttributeDesignator.ENVIRONMENT_TARGET: if (0 > context.nEnvironmentValues(attributeId)) { values = null; } else { switch (context.nEnvironmentValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getEnvironmentValue(attributeId); break; default: values = context.getEnvironmentValues(attributeId); } } break; default: } if (values instanceof String) { logger.debug("getAttributeLocally string value=" + (String) values); } else if (values instanceof String[]) { - logger.debug("getAttributeLocally string values=" + values); + logger.debug("getAttributeLocally string values={}", values); for (int i = 0; i < ((String[]) values).length; i++) { - logger.debug("another string value=" + ((String[]) values)[i]); + logger.debug("another string value={}", ((String[]) values)[i]); } } else { - logger.debug("getAttributeLocally object value=" + values); + logger.debug("getAttributeLocally object value={}", values); } return values; } }
false
true
protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx ctx) { logger.debug("getAttributeLocally context"); String contextId = getContextId(ctx); logger.debug("contextId=" + contextId + " attributeId=" + attributeId); Context context = m_contexts.getContext(contextId); logger.debug("got context"); Object values = null; logger.debug("designatorType" + designatorType); switch (designatorType) { case AttributeDesignator.SUBJECT_TARGET: if (0 > context.nSubjectValues(attributeId)) { values = null; } else { logger.debug("getting n values for " + attributeId + "=" + context.nSubjectValues(attributeId)); switch (context.nSubjectValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getSubjectValue(attributeId); break; default: values = context.getSubjectValues(attributeId); } if (logger.isDebugEnabled()) { if (values == null) { logger.debug("RETURNING NO VALUES FOR " + attributeId); } else { StringBuffer sb = new StringBuffer(); sb.append("RETURNING " + ((String[]) values).length + " VALUES FOR " + attributeId + " =="); for (int i = 0; i < ((String[]) values).length; i++) { sb.append(" " + ((String[]) values)[i]); } logger.debug(sb.toString()); } } } break; case AttributeDesignator.ACTION_TARGET: if (0 > context.nActionValues(attributeId)) { values = null; } else { switch (context.nActionValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getActionValue(attributeId); break; default: values = context.getActionValues(attributeId); } } break; case AttributeDesignator.RESOURCE_TARGET: if (0 > context.nResourceValues(attributeId)) { values = null; } else { switch (context.nResourceValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getResourceValue(attributeId); break; default: values = context.getResourceValues(attributeId); } } break; case AttributeDesignator.ENVIRONMENT_TARGET: if (0 > context.nEnvironmentValues(attributeId)) { values = null; } else { switch (context.nEnvironmentValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getEnvironmentValue(attributeId); break; default: values = context.getEnvironmentValues(attributeId); } } break; default: } if (values instanceof String) { logger.debug("getAttributeLocally string value=" + (String) values); } else if (values instanceof String[]) { logger.debug("getAttributeLocally string values=" + values); for (int i = 0; i < ((String[]) values).length; i++) { logger.debug("another string value=" + ((String[]) values)[i]); } } else { logger.debug("getAttributeLocally object value=" + values); } return values; }
protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx ctx) { logger.debug("getAttributeLocally context"); String contextId = getContextId(ctx); logger.debug("contextId=" + contextId + " attributeId=" + attributeId); if (contextId == null || contextId.equals("")) { return null; } Context context = m_contexts.getContext(contextId); logger.debug("got context"); Object values = null; logger.debug("designatorType" + designatorType); switch (designatorType) { case AttributeDesignator.SUBJECT_TARGET: if (0 > context.nSubjectValues(attributeId)) { values = null; } else { logger.debug("getting n values for " + attributeId + "=" + context.nSubjectValues(attributeId)); switch (context.nSubjectValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getSubjectValue(attributeId); break; default: values = context.getSubjectValues(attributeId); } if (logger.isDebugEnabled()) { if (values == null) { logger.debug("RETURNING NO VALUES FOR " + attributeId); } else { StringBuffer sb = new StringBuffer(); sb.append("RETURNING " + ((String[]) values).length + " VALUES FOR " + attributeId + " =="); for (int i = 0; i < ((String[]) values).length; i++) { sb.append(" " + ((String[]) values)[i]); } logger.debug(sb.toString()); } } } break; case AttributeDesignator.ACTION_TARGET: if (0 > context.nActionValues(attributeId)) { values = null; } else { switch (context.nActionValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getActionValue(attributeId); break; default: values = context.getActionValues(attributeId); } } break; case AttributeDesignator.RESOURCE_TARGET: if (0 > context.nResourceValues(attributeId)) { values = null; } else { switch (context.nResourceValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getResourceValue(attributeId); break; default: values = context.getResourceValues(attributeId); } } break; case AttributeDesignator.ENVIRONMENT_TARGET: if (0 > context.nEnvironmentValues(attributeId)) { values = null; } else { switch (context.nEnvironmentValues(attributeId)) { case 0: values = null; /* * values = new String[1]; ((String[])values)[0] = * Authorization.UNDEFINED; */ break; case 1: values = new String[1]; ((String[]) values)[0] = context.getEnvironmentValue(attributeId); break; default: values = context.getEnvironmentValues(attributeId); } } break; default: } if (values instanceof String) { logger.debug("getAttributeLocally string value=" + (String) values); } else if (values instanceof String[]) { logger.debug("getAttributeLocally string values={}", values); for (int i = 0; i < ((String[]) values).length; i++) { logger.debug("another string value={}", ((String[]) values)[i]); } } else { logger.debug("getAttributeLocally object value={}", values); } return values; }
diff --git a/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/ServerTestsActivator.java b/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/ServerTestsActivator.java index ce1cdb7f..4d73c10f 100644 --- a/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/ServerTestsActivator.java +++ b/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/ServerTestsActivator.java @@ -1,119 +1,119 @@ /******************************************************************************* * Copyright (c) 2010, 2011 IBM Corporation and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.orion.server.tests; import org.eclipse.orion.internal.server.servlets.Activator; import org.eclipse.orion.server.configurator.ConfiguratorActivator; import org.eclipse.orion.server.configurator.WebApplication; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceReference; import org.osgi.service.http.HttpService; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.util.tracker.ServiceTracker; public class ServerTestsActivator implements BundleActivator { private static final String EQUINOX_HTTP_JETTY = "org.eclipse.equinox.http.jetty"; //$NON-NLS-1$ private static final String EQUINOX_HTTP_REGISTRY = "org.eclipse.equinox.http.registry"; //$NON-NLS-1$ public static final String PI_TESTS = "org.eclipse.orion.server.tests"; public static BundleContext bundleContext; private static ServiceTracker<HttpService, HttpService> httpServiceTracker; private static ServiceTracker<PackageAdmin, PackageAdmin> packageAdminTracker; private static boolean initialized = false; private static String serverHost = null; private static int serverPort = 0; private static WebApplication webapp; public static BundleContext getContext() { return bundleContext; } public static String getServerLocation() { if (!initialized) { try { - initialize(); //make sure the http registry is started ensureBundleStarted(EQUINOX_HTTP_JETTY); ensureBundleStarted(EQUINOX_HTTP_REGISTRY); //get the webide bundle started via lazy activation. org.eclipse.orion.server.authentication.Activator.getDefault(); Activator.getDefault(); ConfiguratorActivator.getDefault(); webapp = new WebApplication(); webapp.start(null); + initialize(); } catch (Exception e) { e.printStackTrace(); return null; } } return "http://" + serverHost + ':' + String.valueOf(serverPort); } private static void initialize() throws Exception { ServiceReference<HttpService> reference = httpServiceTracker.getServiceReference(); String port = (String) reference.getProperty("http.port"); //$NON-NLS-1$ serverHost = "localhost"; //$NON-NLS-1$ serverPort = Integer.parseInt(port); initialized = true; } public void start(BundleContext context) throws Exception { bundleContext = context; httpServiceTracker = new ServiceTracker<HttpService, HttpService>(context, HttpService.class, null); httpServiceTracker.open(); packageAdminTracker = new ServiceTracker<PackageAdmin, PackageAdmin>(context, PackageAdmin.class.getName(), null); packageAdminTracker.open(); } public void stop(BundleContext context) throws Exception { if (webapp != null) webapp.stop(); if (httpServiceTracker != null) httpServiceTracker.close(); if (packageAdminTracker != null) packageAdminTracker.close(); httpServiceTracker = null; packageAdminTracker = null; bundleContext = null; } static private Bundle getBundle(String symbolicName) { PackageAdmin packageAdmin = packageAdminTracker.getService(); if (packageAdmin == null) return null; Bundle[] bundles = packageAdmin.getBundles(symbolicName, null); if (bundles == null) return null; // Return the first bundle that is not installed or uninstalled for (int i = 0; i < bundles.length; i++) { if ((bundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) { return bundles[i]; } } return null; } static private void ensureBundleStarted(String name) throws BundleException { Bundle bundle = getBundle(name); if (bundle != null) { if (bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.STARTING) { bundle.start(Bundle.START_TRANSIENT); } } } }
false
true
public static String getServerLocation() { if (!initialized) { try { initialize(); //make sure the http registry is started ensureBundleStarted(EQUINOX_HTTP_JETTY); ensureBundleStarted(EQUINOX_HTTP_REGISTRY); //get the webide bundle started via lazy activation. org.eclipse.orion.server.authentication.Activator.getDefault(); Activator.getDefault(); ConfiguratorActivator.getDefault(); webapp = new WebApplication(); webapp.start(null); } catch (Exception e) { e.printStackTrace(); return null; } } return "http://" + serverHost + ':' + String.valueOf(serverPort); }
public static String getServerLocation() { if (!initialized) { try { //make sure the http registry is started ensureBundleStarted(EQUINOX_HTTP_JETTY); ensureBundleStarted(EQUINOX_HTTP_REGISTRY); //get the webide bundle started via lazy activation. org.eclipse.orion.server.authentication.Activator.getDefault(); Activator.getDefault(); ConfiguratorActivator.getDefault(); webapp = new WebApplication(); webapp.start(null); initialize(); } catch (Exception e) { e.printStackTrace(); return null; } } return "http://" + serverHost + ':' + String.valueOf(serverPort); }
diff --git a/src/org/geworkbench/engine/config/UILauncher.java b/src/org/geworkbench/engine/config/UILauncher.java index 312aefff..ce0cbf81 100755 --- a/src/org/geworkbench/engine/config/UILauncher.java +++ b/src/org/geworkbench/engine/config/UILauncher.java @@ -1,222 +1,223 @@ package org.geworkbench.engine.config; import java.io.IOException; import java.io.InputStream; import javax.swing.JOptionPane; import javax.swing.ToolTipManager; import javax.swing.UIManager; import org.apache.commons.digester.Digester; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geworkbench.engine.ccm.ComponentConfigurationManager; import org.geworkbench.engine.config.rules.GeawConfigObject; import org.geworkbench.engine.config.rules.GeawConfigRule; import org.geworkbench.engine.config.rules.PluginRule; import org.geworkbench.util.SplashBitmap; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.jgoodies.looks.plastic.theme.SkyBlue; /** * <p>Copyright: Copyright (c) 2003</p> * <p>Company: First Genetic Trust, Inc.</p> * * @author First Genetic Trust, Inc. * @version 1.0 */ /** * The starting point for an application. Parses the application configuration * file. */ public class UILauncher { private static Log log = LogFactory.getLog(UILauncher.class); public static String getComponentsDirectory() { return componentsDir; } /** * The name of the string in the <code>application.properties</code> file * that contains the location of the application configuration file. */ private final static String CONFIG_FILE_NAME = "component.configuration.file"; private static SplashBitmap splash = new org.geworkbench.util.SplashBitmap(SplashBitmap.class.getResource("splashscreen.png")); private static final String LOOK_AND_FEEL_FLAG = "-lookandfeel"; private static final String DEFAULT_COMPONENTS_DIR = "components"; private static final String COMPONENTS_DIR_PROPERTY = "components.dir"; private static String componentsDir = null; /** * Configure the rules for translating the application configuration file. */ private static Digester createDigester() { Digester digester = new Digester(new org.apache.xerces.parsers.SAXParser()); digester.setUseContextClassLoader(true); // Opening tag <geaw-config> digester.addRule("geaw-config", new GeawConfigRule("org.geworkbench.engine.config.rules.GeawConfigObject")); // Creates the top-level GUI window digester.addObjectCreate("geaw-config/gui-window", "org.geworkbench.engine.config.rules.GUIWindowObject"); digester.addCallMethod("geaw-config/gui-window", "createGUI", 1); digester.addCallParam("geaw-config/gui-window", 0, "class"); // Instantiates a plugin and adds it in the PluginResgistry digester.addRule("geaw-config/plugin", new PluginRule("org.geworkbench.engine.config.rules.PluginObject")); // Registers a plugin with an extension point digester.addCallMethod("geaw-config/plugin/extension-point", "addExtensionPoint", 1); digester.addCallParam("geaw-config/plugin/extension-point", 0, "name"); // Registers a visual plugin with the top-level application GUI. digester.addCallMethod("geaw-config/plugin/gui-area", "addGUIComponent", 1); digester.addCallParam("geaw-config/plugin/gui-area", 0, "name"); // Associates the plugin's module methods to plugin modules digester.addCallMethod("geaw-config/plugin/use-module", "addModule", 2); digester.addCallParam("geaw-config/plugin/use-module", 0, "name"); digester.addCallParam("geaw-config/plugin/use-module", 1, "id"); // Turn subscription object on and off digester.addCallMethod("geaw-config/plugin/subscription", "handleSubscription", 2); digester.addCallParam("geaw-config/plugin/subscription", 0, "type"); digester.addCallParam("geaw-config/plugin/subscription", 1, "enabled"); // Sets up a coupled listener relationship involving 2 plugins. digester.addCallMethod("geaw-config/plugin/coupled-event", "registerCoupledListener", 2); digester.addCallParam("geaw-config/plugin/coupled-event", 0, "event"); digester.addCallParam("geaw-config/plugin/coupled-event", 1, "source"); return digester; } /** * Reads application properties from a file called * <bold>application.properties</bold> */ private static void initProperties() { InputStream reader = null; try { reader = Class.forName(UILauncher.class.getName()).getResourceAsStream("/application.properties"); System.getProperties().load(reader); if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } reader.close(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } //Set system-wide ToolTip properties ToolTipManager.sharedInstance().setInitialDelay(100); } private static void exitOnErrorMessage(String message) { JOptionPane.showMessageDialog(null, message, "Application Startup Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } /** * The application start point. * * @param args */ public static void main(String[] args) { String configFileArg = null; String lookAndFeelArg = null; for (int i = 0; i < args.length; i++) { if (LOOK_AND_FEEL_FLAG.equals(args[i])) { if (args.length == (i + 1)) { exitOnErrorMessage("No look & feel parameter specified."); } else { i++; lookAndFeelArg = args[i]; } } else { configFileArg = args[i]; } } try { if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1) { // If we're not on windows, then use native look and feel no matter what UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { if (lookAndFeelArg != null) { if ("native".equals(lookAndFeelArg)) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else if ("plastic".equals(lookAndFeelArg)) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else { UIManager.setLookAndFeel(lookAndFeelArg); } } else { // Default to plastic. PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } } } catch (Exception e) { log.error(e,e); } splash.hideOnClick(); splash.addAutoProgressBarIndeterminate(); splash.setProgressBarString("loading..."); splash.showSplash(); // Read the properties file initProperties(); componentsDir = System.getProperty(COMPONENTS_DIR_PROPERTY); if (componentsDir == null) { componentsDir = DEFAULT_COMPONENTS_DIR; } Digester digester = createDigester(); org.geworkbench.util.Debug.debugStatus = false; // debugging toggle // Locate and open the application configuration file. String configFileName = null; if (configFileArg != null) { configFileName = configFileArg; } else { configFileName = System.getProperty(CONFIG_FILE_NAME); if (configFileName == null) exitOnErrorMessage("Invalid or absent configuration file."); } try { InputStream is = Class.forName(UILauncher.class.getName()).getResourceAsStream("/" + configFileName); if (is == null) { exitOnErrorMessage("Invalid or absent configuration file."); } digester.parse(is); is.close(); } catch (Exception e) { log.error(e,e); exitOnErrorMessage("Exception in parsing the configuration file."); } /* Load Components */ ComponentConfigurationManager ccm = ComponentConfigurationManager.getInstance(); ccm.loadAllComponentFolders(); ccm.loadSelectedComponents(); PluginRegistry.debugPrint(); splash.hideSplash(); GUIFramework guiWindow = GeawConfigObject.getGuiWindow(); guiWindow.setVisible(true); + GeawConfigObject.getGuiWindow().setVisualizationType(null); // force the welcome component to show } public static void setProgressBarString(String name) { splash.setProgressBarString(name); } }
true
true
public static void main(String[] args) { String configFileArg = null; String lookAndFeelArg = null; for (int i = 0; i < args.length; i++) { if (LOOK_AND_FEEL_FLAG.equals(args[i])) { if (args.length == (i + 1)) { exitOnErrorMessage("No look & feel parameter specified."); } else { i++; lookAndFeelArg = args[i]; } } else { configFileArg = args[i]; } } try { if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1) { // If we're not on windows, then use native look and feel no matter what UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { if (lookAndFeelArg != null) { if ("native".equals(lookAndFeelArg)) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else if ("plastic".equals(lookAndFeelArg)) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else { UIManager.setLookAndFeel(lookAndFeelArg); } } else { // Default to plastic. PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } } } catch (Exception e) { log.error(e,e); } splash.hideOnClick(); splash.addAutoProgressBarIndeterminate(); splash.setProgressBarString("loading..."); splash.showSplash(); // Read the properties file initProperties(); componentsDir = System.getProperty(COMPONENTS_DIR_PROPERTY); if (componentsDir == null) { componentsDir = DEFAULT_COMPONENTS_DIR; } Digester digester = createDigester(); org.geworkbench.util.Debug.debugStatus = false; // debugging toggle // Locate and open the application configuration file. String configFileName = null; if (configFileArg != null) { configFileName = configFileArg; } else { configFileName = System.getProperty(CONFIG_FILE_NAME); if (configFileName == null) exitOnErrorMessage("Invalid or absent configuration file."); } try { InputStream is = Class.forName(UILauncher.class.getName()).getResourceAsStream("/" + configFileName); if (is == null) { exitOnErrorMessage("Invalid or absent configuration file."); } digester.parse(is); is.close(); } catch (Exception e) { log.error(e,e); exitOnErrorMessage("Exception in parsing the configuration file."); } /* Load Components */ ComponentConfigurationManager ccm = ComponentConfigurationManager.getInstance(); ccm.loadAllComponentFolders(); ccm.loadSelectedComponents(); PluginRegistry.debugPrint(); splash.hideSplash(); GUIFramework guiWindow = GeawConfigObject.getGuiWindow(); guiWindow.setVisible(true); }
public static void main(String[] args) { String configFileArg = null; String lookAndFeelArg = null; for (int i = 0; i < args.length; i++) { if (LOOK_AND_FEEL_FLAG.equals(args[i])) { if (args.length == (i + 1)) { exitOnErrorMessage("No look & feel parameter specified."); } else { i++; lookAndFeelArg = args[i]; } } else { configFileArg = args[i]; } } try { if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1) { // If we're not on windows, then use native look and feel no matter what UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { if (lookAndFeelArg != null) { if ("native".equals(lookAndFeelArg)) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else if ("plastic".equals(lookAndFeelArg)) { PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } else { UIManager.setLookAndFeel(lookAndFeelArg); } } else { // Default to plastic. PlasticLookAndFeel.setMyCurrentTheme(new SkyBlue()); UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } } } catch (Exception e) { log.error(e,e); } splash.hideOnClick(); splash.addAutoProgressBarIndeterminate(); splash.setProgressBarString("loading..."); splash.showSplash(); // Read the properties file initProperties(); componentsDir = System.getProperty(COMPONENTS_DIR_PROPERTY); if (componentsDir == null) { componentsDir = DEFAULT_COMPONENTS_DIR; } Digester digester = createDigester(); org.geworkbench.util.Debug.debugStatus = false; // debugging toggle // Locate and open the application configuration file. String configFileName = null; if (configFileArg != null) { configFileName = configFileArg; } else { configFileName = System.getProperty(CONFIG_FILE_NAME); if (configFileName == null) exitOnErrorMessage("Invalid or absent configuration file."); } try { InputStream is = Class.forName(UILauncher.class.getName()).getResourceAsStream("/" + configFileName); if (is == null) { exitOnErrorMessage("Invalid or absent configuration file."); } digester.parse(is); is.close(); } catch (Exception e) { log.error(e,e); exitOnErrorMessage("Exception in parsing the configuration file."); } /* Load Components */ ComponentConfigurationManager ccm = ComponentConfigurationManager.getInstance(); ccm.loadAllComponentFolders(); ccm.loadSelectedComponents(); PluginRegistry.debugPrint(); splash.hideSplash(); GUIFramework guiWindow = GeawConfigObject.getGuiWindow(); guiWindow.setVisible(true); GeawConfigObject.getGuiWindow().setVisualizationType(null); // force the welcome component to show }
diff --git a/src/org/apache/xpath/functions/Function3Args.java b/src/org/apache/xpath/functions/Function3Args.java index 062412e4..4903f91d 100644 --- a/src/org/apache/xpath/functions/Function3Args.java +++ b/src/org/apache/xpath/functions/Function3Args.java @@ -1,32 +1,32 @@ package org.apache.xpath.functions; import org.apache.xpath.Expression; public class Function3Args extends Function2Args { Expression m_arg2; public Expression getArg2() { return m_arg2; } public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { if(argNum < 2) - super.setArg(arg, 1); + super.setArg(arg, argNum); else if(2 == argNum) m_arg2 = arg; else throw new WrongNumberArgsException("3"); } public void checkNumberArgs(int argNum) throws WrongNumberArgsException { if(argNum != 3) throw new WrongNumberArgsException("3"); } }
true
true
public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { if(argNum < 2) super.setArg(arg, 1); else if(2 == argNum) m_arg2 = arg; else throw new WrongNumberArgsException("3"); }
public void setArg(Expression arg, int argNum) throws WrongNumberArgsException { if(argNum < 2) super.setArg(arg, argNum); else if(2 == argNum) m_arg2 = arg; else throw new WrongNumberArgsException("3"); }
diff --git a/test/com/diycomputerscience/slides/service/SlideServiceTest.java b/test/com/diycomputerscience/slides/service/SlideServiceTest.java index 938f0bd..9554139 100644 --- a/test/com/diycomputerscience/slides/service/SlideServiceTest.java +++ b/test/com/diycomputerscience/slides/service/SlideServiceTest.java @@ -1,65 +1,65 @@ /** * */ package com.diycomputerscience.slides.service; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.ejb.embeddable.EJBContainer; import com.diycomputerscience.slides.model.Category; import com.diycomputerscience.slides.model.SlideShow; import com.diycomputerscience.slides.view.dto.CategoryTO; import com.diycomputerscience.slides.view.dto.SlideShowTO; import junit.framework.TestCase; /** * @author pshah * */ public class SlideServiceTest extends TestCase { EJBContainer ejbContainer; private SlideService slideService; /** * @param name */ public SlideServiceTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); final Properties p = new Properties(); p.put("myds", "new://Resource?type=DataSource"); p.put("myds.JdbcDriver", "org.hsqldb.jdbcDriver"); p.put("myds.JdbcUrl", "jdbc:hsqldb:mem:slidedb"); - this.ejbContainer = EJBContainer.createEJBContainer(); + this.ejbContainer = EJBContainer.createEJBContainer(p); Object oSlideService = ejbContainer.getContext().lookup("java:global/slides/SlideService"); assertNotNull(oSlideService); this.slideService = (SlideService)oSlideService; this.slideService.initDb(); } protected void tearDown() throws Exception { super.tearDown(); if(ejbContainer != null) { ejbContainer.close(); } } public void testFetchSlideShowsBycategory() { Map<CategoryTO, List<SlideShowTO>> slideShowsByCategory = this.slideService.fetchSlideShowsByCategory(); Set<CategoryTO> categories = slideShowsByCategory.keySet(); assertNotNull(slideShowsByCategory); //assertEquals(2, categories); } }
true
true
protected void setUp() throws Exception { super.setUp(); final Properties p = new Properties(); p.put("myds", "new://Resource?type=DataSource"); p.put("myds.JdbcDriver", "org.hsqldb.jdbcDriver"); p.put("myds.JdbcUrl", "jdbc:hsqldb:mem:slidedb"); this.ejbContainer = EJBContainer.createEJBContainer(); Object oSlideService = ejbContainer.getContext().lookup("java:global/slides/SlideService"); assertNotNull(oSlideService); this.slideService = (SlideService)oSlideService; this.slideService.initDb(); }
protected void setUp() throws Exception { super.setUp(); final Properties p = new Properties(); p.put("myds", "new://Resource?type=DataSource"); p.put("myds.JdbcDriver", "org.hsqldb.jdbcDriver"); p.put("myds.JdbcUrl", "jdbc:hsqldb:mem:slidedb"); this.ejbContainer = EJBContainer.createEJBContainer(p); Object oSlideService = ejbContainer.getContext().lookup("java:global/slides/SlideService"); assertNotNull(oSlideService); this.slideService = (SlideService)oSlideService; this.slideService.initDb(); }
diff --git a/src/graindcafe/tribu/TribuSpawner.java b/src/graindcafe/tribu/TribuSpawner.java index 7a87672..f80b04a 100644 --- a/src/graindcafe/tribu/TribuSpawner.java +++ b/src/graindcafe/tribu/TribuSpawner.java @@ -1,366 +1,366 @@ /******************************************************************************* * Copyright or � or Copr. Quentin Godron (2011) * * [email protected] * * This software is a computer program whose purpose is to create zombie * survival games on Bukkit's server. * * This software is governed by the CeCILL-C license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-C * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. ******************************************************************************/ package graindcafe.tribu; import graindcafe.tribu.Configuration.Constants; import graindcafe.tribu.Configuration.FocusType; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import de.ntcomputer.minecraft.controllablemobs.api.ControllableMob; import de.ntcomputer.minecraft.controllablemobs.api.ControllableMobs; import de.ntcomputer.minecraft.controllablemobs.api.ai.behaviors.AITargetNearest; public class TribuSpawner { HashMap<Entity, TribuZombie> bukkitAssociation = new HashMap<Entity, TribuZombie>(); ; /** * Is the round finish */ private boolean finished; /** * Health of zombie to spawn */ private int health; /** * A zombie just spawned */ private boolean justspawned; /** * number of zombies to spawn */ private int totalToSpawn; /** * Tribu */ private final Tribu plugin; /** * Gonna start */ private boolean starting; /** * spawned zombies */ private int alreadySpawned; /** * Referenced zombies */ // private final LinkedList<ControllableMob<Zombie>> zombies; /** * Init the spawner * @param instance of Tribu */ public TribuSpawner(final Tribu instance) { plugin = instance; alreadySpawned = 0; totalToSpawn = 5; finished = false; starting = true; health = 10; // zombies = new LinkedList<ControllableMob<Zombie>>(); } /** * Check that all referenced zombies are alive * Useful to check if a zombie has been despawned (too far away, killed but not caught) * set finished if they are all dead */ public void checkZombies() { Iterator<Entry<Entity, TribuZombie>> it = bukkitAssociation.entrySet().iterator(); finished = false; while (it.hasNext()) { ControllableMob<Zombie> e = it.next().getValue().getControl(); if (e == null || e.getEntity().isDead()) { it.remove(); finished = false; } } } /** * Delete all zombies and prevent the spawner to continue spawning */ public void clearZombies() { Iterator<Entity> it = bukkitAssociation.keySet().iterator(); while (it.hasNext()) { it.next().remove(); it.remove(); } resetTotal(); // zombies.clear(); } /** * Despawn a killed zombie * @param zombie zombie to unreference * @param drops drops to clear */ public void despawnZombie(final TribuZombie zombie, final List<ItemStack> drops) { if (bukkitAssociation.remove(zombie.getControl().getEntity()) != null) { drops.clear(); tryStartNextWave(); } // Else The zombie may have been deleted by "removedZombieCallback" /*else { plugin.LogWarning("Unreferenced zombie despawned"); }*/ } /** * Set that it's finish */ public void finishCallback() { finished = true; } // Debug command /** * This is a debug command returning the location of a living zombie * It prints info of this zombie on the console or a severe error * @return location of a living zombie */ public Location getFirstZombieLocation() { if (alreadySpawned > 0) if (!bukkitAssociation.isEmpty()) { LivingEntity e = bukkitAssociation.entrySet().iterator().next().getValue().getControl().getEntity(); plugin.LogInfo("Health : " + e.getHealth()); plugin.LogInfo("LastDamage : " + e.getLastDamage()); plugin.LogInfo("isDead : " + e.isDead()); return e.getLocation(); } else { plugin.getSpawnTimer().getState(); plugin.LogSevere("There is " + bukkitAssociation.size() + " zombie alive of " + alreadySpawned + "/" + totalToSpawn + " spawned . The wave is " + (finished ? "finished" : "in progress")); return null; } else return null; } /** * Get the total quantity of zombie to spawn * (Not counting zombies killed) * @return total to spawn */ public int getMaxSpawn() { return totalToSpawn; } /** * Get the number of zombie already spawned * @return number of zombie already spawned */ public int getTotal() { return alreadySpawned; } /** * Get the first spawn in a loaded chunk * @return */ public Location getValidSpawn() { for (final Location curPos : plugin.getLevel().getActiveSpawns()) if (curPos.getWorld().isChunkLoaded(curPos.getWorld().getChunkAt(curPos))) return curPos; plugin.LogInfo(plugin.getLocale("Warning.AllSpawnsCurrentlyUnloaded")); return null; } /** * If the spawner should continue spawning * @return */ public boolean haveZombieToSpawn() { return alreadySpawned < totalToSpawn; } /** * Check if the living entity is referenced here * @param ent * @return if the living entity was spawned by this */ public boolean isSpawned(final LivingEntity ent) { return bukkitAssociation.containsKey(ent); } /** * The wave is completed if there is no zombie to spawn and zombies spawned are dead * @return is wave completed */ public boolean isWaveCompleted() { return !haveZombieToSpawn() && bukkitAssociation.isEmpty(); } /** * Is currently spawning a zombie ? * @return */ public boolean justSpawned() { return justspawned; } /** * Kill & unreference a zombie * @param e Zombie to despawn * @param removeReward Reward attakers ? */ public void removedZombieCallback(final Entity e, final boolean removeReward) { if (e != null) { TribuZombie zomb = bukkitAssociation.get(e); if (zomb == null) return; bukkitAssociation.remove(e); alreadySpawned--; if (removeReward) zomb.setNoAttacker(); e.remove(); } } /** * Prevent spawner to continue spawning but do not set it as finished */ public void resetTotal() { alreadySpawned = 0; finished = false; } /** * Set health of zombie to spawn * @param value Health */ public void setHealth(final int value) { health = value; } /** * Set the number of zombie to spawn * @param count */ public void setMaxSpawn(final int count) { totalToSpawn = count; } /** * Try to spawn a zombie * @return if zombies still have to spawn (before spawning it) */ @SuppressWarnings("deprecation") public boolean spawnZombie() { if (alreadySpawned < totalToSpawn && !finished) { Location pos = plugin.getLevel().getRandomZombieSpawn(); if (pos != null) { if (!pos.getWorld().isChunkLoaded(pos.getWorld().getChunkAt(pos))) { checkZombies(); pos = getValidSpawn(); } if (pos != null) { // Surrounded with justspawned so that the zombie isn't // removed in the entity spawn listener justspawned = true; Zombie zombie; try { zombie = pos.getWorld().spawn(pos, Zombie.class); zombie.setHealth(health); TribuZombie zomb = new TribuZombie(ControllableMobs.assign(zombie, false)); if (plugin.config().ZombiesFocus == FocusType.NearestPlayer) zomb.getControl().getAI().addAIBehavior(new AITargetNearest(1, 1000)); if (plugin.config().ZombiesFocus == FocusType.DeathSpawn) zomb.getControl().getActions().moveTo(plugin.getLevel().getDeathSpawn()); if (plugin.config().ZombiesFocus == FocusType.InitialSpawn) zomb.getControl().getActions().moveTo(plugin.getLevel().getDeathSpawn()); if (plugin.config().ZombiesFocus == FocusType.RandomPlayer) // for (int i = 0; i < 5; i++) zomb.getControl().getActions().target(plugin.getRandomPlayer(), true); zomb.getControl().getAttributes().setMaximumNavigationDistance(Double.POSITIVE_INFINITY); // Default speed * ( (1/10 + rand() * 1/3 | 1/4) + 3/4 * // base ) - zomb.getControl().getProperties().setMovementSpeed(0.25f * ((plugin.config().ZombiesSpeedRandom) ? .1f + (Tribu.getRandom().nextFloat() / 3f) : .25f) + (plugin.config().ZombiesSpeedBase - .25f)); + zomb.getControl().getProperties().setMovementSpeed(0.25f * ((plugin.config().ZombiesSpeedRandom ? .1f + Tribu.getRandom().nextFloat() / 3f : .25f) + plugin.config().ZombiesSpeedBase - .25f)); bukkitAssociation.put(zombie, zomb); // Rush speed // sun proof // fire proof alreadySpawned++; } catch (final Exception e) { // Impossible to spawn the zombie, maybe because of lack // of // space e.printStackTrace(); } justspawned = false; } } } else return false; return true; } /** * Set that the spawner has started */ public void startingCallback() { starting = false; } /** * Try to start the next wave if possible and return if it's starting * @return */ public boolean tryStartNextWave() { if (bukkitAssociation.isEmpty() && finished && !starting) { starting = true; plugin.messagePlayers(plugin.getLocale("Broadcast.WaveComplete")); plugin.getWaveStarter().incrementWave(); plugin.getWaveStarter().scheduleWave(Constants.TicksBySecond * plugin.config().WaveStartDelay); } return starting; } public HashMap<Entity, TribuZombie> getBukkitAssociation() { return bukkitAssociation; } }
true
true
public boolean spawnZombie() { if (alreadySpawned < totalToSpawn && !finished) { Location pos = plugin.getLevel().getRandomZombieSpawn(); if (pos != null) { if (!pos.getWorld().isChunkLoaded(pos.getWorld().getChunkAt(pos))) { checkZombies(); pos = getValidSpawn(); } if (pos != null) { // Surrounded with justspawned so that the zombie isn't // removed in the entity spawn listener justspawned = true; Zombie zombie; try { zombie = pos.getWorld().spawn(pos, Zombie.class); zombie.setHealth(health); TribuZombie zomb = new TribuZombie(ControllableMobs.assign(zombie, false)); if (plugin.config().ZombiesFocus == FocusType.NearestPlayer) zomb.getControl().getAI().addAIBehavior(new AITargetNearest(1, 1000)); if (plugin.config().ZombiesFocus == FocusType.DeathSpawn) zomb.getControl().getActions().moveTo(plugin.getLevel().getDeathSpawn()); if (plugin.config().ZombiesFocus == FocusType.InitialSpawn) zomb.getControl().getActions().moveTo(plugin.getLevel().getDeathSpawn()); if (plugin.config().ZombiesFocus == FocusType.RandomPlayer) // for (int i = 0; i < 5; i++) zomb.getControl().getActions().target(plugin.getRandomPlayer(), true); zomb.getControl().getAttributes().setMaximumNavigationDistance(Double.POSITIVE_INFINITY); // Default speed * ( (1/10 + rand() * 1/3 | 1/4) + 3/4 * // base ) zomb.getControl().getProperties().setMovementSpeed(0.25f * ((plugin.config().ZombiesSpeedRandom) ? .1f + (Tribu.getRandom().nextFloat() / 3f) : .25f) + (plugin.config().ZombiesSpeedBase - .25f)); bukkitAssociation.put(zombie, zomb); // Rush speed // sun proof // fire proof alreadySpawned++; } catch (final Exception e) { // Impossible to spawn the zombie, maybe because of lack // of // space e.printStackTrace(); } justspawned = false; } } } else return false; return true; }
public boolean spawnZombie() { if (alreadySpawned < totalToSpawn && !finished) { Location pos = plugin.getLevel().getRandomZombieSpawn(); if (pos != null) { if (!pos.getWorld().isChunkLoaded(pos.getWorld().getChunkAt(pos))) { checkZombies(); pos = getValidSpawn(); } if (pos != null) { // Surrounded with justspawned so that the zombie isn't // removed in the entity spawn listener justspawned = true; Zombie zombie; try { zombie = pos.getWorld().spawn(pos, Zombie.class); zombie.setHealth(health); TribuZombie zomb = new TribuZombie(ControllableMobs.assign(zombie, false)); if (plugin.config().ZombiesFocus == FocusType.NearestPlayer) zomb.getControl().getAI().addAIBehavior(new AITargetNearest(1, 1000)); if (plugin.config().ZombiesFocus == FocusType.DeathSpawn) zomb.getControl().getActions().moveTo(plugin.getLevel().getDeathSpawn()); if (plugin.config().ZombiesFocus == FocusType.InitialSpawn) zomb.getControl().getActions().moveTo(plugin.getLevel().getDeathSpawn()); if (plugin.config().ZombiesFocus == FocusType.RandomPlayer) // for (int i = 0; i < 5; i++) zomb.getControl().getActions().target(plugin.getRandomPlayer(), true); zomb.getControl().getAttributes().setMaximumNavigationDistance(Double.POSITIVE_INFINITY); // Default speed * ( (1/10 + rand() * 1/3 | 1/4) + 3/4 * // base ) zomb.getControl().getProperties().setMovementSpeed(0.25f * ((plugin.config().ZombiesSpeedRandom ? .1f + Tribu.getRandom().nextFloat() / 3f : .25f) + plugin.config().ZombiesSpeedBase - .25f)); bukkitAssociation.put(zombie, zomb); // Rush speed // sun proof // fire proof alreadySpawned++; } catch (final Exception e) { // Impossible to spawn the zombie, maybe because of lack // of // space e.printStackTrace(); } justspawned = false; } } } else return false; return true; }
diff --git a/oaaas-authorization-server-war/src/test/java/it/VerifyResourceTestIT.java b/oaaas-authorization-server-war/src/test/java/it/VerifyResourceTestIT.java index 7b31fe5..ce5ac38 100644 --- a/oaaas-authorization-server-war/src/test/java/it/VerifyResourceTestIT.java +++ b/oaaas-authorization-server-war/src/test/java/it/VerifyResourceTestIT.java @@ -1,79 +1,79 @@ /* * Copyright 2012 SURFnet bv, The Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import org.junit.Test; import org.surfnet.oaaas.auth.VerifyTokenResponse; import static org.junit.Assert.assertEquals; public class VerifyResourceTestIT extends AbstractAuthorizationServerTest { @Test public void withNoParams() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) .get(ClientResponse.class); assertEquals(401, response.getStatus()); } @Test public void withNoAuthorizationHeader() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) .queryParam("access_token", "boobaa") .get(ClientResponse.class); assertEquals(401, response.getStatus()); } @Test public void withInvalidAuthorizationHeader() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) .queryParam("access_token", "boobaa") .header("Authorization", "NotBasicButGarbage abb ccc dd") .get(ClientResponse.class); assertEquals(401, response.getStatus()); } @Test public void withValidAuthorizationHeaderButNoAccessToken() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) .header("Authorization", authorizationBasic("user", "pass")) .get(ClientResponse.class); assertEquals(401, response.getStatus()); } @Test public void happy() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) - .queryParam("access_token", "boobaa") - .header("Authorization", authorizationBasic("authorization-server-admin", "cafebabe-cafe-babe-cafe-babecafebabe")) + .queryParam("access_token", "00-11-22-33") + .header("Authorization", authorizationBasic("it-test-resource-server", "somesecret")) .get(ClientResponse.class); assertEquals(200, response.getStatus()); final VerifyTokenResponse verifyTokenResponse = response.getEntity(VerifyTokenResponse.class); - assertEquals("boo", verifyTokenResponse.getUser_id()); + assertEquals("it-test-enduser", verifyTokenResponse.getUser_id()); } }
false
true
public void happy() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) .queryParam("access_token", "boobaa") .header("Authorization", authorizationBasic("authorization-server-admin", "cafebabe-cafe-babe-cafe-babecafebabe")) .get(ClientResponse.class); assertEquals(200, response.getStatus()); final VerifyTokenResponse verifyTokenResponse = response.getEntity(VerifyTokenResponse.class); assertEquals("boo", verifyTokenResponse.getUser_id()); }
public void happy() { final ClientResponse response = new Client() .resource(baseUrlWith("/v1/tokeninfo")) .queryParam("access_token", "00-11-22-33") .header("Authorization", authorizationBasic("it-test-resource-server", "somesecret")) .get(ClientResponse.class); assertEquals(200, response.getStatus()); final VerifyTokenResponse verifyTokenResponse = response.getEntity(VerifyTokenResponse.class); assertEquals("it-test-enduser", verifyTokenResponse.getUser_id()); }
diff --git a/src/main/java/net/robbytu/banjoserver/bungee/auth/LoginAlert.java b/src/main/java/net/robbytu/banjoserver/bungee/auth/LoginAlert.java index 4e461d2..c915df0 100644 --- a/src/main/java/net/robbytu/banjoserver/bungee/auth/LoginAlert.java +++ b/src/main/java/net/robbytu/banjoserver/bungee/auth/LoginAlert.java @@ -1,33 +1,34 @@ package net.robbytu.banjoserver.bungee.auth; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.LoginEvent; import net.robbytu.banjoserver.bungee.Main; import java.util.concurrent.TimeUnit; public class LoginAlert { public static void handle(final LoginEvent event) { Main.instance.getProxy().getScheduler().schedule(Main.instance, new Runnable() { @Override public void run() { final ProxiedPlayer target = Main.instance.getProxy().getPlayer(event.getConnection().getName()); boolean registered = AuthProvider.isRegistered(target.getName()); target.sendMessage(ChatColor.GREEN + "Welkom " + ((registered) ? "terug " : "") + "in de Banjoserver, " + target.getName() + "!"); target.sendMessage(ChatColor.GRAY + "Gebruik " + ((registered) ? ChatColor.WHITE + "/login [wachtwoord]" + ChatColor.GRAY + " om in te loggen." : ChatColor.WHITE + "/register [wachtwoord]" + ChatColor.GRAY + " om te registreren.")); target.sendMessage(" "); Main.instance.getProxy().getScheduler().schedule(Main.instance, new Runnable() { @Override public void run() { + if(target == null) return; //BS-89 if(!AuthProvider.isAuthenticated(target)) { target.disconnect("Om overbelasting van onze servers te voorkomen moet je binnen 30 seconden inloggen."); } } }, 29, TimeUnit.SECONDS); } }, 1, TimeUnit.SECONDS); } }
true
true
public static void handle(final LoginEvent event) { Main.instance.getProxy().getScheduler().schedule(Main.instance, new Runnable() { @Override public void run() { final ProxiedPlayer target = Main.instance.getProxy().getPlayer(event.getConnection().getName()); boolean registered = AuthProvider.isRegistered(target.getName()); target.sendMessage(ChatColor.GREEN + "Welkom " + ((registered) ? "terug " : "") + "in de Banjoserver, " + target.getName() + "!"); target.sendMessage(ChatColor.GRAY + "Gebruik " + ((registered) ? ChatColor.WHITE + "/login [wachtwoord]" + ChatColor.GRAY + " om in te loggen." : ChatColor.WHITE + "/register [wachtwoord]" + ChatColor.GRAY + " om te registreren.")); target.sendMessage(" "); Main.instance.getProxy().getScheduler().schedule(Main.instance, new Runnable() { @Override public void run() { if(!AuthProvider.isAuthenticated(target)) { target.disconnect("Om overbelasting van onze servers te voorkomen moet je binnen 30 seconden inloggen."); } } }, 29, TimeUnit.SECONDS); } }, 1, TimeUnit.SECONDS); }
public static void handle(final LoginEvent event) { Main.instance.getProxy().getScheduler().schedule(Main.instance, new Runnable() { @Override public void run() { final ProxiedPlayer target = Main.instance.getProxy().getPlayer(event.getConnection().getName()); boolean registered = AuthProvider.isRegistered(target.getName()); target.sendMessage(ChatColor.GREEN + "Welkom " + ((registered) ? "terug " : "") + "in de Banjoserver, " + target.getName() + "!"); target.sendMessage(ChatColor.GRAY + "Gebruik " + ((registered) ? ChatColor.WHITE + "/login [wachtwoord]" + ChatColor.GRAY + " om in te loggen." : ChatColor.WHITE + "/register [wachtwoord]" + ChatColor.GRAY + " om te registreren.")); target.sendMessage(" "); Main.instance.getProxy().getScheduler().schedule(Main.instance, new Runnable() { @Override public void run() { if(target == null) return; //BS-89 if(!AuthProvider.isAuthenticated(target)) { target.disconnect("Om overbelasting van onze servers te voorkomen moet je binnen 30 seconden inloggen."); } } }, 29, TimeUnit.SECONDS); } }, 1, TimeUnit.SECONDS); }
diff --git a/src/main/java/org/gwaspi/dao/sql/OperationServiceImpl.java b/src/main/java/org/gwaspi/dao/sql/OperationServiceImpl.java index 82a2f0bb..a0c679b5 100644 --- a/src/main/java/org/gwaspi/dao/sql/OperationServiceImpl.java +++ b/src/main/java/org/gwaspi/dao/sql/OperationServiceImpl.java @@ -1,445 +1,446 @@ package org.gwaspi.dao.sql; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.gwaspi.constants.cDBGWASpi; import org.gwaspi.constants.cDBOperations; import org.gwaspi.constants.cNetCDF; import org.gwaspi.constants.cNetCDF.Defaults.OPType; import org.gwaspi.dao.OperationService; import org.gwaspi.database.DbManager; import org.gwaspi.global.Config; import org.gwaspi.global.ServiceLocator; import org.gwaspi.model.Operation; import org.gwaspi.model.OperationMetadata; import org.gwaspi.model.ReportsList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.nc2.Dimension; import ucar.nc2.NetcdfFile; public class OperationServiceImpl implements OperationService { private static final Logger log = LoggerFactory.getLogger(OperationServiceImpl.class); /** * This will init the Matrix object requested from the DB */ @Override public Operation getById(int operationId) throws IOException { Operation operation = null; List<Map<String, Object>> rs = getOperationMetadataRS(operationId); // PREVENT PHANTOM-DB READS EXCEPTIONS if (!rs.isEmpty() && rs.get(0).size() == cDBOperations.T_CREATE_OPERATIONS.length) { String friendlyName = (rs.get(0).get(cDBOperations.f_OP_NAME) != null) ? rs.get(0).get(cDBOperations.f_OP_NAME).toString() : ""; String netCDFName = (rs.get(0).get(cDBOperations.f_OP_NETCDF_NAME) != null) ? rs.get(0).get(cDBOperations.f_OP_NETCDF_NAME).toString() : ""; String type = (rs.get(0).get(cDBOperations.f_OP_TYPE) != null) ? rs.get(0).get(cDBOperations.f_OP_TYPE).toString() : ""; int parentMatrixId = (rs.get(0).get(cDBOperations.f_PARENT_MATRIXID) != null) ? Integer.parseInt(rs.get(0).get(cDBOperations.f_PARENT_MATRIXID).toString()) : -1; int parentOperationId = (rs.get(0).get(cDBOperations.f_PARENT_OPID) != null) ? Integer.parseInt(rs.get(0).get(cDBOperations.f_PARENT_OPID).toString()) : -1; String command = (rs.get(0).get(cDBOperations.f_OP_COMMAND) != null) ? rs.get(0).get(cDBOperations.f_OP_COMMAND).toString() : ""; String description = (rs.get(0).get(cDBOperations.f_DESCRIPTION) != null) ? rs.get(0).get(cDBOperations.f_DESCRIPTION).toString() : ""; int studyId = (rs.get(0).get(cDBOperations.f_STUDYID) != null) ? Integer.parseInt(rs.get(0).get(cDBOperations.f_STUDYID).toString()) : 0; operation = new Operation( operationId, friendlyName, netCDFName, type, parentMatrixId, parentOperationId, command, description, studyId); } return operation; } private static List<Map<String, Object>> getOperationMetadataRS(int opId) throws IOException { List<Map<String, Object>> rs = null; String dbName = cDBGWASpi.DB_DATACENTER; DbManager studyDbManager = ServiceLocator.getDbManager(dbName); try { rs = studyDbManager.executeSelectStatement("SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_ID + "=" + opId + " WITH RR"); } catch (Exception ex) { log.error(null, ex); } return rs; } @Override public List<Operation> getOperationsList(int matrixId) throws IOException { List<Operation> operationsList = new ArrayList<Operation>(); List<Map<String, Object>> rsOperations = getOperationsListByMatrixId(matrixId); int rowcount = rsOperations.size(); if (rowcount > 0) { for (int i = 0; i < rowcount; i++) // loop through rows of result set { //PREVENT PHANTOM-DB READS EXCEPTIONS if (!rsOperations.isEmpty() && rsOperations.get(i).size() == cDBOperations.T_CREATE_OPERATIONS.length) { int currentOPId = (Integer) rsOperations.get(i).get(cDBOperations.f_ID); Operation currentOP = getById(currentOPId); operationsList.add(currentOP); } } } return operationsList; } @Override public List<Operation> getOperationsList(int matrixId, int parentOpId) throws IOException { List<Operation> operationsList = new ArrayList<Operation>(); List<Map<String, Object>> rsOperations = getOperationsListByMatrixId(matrixId); int rowcount = rsOperations.size(); if (rowcount > 0) { // loop through rows of result set for (int i = 0; i < rowcount; i++) { // PREVENT PHANTOM-DB READS EXCEPTIONS if (!rsOperations.isEmpty() && rsOperations.get(i).size() == cDBOperations.T_CREATE_OPERATIONS.length) { int currentParentOPId = (Integer) rsOperations.get(i).get(cDBOperations.f_PARENT_OPID); int currentOpId = (Integer) rsOperations.get(i).get(cDBOperations.f_ID); if (currentParentOPId == parentOpId) { Operation currentOP = getById(currentOpId); operationsList.add(currentOP); } } } } return operationsList; } @Override public List<Operation> getOperationsList(int matrixId, int parentOpId, OPType opType) throws IOException { List<Operation> operationsList = new ArrayList<Operation>(); List<Map<String, Object>> rsOperations = getOperationsListByMatrixId(matrixId); int rowcount = rsOperations.size(); if (rowcount > 0) { // loop through rows of result set for (int i = 0; i < rowcount; i++) { // PREVENT PHANTOM-DB READS EXCEPTIONS if (!rsOperations.isEmpty() && rsOperations.get(i).size() == cDBOperations.T_CREATE_OPERATIONS.length) { int currentParentOPId = (Integer) rsOperations.get(i).get(cDBOperations.f_PARENT_OPID); int currentOpId = (Integer) rsOperations.get(i).get(cDBOperations.f_ID); String currentOpType = rsOperations.get(i).get(cDBOperations.f_OP_TYPE).toString(); if (currentParentOPId == parentOpId && currentOpType.equals(opType.toString())) { Operation currentOP = getById(currentOpId); operationsList.add(currentOP); } } } } return operationsList; } private static List<Map<String, Object>> getOperationsListByMatrixId(int matrixId) throws IOException { List<Map<String, Object>> rs = null; String dbName = cDBGWASpi.DB_DATACENTER; DbManager studyDbManager = ServiceLocator.getDbManager(dbName); try { rs = studyDbManager.executeSelectStatement("SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_PARENT_MATRIXID + "=" + matrixId + " WITH RR"); } catch (Exception ex) { log.error(null, ex); } return rs; } //<editor-fold defaultstate="expanded" desc="OPERATIONS TABLES"> @Override public List<OperationMetadata> getOperationsTable(int matrixId) throws IOException { List<OperationMetadata> operations = new ArrayList<OperationMetadata>(); String dbName = cDBGWASpi.DB_DATACENTER; DbManager dbManager = ServiceLocator.getDbManager(dbName); try { List<Map<String, Object>> rs = dbManager.executeSelectStatement("SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_PARENT_MATRIXID + "=" + matrixId + " AND " + cDBOperations.f_PARENT_OPID + " = -1" + " WITH RR"); for (Map<String, Object> dbProps : rs) { OperationMetadata operationMetadata = getOperationMetadata(dbProps); if (operationMetadata != null) { operations.add(operationMetadata); } } } catch (Exception ex) { log.error(null, ex); } return operations; } @Override public List<OperationMetadata> getOperationsTable(int matrixId, int opId) throws IOException { List<OperationMetadata> operations = new ArrayList<OperationMetadata>(); String dbName = cDBGWASpi.DB_DATACENTER; DbManager dbManager = ServiceLocator.getDbManager(dbName); try { List<Map<String, Object>> rs = dbManager.executeSelectStatement("SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_PARENT_MATRIXID + "=" + matrixId + " AND " + cDBOperations.f_PARENT_OPID + "=" + opId + " WITH RR"); List<Map<String, Object>> rsSelf = dbManager.executeSelectStatement("SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_PARENT_MATRIXID + "=" + matrixId + " AND " + cDBOperations.f_ID + "=" + opId + " WITH RR"); if (!rs.isEmpty()) { operations.add(getOperationMetadata(rsSelf.get(0))); } for (Map<String, Object> dbProps : rsSelf) { OperationMetadata operationMetadata = getOperationMetadata(dbProps); if (operationMetadata != null) { operations.add(operationMetadata); } } } catch (Exception ex) { log.error(null, ex); } return operations; } //</editor-fold> //<editor-fold defaultstate="expanded" desc="HELPERS"> @Override public int getIdOfLastOperationTypeOccurance(List<Operation> operationsList, OPType opType) { int result = Integer.MIN_VALUE; for (int i = 0; i < operationsList.size(); i++) { if (operationsList.get(i).getOperationType().equals(OPType.MARKER_QA.toString())) { result = operationsList.get(i).getId(); } } return result; } //</editor-fold> @Override public String createOperationsMetadataTable() { boolean result = false; try { DbManager db = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); // CREATE SAMPLESET_METADATA table in given SCHEMA db.createTable(cDBGWASpi.SCH_MATRICES, cDBOperations.T_OPERATIONS, cDBOperations.T_CREATE_OPERATIONS); } catch (Exception ex) { log.error("Failed creating management database", ex); } return (result ? "1" : "0"); } @Override public void insertOPMetadata(OperationMetadata operationMetadata) throws IOException { Object[] opMetaData = new Object[] { operationMetadata.getParentMatrixId(), operationMetadata.getParentOperationId(), operationMetadata.getOPName(), operationMetadata.getMatrixCDFName(), (operationMetadata.getGenotypeCode() == null) ? "" : operationMetadata.getGenotypeCode().name(), "", // command operationMetadata.getDescription(), operationMetadata.getStudyId() }; DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); dBManager.insertValuesInTable(cDBGWASpi.SCH_MATRICES, cDBOperations.T_OPERATIONS, cDBOperations.F_INSERT_OPERATION, opMetaData); } @Override public List<Object[]> getMatrixOperations(int matrixId) throws IOException { List<Object[]> result = new ArrayList<Object[]>(); DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); List<Map<String, Object>> rs = dBManager.executeSelectStatement("SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_PARENT_MATRIXID + "=" + matrixId + " WITH RR"); for (int rowcount = 0; rowcount < rs.size(); rowcount++) { // PREVENT PHANTOM-DB READS EXCEPTIONS if (!rs.isEmpty() && rs.get(rowcount).size() == cDBOperations.T_CREATE_OPERATIONS.length) { Object[] element = new Object[2]; element[0] = (Integer) rs.get(rowcount).get(cDBOperations.f_ID); element[1] = rs.get(rowcount).get(cDBOperations.f_OP_TYPE).toString(); result.add(element); } } return result; } @Override public void deleteOperationBranch(int studyId, int opId, boolean deleteReports) throws IOException { try { Operation op = getById(opId); String genotypesFolder = Config.getConfigValue(Config.PROPERTY_GENOTYPES_DIR, ""); List<Operation> operations = getOperationsList(op.getParentMatrixId(), opId); if (!operations.isEmpty()) { operations.add(op); for (int i = 0; i < operations.size(); i++) { File matrixOPFile = new File(genotypesFolder + "/STUDY_" + studyId + "/" + operations.get(i).getNetCDFName() + ".nc"); org.gwaspi.global.Utils.tryToDeleteFile(matrixOPFile); if (deleteReports) { ReportsList.deleteReportByOperationId(operations.get(i).getId()); } DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); String statement = "DELETE FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_ID + "=" + operations.get(i).getId(); dBManager.executeStatement(statement); } } else { File matrixOPFile = new File(genotypesFolder + "/STUDY_" + studyId + "/" + op.getNetCDFName() + ".nc"); org.gwaspi.global.Utils.tryToDeleteFile(matrixOPFile); if (deleteReports) { ReportsList.deleteReportByOperationId(opId); } DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); String statement = "DELETE FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_ID + "=" + opId; dBManager.executeStatement(statement); } } catch (IOException ex) { log.warn(null, ex); // PURGE INEXISTING OPERATIONS FROM DB DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); String statement = "DELETE FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_ID + "=" + opId; dBManager.executeStatement(statement); } catch (IllegalArgumentException ex) { log.warn(null, ex); // PURGE INEXISTING OPERATIONS FROM DB DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); String statement = "DELETE FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_ID + "=" + opId; dBManager.executeStatement(statement); } } @Override public OperationMetadata getOperationMetadata(int opId) throws IOException { OperationMetadata operationMetadata = null; DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); List<Map<String, Object>> rs = dBManager.executeSelectStatement( "SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_ID + "=" + opId + " WITH RR"); if (!rs.isEmpty()) { operationMetadata = getOperationMetadata(rs.get(0)); } return operationMetadata; } @Override public OperationMetadata getOperationMetadata(String netCDFname) throws IOException { OperationMetadata operationMetadata = null; DbManager dBManager = ServiceLocator.getDbManager(cDBGWASpi.DB_DATACENTER); String sql = "SELECT * FROM " + cDBGWASpi.SCH_MATRICES + "." + cDBOperations.T_OPERATIONS + " WHERE " + cDBOperations.f_OP_NETCDF_NAME + "='" + netCDFname + "' ORDER BY " + cDBOperations.f_ID + " DESC WITH RR"; List<Map<String, Object>> rs = dBManager.executeSelectStatement(sql); if (!rs.isEmpty()) { operationMetadata = getOperationMetadata(rs.get(0)); } return operationMetadata; } private OperationMetadata getOperationMetadata(Map<String, Object> dbProperties) throws IOException { int opId = Integer.MIN_VALUE; int parentMatrixId = Integer.MIN_VALUE; int parentOperationId = Integer.MIN_VALUE; String opName = ""; String netCDF_name = ""; String description = ""; OPType gtCode = null; int studyId = Integer.MIN_VALUE; int opSetSize = Integer.MIN_VALUE; int implicitSetSize = Integer.MIN_VALUE; long creationDate = Long.MIN_VALUE; // PREVENT PHANTOM-DB READS EXCEPTIONS if (dbProperties.size() == cDBOperations.T_CREATE_OPERATIONS.length) { opId = Integer.parseInt(dbProperties.get(cDBOperations.f_ID).toString()); parentMatrixId = Integer.parseInt(dbProperties.get(cDBOperations.f_PARENT_MATRIXID).toString()); parentOperationId = Integer.parseInt(dbProperties.get(cDBOperations.f_PARENT_OPID).toString()); opName = dbProperties.get(cDBOperations.f_OP_NAME).toString(); netCDF_name = dbProperties.get(cDBOperations.f_OP_NETCDF_NAME).toString(); description = dbProperties.get(cDBOperations.f_DESCRIPTION).toString(); - // FIXME fill gtCode with value from f_OP_TYPE + String gtCodeStr = dbProperties.get(cDBOperations.f_OP_TYPE).toString(); + gtCode = OPType.valueOf(gtCodeStr); studyId = (Integer) dbProperties.get(cDBOperations.f_STUDYID); String dateTime = dbProperties.get(cDBOperations.f_CREATION_DATE).toString(); dateTime = dateTime.substring(0, dateTime.lastIndexOf('.')); creationDate = org.gwaspi.global.Utils.stringToDate(dateTime, "yyyy-MM-dd HH:mm:ss").getTime(); } String genotypesFolder = Config.getConfigValue(Config.PROPERTY_GENOTYPES_DIR, ""); String pathToStudy = genotypesFolder + "/STUDY_" + studyId + "/"; String pathToMatrix = pathToStudy + netCDF_name + ".nc"; NetcdfFile ncfile = null; if (new File(pathToMatrix).exists()) { try { ncfile = NetcdfFile.open(pathToMatrix); // gtCode = ncfile.findGlobalAttribute(cNetCDF.Attributes.GLOB_GTCODE).getStringValue(); Dimension markerSetDim = ncfile.findDimension(cNetCDF.Dimensions.DIM_OPSET); opSetSize = markerSetDim.getLength(); Dimension implicitDim = ncfile.findDimension(cNetCDF.Dimensions.DIM_IMPLICITSET); implicitSetSize = implicitDim.getLength(); } catch (IOException ex) { log.error("Cannot open file: " + pathToMatrix, ex); } finally { if (null != ncfile) { try { ncfile.close(); } catch (IOException ex) { log.warn("Cannot close file: " + ncfile.getLocation(), ex); } } } } OperationMetadata operationMetadata = new OperationMetadata( opId, parentMatrixId, parentOperationId, opName, netCDF_name, description, pathToMatrix, gtCode, opSetSize, implicitSetSize, studyId, creationDate); return operationMetadata; } }
true
true
private OperationMetadata getOperationMetadata(Map<String, Object> dbProperties) throws IOException { int opId = Integer.MIN_VALUE; int parentMatrixId = Integer.MIN_VALUE; int parentOperationId = Integer.MIN_VALUE; String opName = ""; String netCDF_name = ""; String description = ""; OPType gtCode = null; int studyId = Integer.MIN_VALUE; int opSetSize = Integer.MIN_VALUE; int implicitSetSize = Integer.MIN_VALUE; long creationDate = Long.MIN_VALUE; // PREVENT PHANTOM-DB READS EXCEPTIONS if (dbProperties.size() == cDBOperations.T_CREATE_OPERATIONS.length) { opId = Integer.parseInt(dbProperties.get(cDBOperations.f_ID).toString()); parentMatrixId = Integer.parseInt(dbProperties.get(cDBOperations.f_PARENT_MATRIXID).toString()); parentOperationId = Integer.parseInt(dbProperties.get(cDBOperations.f_PARENT_OPID).toString()); opName = dbProperties.get(cDBOperations.f_OP_NAME).toString(); netCDF_name = dbProperties.get(cDBOperations.f_OP_NETCDF_NAME).toString(); description = dbProperties.get(cDBOperations.f_DESCRIPTION).toString(); // FIXME fill gtCode with value from f_OP_TYPE studyId = (Integer) dbProperties.get(cDBOperations.f_STUDYID); String dateTime = dbProperties.get(cDBOperations.f_CREATION_DATE).toString(); dateTime = dateTime.substring(0, dateTime.lastIndexOf('.')); creationDate = org.gwaspi.global.Utils.stringToDate(dateTime, "yyyy-MM-dd HH:mm:ss").getTime(); } String genotypesFolder = Config.getConfigValue(Config.PROPERTY_GENOTYPES_DIR, ""); String pathToStudy = genotypesFolder + "/STUDY_" + studyId + "/"; String pathToMatrix = pathToStudy + netCDF_name + ".nc"; NetcdfFile ncfile = null; if (new File(pathToMatrix).exists()) { try { ncfile = NetcdfFile.open(pathToMatrix); // gtCode = ncfile.findGlobalAttribute(cNetCDF.Attributes.GLOB_GTCODE).getStringValue(); Dimension markerSetDim = ncfile.findDimension(cNetCDF.Dimensions.DIM_OPSET); opSetSize = markerSetDim.getLength(); Dimension implicitDim = ncfile.findDimension(cNetCDF.Dimensions.DIM_IMPLICITSET); implicitSetSize = implicitDim.getLength(); } catch (IOException ex) { log.error("Cannot open file: " + pathToMatrix, ex); } finally { if (null != ncfile) { try { ncfile.close(); } catch (IOException ex) { log.warn("Cannot close file: " + ncfile.getLocation(), ex); } } } } OperationMetadata operationMetadata = new OperationMetadata( opId, parentMatrixId, parentOperationId, opName, netCDF_name, description, pathToMatrix, gtCode, opSetSize, implicitSetSize, studyId, creationDate); return operationMetadata; }
private OperationMetadata getOperationMetadata(Map<String, Object> dbProperties) throws IOException { int opId = Integer.MIN_VALUE; int parentMatrixId = Integer.MIN_VALUE; int parentOperationId = Integer.MIN_VALUE; String opName = ""; String netCDF_name = ""; String description = ""; OPType gtCode = null; int studyId = Integer.MIN_VALUE; int opSetSize = Integer.MIN_VALUE; int implicitSetSize = Integer.MIN_VALUE; long creationDate = Long.MIN_VALUE; // PREVENT PHANTOM-DB READS EXCEPTIONS if (dbProperties.size() == cDBOperations.T_CREATE_OPERATIONS.length) { opId = Integer.parseInt(dbProperties.get(cDBOperations.f_ID).toString()); parentMatrixId = Integer.parseInt(dbProperties.get(cDBOperations.f_PARENT_MATRIXID).toString()); parentOperationId = Integer.parseInt(dbProperties.get(cDBOperations.f_PARENT_OPID).toString()); opName = dbProperties.get(cDBOperations.f_OP_NAME).toString(); netCDF_name = dbProperties.get(cDBOperations.f_OP_NETCDF_NAME).toString(); description = dbProperties.get(cDBOperations.f_DESCRIPTION).toString(); String gtCodeStr = dbProperties.get(cDBOperations.f_OP_TYPE).toString(); gtCode = OPType.valueOf(gtCodeStr); studyId = (Integer) dbProperties.get(cDBOperations.f_STUDYID); String dateTime = dbProperties.get(cDBOperations.f_CREATION_DATE).toString(); dateTime = dateTime.substring(0, dateTime.lastIndexOf('.')); creationDate = org.gwaspi.global.Utils.stringToDate(dateTime, "yyyy-MM-dd HH:mm:ss").getTime(); } String genotypesFolder = Config.getConfigValue(Config.PROPERTY_GENOTYPES_DIR, ""); String pathToStudy = genotypesFolder + "/STUDY_" + studyId + "/"; String pathToMatrix = pathToStudy + netCDF_name + ".nc"; NetcdfFile ncfile = null; if (new File(pathToMatrix).exists()) { try { ncfile = NetcdfFile.open(pathToMatrix); // gtCode = ncfile.findGlobalAttribute(cNetCDF.Attributes.GLOB_GTCODE).getStringValue(); Dimension markerSetDim = ncfile.findDimension(cNetCDF.Dimensions.DIM_OPSET); opSetSize = markerSetDim.getLength(); Dimension implicitDim = ncfile.findDimension(cNetCDF.Dimensions.DIM_IMPLICITSET); implicitSetSize = implicitDim.getLength(); } catch (IOException ex) { log.error("Cannot open file: " + pathToMatrix, ex); } finally { if (null != ncfile) { try { ncfile.close(); } catch (IOException ex) { log.warn("Cannot close file: " + ncfile.getLocation(), ex); } } } } OperationMetadata operationMetadata = new OperationMetadata( opId, parentMatrixId, parentOperationId, opName, netCDF_name, description, pathToMatrix, gtCode, opSetSize, implicitSetSize, studyId, creationDate); return operationMetadata; }
diff --git a/src/com/csipsimple/service/MediaManager.java b/src/com/csipsimple/service/MediaManager.java index dc70781f..0916a577 100644 --- a/src/com/csipsimple/service/MediaManager.java +++ b/src/com/csipsimple/service/MediaManager.java @@ -1,631 +1,634 @@ /** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.media.AudioManager; import android.media.ToneGenerator; import android.net.NetworkInfo.DetailedState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.provider.Settings; import com.csipsimple.api.MediaState; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipManager; import com.csipsimple.service.SipService.SameThreadException; import com.csipsimple.service.SipService.SipRunnable; import com.csipsimple.utils.Compatibility; import com.csipsimple.utils.Log; import com.csipsimple.utils.Ringer; import com.csipsimple.utils.accessibility.AccessibilityWrapper; import com.csipsimple.utils.audio.AudioFocusWrapper; import com.csipsimple.utils.bluetooth.BluetoothWrapper; public class MediaManager { final private static String THIS_FILE = "MediaManager"; private SipService service; private AudioManager audioManager; private Ringer ringer; //Locks private WifiLock wifiLock; private WakeLock screenLock; private WakeLock cpuLock; // Media settings to save / resore private boolean isSetAudioMode = false; //By default we assume user want bluetooth. //If bluetooth is not available connection will never be done and then //UI will not show bluetooth is activated private boolean userWantBluetooth = false; private boolean userWantSpeaker = false; private boolean userWantMicrophoneMute = false; private Intent mediaStateChangedIntent; //Bluetooth related private BluetoothWrapper bluetoothWrapper; private AudioFocusWrapper audioFocusWrapper; private AccessibilityWrapper accessibilityManager; private SharedPreferences prefs; private boolean useSgsWrkAround = false; private boolean useWebRTCImpl = false; private boolean doFocusAudio = true; private static int modeSipInCall = AudioManager.MODE_NORMAL; public MediaManager(SipService aService) { service = aService; audioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE); prefs = service.getSharedPreferences("audio", Context.MODE_PRIVATE); //prefs = PreferenceManager.getDefaultSharedPreferences(service); accessibilityManager = AccessibilityWrapper.getInstance(); accessibilityManager.init(service); ringer = new Ringer(service); mediaStateChangedIntent = new Intent(SipManager.ACTION_SIP_MEDIA_CHANGED); //Try to reset if there were a crash in a call could restore previous settings restoreAudioState(); } public void startService() { if(bluetoothWrapper == null) { bluetoothWrapper = BluetoothWrapper.getInstance(); bluetoothWrapper.init(service, this); } if(audioFocusWrapper == null) { audioFocusWrapper = AudioFocusWrapper.getInstance(); audioFocusWrapper.init(service, audioManager); } modeSipInCall = service.getPrefs().getInCallMode(); useSgsWrkAround = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.USE_SGS_CALL_HACK); useWebRTCImpl = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.USE_WEBRTC_HACK); doFocusAudio = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.DO_FOCUS_AUDIO); userWantBluetooth = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.AUTO_CONNECT_BLUETOOTH); } public void stopService() { Log.i(THIS_FILE, "Remove media manager...."); if(bluetoothWrapper != null) { bluetoothWrapper.unregister(); } } private int getAudioTargetMode() { int targetMode = modeSipInCall; if(service.getPrefs().useModeApi()) { Log.d(THIS_FILE, "User want speaker now..."+userWantSpeaker); if(!service.getPrefs().generateForSetCall()) { return userWantSpeaker ? AudioManager.MODE_NORMAL : AudioManager.MODE_IN_CALL; }else { return userWantSpeaker ? AudioManager.MODE_IN_CALL: AudioManager.MODE_NORMAL ; } } if(userWantBluetooth) { targetMode = AudioManager.MODE_NORMAL; } Log.d(THIS_FILE, "Target mode... : " + targetMode); return targetMode; } public int validateAudioClockRate(int clockRate) { if(bluetoothWrapper != null && clockRate != 8000) { if(userWantBluetooth && bluetoothWrapper.canBluetooth()) { return -1; } } return 0; } public void setAudioInCall() { actualSetAudioInCall(); } public void unsetAudioInCall() { actualUnsetAudioInCall(); } /** * Set the audio mode as in call */ @SuppressWarnings("deprecation") private synchronized void actualSetAudioInCall() { //Ensure not already set if(isSetAudioMode) { return; } stopRing(); saveAudioState(); - //Set the rest of the phone in a better state to not interferate with current call - audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); - audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); - audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); + // Set the rest of the phone in a better state to not interferate with current call + // Do that only if we were not already in silent mode + if(audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) { + audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); + audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); + audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); + } //LOCKS //Wifi management if necessary ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); //Acquire wifi lock WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE); if(wifiLock == null) { wifiLock = wman.createWifiLock( (Compatibility.isCompatible(9)) ? 3 : WifiManager.WIFI_MODE_FULL, "com.csipsimple.InCallLock"); wifiLock.setReferenceCounted(false); } WifiInfo winfo = wman.getConnectionInfo(); if(winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); //We assume that if obtaining ip addr, we are almost connected so can keep wifi lock if(dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if(!wifiLock.isHeld()) { wifiLock.acquire(); } } //This wake lock purpose is to prevent PSP wifi mode if(service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) { if(screenLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); screenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.csipsimple.onIncomingCall.SCREEN"); screenLock.setReferenceCounted(false); } //Ensure single lock if(!screenLock.isHeld()) { screenLock.acquire(); } } } if(cpuLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); cpuLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.onIncomingCall.CPU"); cpuLock.setReferenceCounted(false); } if(!cpuLock.isHeld()) { cpuLock.acquire(); } if(!useWebRTCImpl) { //Audio routing int targetMode = getAudioTargetMode(); Log.d(THIS_FILE, "Set mode audio in call to "+targetMode); if(service.getPrefs().generateForSetCall()) { ToneGenerator toneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, 1); toneGenerator.startTone(41 /*ToneGenerator.TONE_CDMA_CONFIRM*/); toneGenerator.stopTone(); toneGenerator.release(); } //Set mode if(targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) { //For galaxy S we need to set in call mode before to reset stack audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setMode(targetMode); //Routing if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, userWantSpeaker?AudioManager.ROUTE_SPEAKER:AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false); } audioManager.setMicrophoneMute(false); if(bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) { Log.d(THIS_FILE, "Try to enable bluetooth"); bluetoothWrapper.setBluetoothOn(true); } }else { //WebRTC implementation for routing int apiLevel = Compatibility.getApiLevel(); //SetAudioMode // ***IMPORTANT*** When the API level for honeycomb (H) has been // decided, // the condition should be changed to include API level 8 to H-1. if ( android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) { // Set Samsung specific VoIP mode for 2.2 devices int mode = 4; audioManager.setMode(mode); if (audioManager.getMode() != mode) { Log.e(THIS_FILE, "Could not set audio mode for Samsung device"); } } //SetPlayoutSpeaker if ((3 == apiLevel) || (4 == apiLevel)) { // 1.5 and 1.6 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_NORMAL); } else { // route audio to earpiece audioManager.setMode(AudioManager.MODE_IN_CALL); } } else { // 2.x devices if ((android.os.Build.BRAND.equalsIgnoreCase("samsung")) && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) { // Samsung 2.0, 2.0.1 and 2.1 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(userWantSpeaker); } else { // route audio to earpiece audioManager.setSpeakerphoneOn(userWantSpeaker); audioManager.setMode(AudioManager.MODE_NORMAL); } } else { // Non-Samsung and Samsung 2.2 and up devices audioManager.setSpeakerphoneOn(userWantSpeaker); } } } //Set stream solo/volume/focus int inCallStream = Compatibility.getInCallStream(); if(doFocusAudio) { if(!accessibilityManager.isEnabled()) { audioManager.setStreamSolo(inCallStream, true); } audioFocusWrapper.focus(); } Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel()); setStreamVolume(inCallStream, (int) (audioManager.getStreamMaxVolume(inCallStream) * service.getPrefs().getInitialVolumeLevel()), 0); isSetAudioMode = true; // System.gc(); } /** * Save current audio mode in order to be able to restore it once done */ @SuppressWarnings("deprecation") private synchronized void saveAudioState() { if( prefs.getBoolean("isSavedAudioState", false) ) { //If we have already set, do not set it again !!! return; } ContentResolver ctntResolver = service.getContentResolver(); Editor ed = prefs.edit(); ed.putInt("savedVibrateRing", audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)); ed.putInt("savedVibradeNotif", audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION)); ed.putInt("savedRingerMode", audioManager.getRingerMode()); ed.putInt("savedWifiPolicy" , android.provider.Settings.System.getInt(ctntResolver, android.provider.Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT)); int inCallStream = Compatibility.getInCallStream(); ed.putInt("savedVolume", audioManager.getStreamVolume(inCallStream)); int targetMode = getAudioTargetMode(); if(service.getPrefs().useRoutingApi()) { ed.putInt("savedRoute", audioManager.getRouting(targetMode)); }else { ed.putBoolean("savedSpeakerPhone", audioManager.isSpeakerphoneOn()); } ed.putInt("savedMode", audioManager.getMode()); ed.putBoolean("isSavedAudioState", true); ed.commit(); } /** * Restore the state of the audio */ @SuppressWarnings("deprecation") private final synchronized void restoreAudioState() { if( !prefs.getBoolean("isSavedAudioState", false) ) { //If we have NEVER set, do not try to reset ! return; } ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, prefs.getInt("savedWifiPolicy", Settings.System.WIFI_SLEEP_POLICY_DEFAULT)); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, prefs.getInt("savedVibrateRing", AudioManager.VIBRATE_SETTING_ONLY_SILENT)); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, prefs.getInt("savedVibradeNotif", AudioManager.VIBRATE_SETTING_OFF)); audioManager.setRingerMode(prefs.getInt("savedRingerMode", AudioManager.RINGER_MODE_NORMAL)); int inCallStream = Compatibility.getInCallStream(); setStreamVolume(inCallStream, prefs.getInt("savedVolume", (int)(audioManager.getStreamMaxVolume(inCallStream)*0.8) ), 0); int targetMode = getAudioTargetMode(); if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, prefs.getInt("savedRoute", AudioManager.ROUTE_SPEAKER), AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(prefs.getBoolean("savedSpeakerPhone", false)); } audioManager.setMode(prefs.getInt("savedMode", AudioManager.MODE_NORMAL)); Editor ed = prefs.edit(); ed.putBoolean("isSavedAudioState", false); ed.commit(); } /** * Reset the audio mode */ private synchronized void actualUnsetAudioInCall() { if(!prefs.getBoolean("isSavedAudioState", false) || !isSetAudioMode) { return; } Log.d(THIS_FILE, "Unset Audio In call"); int inCallStream = Compatibility.getInCallStream(); if(bluetoothWrapper != null) { //This fixes the BT activation but... but... seems to introduce a lot of other issues //bluetoothWrapper.setBluetoothOn(true); Log.d(THIS_FILE, "Unset bt"); bluetoothWrapper.setBluetoothOn(false); } audioManager.setMicrophoneMute(false); if(doFocusAudio) { audioManager.setStreamSolo(inCallStream, false); audioFocusWrapper.unFocus(); } restoreAudioState(); if(wifiLock != null && wifiLock.isHeld()) { wifiLock.release(); } if(screenLock != null && screenLock.isHeld()) { Log.d(THIS_FILE, "Release screen lock"); screenLock.release(); } if(cpuLock != null && cpuLock.isHeld()) { cpuLock.release(); } isSetAudioMode = false; } /** * Start ringing announce for a given contact. * It will also focus audio for us. * @param remoteContact the contact to ring for. May resolve the contact ringtone if any. */ synchronized public void startRing(String remoteContact) { saveAudioState(); audioFocusWrapper.focus(); if(!ringer.isRinging()) { ringer.ring(remoteContact, service.getPrefs().getRingtone()); }else { Log.d(THIS_FILE, "Already ringing ...."); } } /** * Stop all ringing. <br/> * Warning, this will not unfocus audio. */ synchronized public void stopRing() { if(ringer.isRinging()) { ringer.stopRing(); } } /** * Stop call announcement. */ public void stopRingAndUnfocus() { stopRing(); audioFocusWrapper.unFocus(); } public void resetSettings() { userWantBluetooth = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.AUTO_CONNECT_BLUETOOTH); userWantMicrophoneMute = false; userWantSpeaker = false; } public void toggleMute() throws SameThreadException { setMicrophoneMute(!userWantMicrophoneMute); } public void setMicrophoneMute(boolean on) { if(on != userWantMicrophoneMute ) { userWantMicrophoneMute = on; setSoftwareVolume(); broadcastMediaChanged(); } } public void setSpeakerphoneOn(boolean on) throws SameThreadException { if(service != null) { service.setNoSnd(); userWantSpeaker = on; service.setSnd(); } broadcastMediaChanged(); } public void setBluetoothOn(boolean on) throws SameThreadException { Log.d(THIS_FILE, "Set BT "+on); if(service != null) { service.setNoSnd(); userWantBluetooth = on; service.setSnd(); } broadcastMediaChanged(); } public MediaState getMediaState() { MediaState mediaState = new MediaState(); // Micro mediaState.isMicrophoneMute = userWantMicrophoneMute; mediaState.canMicrophoneMute = true; /*&& !mediaState.isBluetoothScoOn*/ //Compatibility.isCompatible(5); // Speaker mediaState.isSpeakerphoneOn = userWantSpeaker; mediaState.canSpeakerphoneOn = true && !mediaState.isBluetoothScoOn; //Compatibility.isCompatible(5); //Bluetooth if(bluetoothWrapper != null) { mediaState.isBluetoothScoOn = bluetoothWrapper.isBluetoothOn(); mediaState.canBluetoothSco = bluetoothWrapper.canBluetooth(); }else { mediaState.isBluetoothScoOn = false; mediaState.canBluetoothSco = false; } return mediaState; } /** * Change the audio volume amplification according to the fact we are using bluetooth */ public void setSoftwareVolume(){ if(service != null) { final boolean useBT = (bluetoothWrapper != null && bluetoothWrapper.isBluetoothOn()); String speaker_key = useBT ? SipConfigManager.SND_BT_SPEAKER_LEVEL : SipConfigManager.SND_SPEAKER_LEVEL; String mic_key = useBT ? SipConfigManager.SND_BT_MIC_LEVEL : SipConfigManager.SND_MIC_LEVEL; final float speakVolume = service.getPrefs().getPreferenceFloatValue(speaker_key); final float micVolume = userWantMicrophoneMute? 0 : service.getPrefs().getPreferenceFloatValue(mic_key); service.getExecutor().execute(new SipRunnable() { @Override protected void doRun() throws SameThreadException { service.confAdjustTxLevel(speakVolume); service.confAdjustRxLevel(micVolume); // Force the BT mode to normal if(useBT) { audioManager.setMode(AudioManager.MODE_NORMAL); } } }); } } public void broadcastMediaChanged() { service.sendBroadcast(mediaStateChangedIntent); } private static final String ACTION_AUDIO_VOLUME_UPDATE = "org.openintents.audio.action_volume_update"; private static final String EXTRA_STREAM_TYPE = "org.openintents.audio.extra_stream_type"; private static final String EXTRA_VOLUME_INDEX = "org.openintents.audio.extra_volume_index"; private static final String EXTRA_RINGER_MODE = "org.openintents.audio.extra_ringer_mode"; private static final int EXTRA_VALUE_UNKNOWN = -9999; private void broadcastVolumeWillBeUpdated(int streamType, int index) { Intent notificationIntent = new Intent(ACTION_AUDIO_VOLUME_UPDATE); notificationIntent.putExtra(EXTRA_STREAM_TYPE, streamType); notificationIntent.putExtra(EXTRA_VOLUME_INDEX, index); notificationIntent.putExtra(EXTRA_RINGER_MODE, EXTRA_VALUE_UNKNOWN); service.sendBroadcast(notificationIntent, null); } public void setStreamVolume(int streamType, int index, int flags) { broadcastVolumeWillBeUpdated(streamType, index); audioManager.setStreamVolume(streamType, index, flags); } public void adjustStreamVolume(int streamType, int direction, int flags) { broadcastVolumeWillBeUpdated(streamType, EXTRA_VALUE_UNKNOWN); audioManager.adjustStreamVolume(streamType, direction, flags); if(streamType == AudioManager.STREAM_RING) { // Update ringer ringer.updateRingerMode(); } int inCallStream = Compatibility.getInCallStream(); if(streamType == inCallStream) { int maxLevel = audioManager.getStreamMaxVolume(inCallStream); float modifiedLevel = (audioManager.getStreamVolume(inCallStream)/(float) maxLevel)*10.0f; // Update default stream level service.getPrefs().setPreferenceFloatValue(SipConfigManager.SND_STREAM_LEVEL, modifiedLevel); } } // Public accessor public boolean isUserWantMicrophoneMute() { return userWantMicrophoneMute; } }
true
true
private synchronized void actualSetAudioInCall() { //Ensure not already set if(isSetAudioMode) { return; } stopRing(); saveAudioState(); //Set the rest of the phone in a better state to not interferate with current call audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); //LOCKS //Wifi management if necessary ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); //Acquire wifi lock WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE); if(wifiLock == null) { wifiLock = wman.createWifiLock( (Compatibility.isCompatible(9)) ? 3 : WifiManager.WIFI_MODE_FULL, "com.csipsimple.InCallLock"); wifiLock.setReferenceCounted(false); } WifiInfo winfo = wman.getConnectionInfo(); if(winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); //We assume that if obtaining ip addr, we are almost connected so can keep wifi lock if(dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if(!wifiLock.isHeld()) { wifiLock.acquire(); } } //This wake lock purpose is to prevent PSP wifi mode if(service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) { if(screenLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); screenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.csipsimple.onIncomingCall.SCREEN"); screenLock.setReferenceCounted(false); } //Ensure single lock if(!screenLock.isHeld()) { screenLock.acquire(); } } } if(cpuLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); cpuLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.onIncomingCall.CPU"); cpuLock.setReferenceCounted(false); } if(!cpuLock.isHeld()) { cpuLock.acquire(); } if(!useWebRTCImpl) { //Audio routing int targetMode = getAudioTargetMode(); Log.d(THIS_FILE, "Set mode audio in call to "+targetMode); if(service.getPrefs().generateForSetCall()) { ToneGenerator toneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, 1); toneGenerator.startTone(41 /*ToneGenerator.TONE_CDMA_CONFIRM*/); toneGenerator.stopTone(); toneGenerator.release(); } //Set mode if(targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) { //For galaxy S we need to set in call mode before to reset stack audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setMode(targetMode); //Routing if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, userWantSpeaker?AudioManager.ROUTE_SPEAKER:AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false); } audioManager.setMicrophoneMute(false); if(bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) { Log.d(THIS_FILE, "Try to enable bluetooth"); bluetoothWrapper.setBluetoothOn(true); } }else { //WebRTC implementation for routing int apiLevel = Compatibility.getApiLevel(); //SetAudioMode // ***IMPORTANT*** When the API level for honeycomb (H) has been // decided, // the condition should be changed to include API level 8 to H-1. if ( android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) { // Set Samsung specific VoIP mode for 2.2 devices int mode = 4; audioManager.setMode(mode); if (audioManager.getMode() != mode) { Log.e(THIS_FILE, "Could not set audio mode for Samsung device"); } } //SetPlayoutSpeaker if ((3 == apiLevel) || (4 == apiLevel)) { // 1.5 and 1.6 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_NORMAL); } else { // route audio to earpiece audioManager.setMode(AudioManager.MODE_IN_CALL); } } else { // 2.x devices if ((android.os.Build.BRAND.equalsIgnoreCase("samsung")) && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) { // Samsung 2.0, 2.0.1 and 2.1 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(userWantSpeaker); } else { // route audio to earpiece audioManager.setSpeakerphoneOn(userWantSpeaker); audioManager.setMode(AudioManager.MODE_NORMAL); } } else { // Non-Samsung and Samsung 2.2 and up devices audioManager.setSpeakerphoneOn(userWantSpeaker); } } } //Set stream solo/volume/focus int inCallStream = Compatibility.getInCallStream(); if(doFocusAudio) { if(!accessibilityManager.isEnabled()) { audioManager.setStreamSolo(inCallStream, true); } audioFocusWrapper.focus(); } Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel()); setStreamVolume(inCallStream, (int) (audioManager.getStreamMaxVolume(inCallStream) * service.getPrefs().getInitialVolumeLevel()), 0); isSetAudioMode = true; // System.gc(); }
private synchronized void actualSetAudioInCall() { //Ensure not already set if(isSetAudioMode) { return; } stopRing(); saveAudioState(); // Set the rest of the phone in a better state to not interferate with current call // Do that only if we were not already in silent mode if(audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); } //LOCKS //Wifi management if necessary ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); //Acquire wifi lock WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE); if(wifiLock == null) { wifiLock = wman.createWifiLock( (Compatibility.isCompatible(9)) ? 3 : WifiManager.WIFI_MODE_FULL, "com.csipsimple.InCallLock"); wifiLock.setReferenceCounted(false); } WifiInfo winfo = wman.getConnectionInfo(); if(winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); //We assume that if obtaining ip addr, we are almost connected so can keep wifi lock if(dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if(!wifiLock.isHeld()) { wifiLock.acquire(); } } //This wake lock purpose is to prevent PSP wifi mode if(service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) { if(screenLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); screenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.csipsimple.onIncomingCall.SCREEN"); screenLock.setReferenceCounted(false); } //Ensure single lock if(!screenLock.isHeld()) { screenLock.acquire(); } } } if(cpuLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); cpuLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.onIncomingCall.CPU"); cpuLock.setReferenceCounted(false); } if(!cpuLock.isHeld()) { cpuLock.acquire(); } if(!useWebRTCImpl) { //Audio routing int targetMode = getAudioTargetMode(); Log.d(THIS_FILE, "Set mode audio in call to "+targetMode); if(service.getPrefs().generateForSetCall()) { ToneGenerator toneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, 1); toneGenerator.startTone(41 /*ToneGenerator.TONE_CDMA_CONFIRM*/); toneGenerator.stopTone(); toneGenerator.release(); } //Set mode if(targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) { //For galaxy S we need to set in call mode before to reset stack audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setMode(targetMode); //Routing if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, userWantSpeaker?AudioManager.ROUTE_SPEAKER:AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false); } audioManager.setMicrophoneMute(false); if(bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) { Log.d(THIS_FILE, "Try to enable bluetooth"); bluetoothWrapper.setBluetoothOn(true); } }else { //WebRTC implementation for routing int apiLevel = Compatibility.getApiLevel(); //SetAudioMode // ***IMPORTANT*** When the API level for honeycomb (H) has been // decided, // the condition should be changed to include API level 8 to H-1. if ( android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) { // Set Samsung specific VoIP mode for 2.2 devices int mode = 4; audioManager.setMode(mode); if (audioManager.getMode() != mode) { Log.e(THIS_FILE, "Could not set audio mode for Samsung device"); } } //SetPlayoutSpeaker if ((3 == apiLevel) || (4 == apiLevel)) { // 1.5 and 1.6 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_NORMAL); } else { // route audio to earpiece audioManager.setMode(AudioManager.MODE_IN_CALL); } } else { // 2.x devices if ((android.os.Build.BRAND.equalsIgnoreCase("samsung")) && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) { // Samsung 2.0, 2.0.1 and 2.1 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(userWantSpeaker); } else { // route audio to earpiece audioManager.setSpeakerphoneOn(userWantSpeaker); audioManager.setMode(AudioManager.MODE_NORMAL); } } else { // Non-Samsung and Samsung 2.2 and up devices audioManager.setSpeakerphoneOn(userWantSpeaker); } } } //Set stream solo/volume/focus int inCallStream = Compatibility.getInCallStream(); if(doFocusAudio) { if(!accessibilityManager.isEnabled()) { audioManager.setStreamSolo(inCallStream, true); } audioFocusWrapper.focus(); } Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel()); setStreamVolume(inCallStream, (int) (audioManager.getStreamMaxVolume(inCallStream) * service.getPrefs().getInitialVolumeLevel()), 0); isSetAudioMode = true; // System.gc(); }
diff --git a/RealSleep/src/com/github/limdingwen/RealSleep/SleepEffect.java b/RealSleep/src/com/github/limdingwen/RealSleep/SleepEffect.java index 940bff8..5ea09cf 100644 --- a/RealSleep/src/com/github/limdingwen/RealSleep/SleepEffect.java +++ b/RealSleep/src/com/github/limdingwen/RealSleep/SleepEffect.java @@ -1,51 +1,51 @@ package com.github.limdingwen.RealSleep; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class SleepEffect { public static boolean refreshEffects() { // To optimize performance, we only check effects when it changes. Player[] players = Bukkit.getServer().getOnlinePlayers(); Map<String, Float> data = new HashMap<String, Float>(); Logger log = Logger.getLogger("RealSleepEffect"); try { data = (Map) SLAPI.load("RealSleepData"); } catch (Exception e) { log.warning("Cannot refresh effects! Reason: Cannot load file."); return false; } for (int i = 0; i < players.length; i++) { if (data.containsKey(players[i].getName())) { - if (data.get(players[i]) < 20) { + if (data.get(players[i].getName()) < 20) { players[i].addPotionEffects((Collection<PotionEffect>) PotionEffectType.CONFUSION); return true; } else { players[i].removePotionEffect(PotionEffectType.CONFUSION); return true; } } else { log.warning("Cannot update effect for " + players[i].getName() + "! Continued to not affect other players."); players[i].sendMessage(ChatColor.RED + "Due to an internal error your sleep effect cannot be updated!"); } } return true; } }
true
true
public static boolean refreshEffects() { // To optimize performance, we only check effects when it changes. Player[] players = Bukkit.getServer().getOnlinePlayers(); Map<String, Float> data = new HashMap<String, Float>(); Logger log = Logger.getLogger("RealSleepEffect"); try { data = (Map) SLAPI.load("RealSleepData"); } catch (Exception e) { log.warning("Cannot refresh effects! Reason: Cannot load file."); return false; } for (int i = 0; i < players.length; i++) { if (data.containsKey(players[i].getName())) { if (data.get(players[i]) < 20) { players[i].addPotionEffects((Collection<PotionEffect>) PotionEffectType.CONFUSION); return true; } else { players[i].removePotionEffect(PotionEffectType.CONFUSION); return true; } } else { log.warning("Cannot update effect for " + players[i].getName() + "! Continued to not affect other players."); players[i].sendMessage(ChatColor.RED + "Due to an internal error your sleep effect cannot be updated!"); } } return true; }
public static boolean refreshEffects() { // To optimize performance, we only check effects when it changes. Player[] players = Bukkit.getServer().getOnlinePlayers(); Map<String, Float> data = new HashMap<String, Float>(); Logger log = Logger.getLogger("RealSleepEffect"); try { data = (Map) SLAPI.load("RealSleepData"); } catch (Exception e) { log.warning("Cannot refresh effects! Reason: Cannot load file."); return false; } for (int i = 0; i < players.length; i++) { if (data.containsKey(players[i].getName())) { if (data.get(players[i].getName()) < 20) { players[i].addPotionEffects((Collection<PotionEffect>) PotionEffectType.CONFUSION); return true; } else { players[i].removePotionEffect(PotionEffectType.CONFUSION); return true; } } else { log.warning("Cannot update effect for " + players[i].getName() + "! Continued to not affect other players."); players[i].sendMessage(ChatColor.RED + "Due to an internal error your sleep effect cannot be updated!"); } } return true; }
diff --git a/modules/quercus/src/com/caucho/quercus/lib/UrlModule.java b/modules/quercus/src/com/caucho/quercus/lib/UrlModule.java index 374ebaaca..eae52e2df 100644 --- a/modules/quercus/src/com/caucho/quercus/lib/UrlModule.java +++ b/modules/quercus/src/com/caucho/quercus/lib/UrlModule.java @@ -1,1071 +1,1071 @@ /* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.lib; import com.caucho.quercus.annotation.Optional; import com.caucho.quercus.annotation.This; import com.caucho.quercus.env.ArrayValue; import com.caucho.quercus.env.ArrayValueImpl; import com.caucho.quercus.env.BooleanValue; import com.caucho.quercus.env.ConstStringValue; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.LongValue; import com.caucho.quercus.env.ObjectValue; import com.caucho.quercus.env.StringBuilderOutputStream; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.UnicodeBuilderValue; import com.caucho.quercus.env.UnsetValue; import com.caucho.quercus.env.Value; import com.caucho.quercus.lib.file.BinaryInput; import com.caucho.quercus.lib.file.BinaryStream; import com.caucho.quercus.lib.file.FileModule; import com.caucho.quercus.module.AbstractQuercusModule; import com.caucho.util.Base64; import com.caucho.util.CharBuffer; import com.caucho.util.L10N; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.URL; import java.util.Map; import java.util.Set; import java.util.logging.Logger; /** * PHP URL */ public class UrlModule extends AbstractQuercusModule { private static final L10N L = new L10N(UrlModule.class); private static final Logger log = Logger.getLogger(UrlModule.class.getName()); public static final int PHP_URL_SCHEME = 0; public static final int PHP_URL_HOST = 1; public static final int PHP_URL_PORT = 2; public static final int PHP_URL_USER = 3; public static final int PHP_URL_PASS = 4; public static final int PHP_URL_PATH = 5; public static final int PHP_URL_QUERY = 6; public static final int PHP_URL_FRAGMENT = 7; private static final StringValue SCHEME_V = new ConstStringValue("scheme"); private static final StringValue SCHEME_U = new UnicodeBuilderValue("scheme"); private static final StringValue USER_V = new ConstStringValue("user"); private static final StringValue USER_U = new UnicodeBuilderValue("user"); private static final StringValue PASS_V = new ConstStringValue("pass"); private static final StringValue PASS_U = new UnicodeBuilderValue("pass"); private static final StringValue HOST_V = new ConstStringValue("host"); private static final StringValue HOST_U = new UnicodeBuilderValue("host"); private static final StringValue PORT_V = new ConstStringValue("port"); private static final StringValue PORT_U = new UnicodeBuilderValue("port"); private static final StringValue PATH_V = new ConstStringValue("path"); private static final StringValue PATH_U = new UnicodeBuilderValue("path"); private static final StringValue QUERY_V = new ConstStringValue("query"); private static final StringValue QUERY_U = new UnicodeBuilderValue("query"); private static final StringValue FRAGMENT_V = new ConstStringValue("fragment"); private static final StringValue FRAGMENT_U = new UnicodeBuilderValue("fragment"); /** * Encodes base64 */ public static String base64_encode(StringValue s) { CharBuffer cb = new CharBuffer(); byte []buffer = new byte[3]; int strlen = s.length(); int offset = 0; for (; offset + 3 <= strlen; offset += 3) { buffer[0] = (byte) s.charAt(offset); buffer[1] = (byte) s.charAt(offset + 1); buffer[2] = (byte) s.charAt(offset + 2); Base64.encode(cb, buffer, 0, 3); } if (offset < strlen) buffer[0] = (byte) s.charAt(offset); if (offset + 1 < strlen) buffer[1] = (byte) s.charAt(offset + 1); if (offset + 2 < strlen) buffer[2] = (byte) s.charAt(offset + 2); Base64.encode(cb, buffer, 0, strlen - offset); return cb.toString(); } /** * Decodes base64 */ public static Value base64_decode(Env env, StringValue str, @Optional boolean isStrict) { if (str.length() == 0) return str; StringValue sb = env.createBinaryBuilder(); OutputStream os = new StringBuilderOutputStream(sb); try { Base64.decodeIgnoreWhitespace(str.toSimpleReader(), os); } catch (IOException e) { env.warning(e); return BooleanValue.FALSE; } return sb; } /** * Connects to the given URL using a HEAD request to retreive * the headers sent in the response. */ public static Value get_headers(Env env, String urlString, @Optional Value format) { Socket socket = null; try { URL url = new URL(urlString); if (! url.getProtocol().equals("http") && ! url.getProtocol().equals("https")) { env.warning(L.l("Not an HTTP URL")); return null; } int port = 80; if (url.getPort() < 0) { if (url.getProtocol().equals("http")) port = 80; else if (url.getProtocol().equals("https")) port = 443; } else { port = url.getPort(); } socket = new Socket(url.getHost(), port); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); StringBuilder request = new StringBuilder(); request.append("HEAD "); if (url.getPath() != null) request.append(url.getPath()); if (url.getQuery() != null) request.append("?" + url.getQuery()); if (url.getRef() != null) request.append("#" + url.getRef()); request.append(" HTTP/1.0\r\n"); if (url.getHost() != null) request.append("Host: " + url.getHost() + "\r\n"); request.append("\r\n"); OutputStreamWriter writer = new OutputStreamWriter(out); writer.write(request.toString()); writer.flush(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(in)); ArrayValue result = new ArrayValueImpl(); if (format.toBoolean()) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); if (line.length() == 0) continue; int colon = line.indexOf(':'); ArrayValue values; if (colon < 0) result.put(env.createString(line.trim())); else { StringValue key = env.createString(line.substring(0, colon).trim()); StringValue value; if (colon < line.length()) value = env.createString(line.substring(colon + 1).trim()); else value = env.getEmptyString(); if (result.get(key) != UnsetValue.UNSET) values = (ArrayValue)result.get(key); else { values = new ArrayValueImpl(); result.put(key, values); } values.put(value); } } // collapse single entries for (Value key : result.keySet()) { Value value = result.get(key); if (value.isArray() && ((ArrayValue)value).getSize() == 1) result.put(key, ((ArrayValue)value).get(LongValue.ZERO)); } } else { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); if (line.length() == 0) continue; result.put(env.createString(line.trim())); } } return result; } catch (Exception e) { env.warning(e); return BooleanValue.FALSE; } finally { try { if (socket != null) socket.close(); } catch (IOException e) { env.warning(e); } } } /** * Extracts the meta tags from a file and returns them as an array. */ public static Value get_meta_tags(Env env, StringValue filename, @Optional boolean useIncludePath) { InputStream in = null; ArrayValue result = new ArrayValueImpl(); try { BinaryStream stream = FileModule.fopen(env, filename, "r", useIncludePath, null); if (stream == null || ! (stream instanceof BinaryInput)) return result; BinaryInput input = (BinaryInput) stream; while (! input.isEOF()) { String tag = getNextTag(input); if (tag.equalsIgnoreCase("meta")) { String name = null; String content = null; String [] attr; while ((attr = getNextAttribute(input)) != null) { if (name == null && attr[0].equalsIgnoreCase("name")) { if (attr.length > 1) name = attr[1]; } else if (content == null && attr[0].equalsIgnoreCase("content")) { if (attr.length > 1) content = attr[1]; } if (name != null && content != null) { result.put(env.createString(name), env.createString(content)); break; } } } else if (tag.equalsIgnoreCase("/head")) break; } } catch (IOException e) { env.warning(e); } finally { try { if (in != null) in.close(); } catch (IOException e) { env.warning(e); } } return result; } public static Value http_build_query(Env env, Value formdata, @Optional StringValue numeric_prefix, @Optional("'&'") StringValue separator) { StringValue result = env.createUnicodeBuilder(); httpBuildQueryImpl(env, result, formdata, env.getEmptyString(), numeric_prefix, separator); return result; } private static void httpBuildQueryImpl(Env env, StringValue result, Value formdata, StringValue path, StringValue numeric_prefix, StringValue separator) { Set<? extends Map.Entry<Value,Value>> entrySet; if (formdata.isArray()) { entrySet = ((ArrayValue) formdata).entrySet(); } else if (formdata.isObject()) { entrySet = ((ObjectValue) formdata).entrySet(); } else { env.warning(L.l("formdata must be an array or object")); return; } boolean isFirst = true; for (Map.Entry<Value,Value> entry : entrySet) { if (! isFirst) { if (separator != null) result.append(separator); else result.append("&"); } isFirst = false; StringValue newPath = makeNewPath(path, entry.getKey(), numeric_prefix); Value entryValue = entry.getValue(); if (entryValue.isArray() || entryValue.isObject()) { // can always throw away the numeric prefix on recursive calls httpBuildQueryImpl(env, result, entryValue, newPath, null, separator); } else { result.append(newPath); result.append("="); result.append(urlencode(entry.getValue().toStringValue())); } } } private static StringValue makeNewPath(StringValue oldPath, Value key, StringValue numeric_prefix) { StringValue path = oldPath.createStringBuilder(); if (oldPath.length() != 0) { path.append(oldPath); //path.append('['); path.append("%5B"); urlencode(path, key.toStringValue()); //path.append(']'); path.append("%5D"); return path; } else if (key.isLongConvertible() && numeric_prefix != null) { urlencode(path, numeric_prefix); urlencode(path, key.toStringValue()); return path; } else { urlencode(path, key.toStringValue()); return path; } } /** * Creates a http string. */ /* public String http_build_query(Value value, @Optional String prefix) { StringBuilder sb = new StringBuilder(); int index = 0; if (value instanceof ArrayValue) { ArrayValue array = (ArrayValue) value; for (Map.Entry<Value,Value> entry : array.entrySet()) { Value keyValue = entry.getKey(); Value v = entry.getValue(); String key; if (keyValue.isLongConvertible()) key = prefix + keyValue; else key = keyValue.toString(); if (v instanceof ArrayValue) http_build_query(sb, key, (ArrayValue) v); else { if (sb.length() > 0) sb.append('&'); sb.append(key); sb.append('='); urlencode(sb, v.toString()); } } } return sb.toString(); } */ /** * Creates a http string. */ /* private void http_build_query(StringBuilder sb, String prefix, ArrayValue array) { for (Map.Entry<Value,Value> entry : array.entrySet()) { Value keyValue = entry.getKey(); Value v = entry.getValue(); String key = prefix + '[' + keyValue + ']'; if (v instanceof ArrayValue) http_build_query(sb, key, (ArrayValue) v); else { if (sb.length() > 0) sb.append('&'); sb.append(key); sb.append('='); urlencode(sb, v.toString()); } } } */ /** * Parses the URL into an array. */ public static Value parse_url(Env env, StringValue str, @Optional("-1") int component) { boolean isUnicode = env.isUnicodeSemantics(); ArrayValueImpl array = new ArrayValueImpl(); parseUrl(env, str, array, isUnicode); switch (component) { case PHP_URL_SCHEME: return array.get(isUnicode ? SCHEME_U : SCHEME_V); case PHP_URL_HOST: return array.get(isUnicode ? HOST_U : HOST_V); case PHP_URL_PORT: return array.get(isUnicode ? PORT_U : PORT_V); case PHP_URL_USER: return array.get(isUnicode ? USER_U : USER_V); case PHP_URL_PASS: return array.get(isUnicode ? PASS_U : PASS_V); case PHP_URL_PATH: return array.get(isUnicode ? PATH_U : PATH_V); case PHP_URL_QUERY: return array.get(isUnicode ? QUERY_U : QUERY_V); case PHP_URL_FRAGMENT: return array.get(isUnicode ? FRAGMENT_U : FRAGMENT_V); } return array; } private static void parseUrl(Env env, StringValue str, ArrayValue array, boolean isUnicode) { int strlen = str.length(); if (strlen == 0) { array.put(PATH_V, PATH_U, env.getEmptyString(), isUnicode); return; } int i = 0; char ch; int colon = str.indexOf(":"); boolean hasHost = false; if (0 <= colon) { int end = colon; if (colon + 1 < strlen && str.charAt(colon + 1) == '/') { if (colon + 2 < strlen && str.charAt(colon + 2) == '/') { end = colon + 2; if (colon + 3 < strlen && str.charAt(colon + 3) == '/') { } else { hasHost = true; } } StringValue sb = env.createStringBuilder(); sb.append(str, 0, colon); array.put(SCHEME_V, SCHEME_U, sb, isUnicode); i = end + 1; } else if (colon + 1 == strlen || (ch = str.charAt(colon + 1)) <= '0' || '9' <= ch) { StringValue sb = env.createStringBuilder(); sb.append(str, 0, colon); array.put(SCHEME_V, SCHEME_U, sb, isUnicode); i = colon + 1; } else { hasHost = true; } } colon = str.indexOf(':', i); int question = str.indexOf('?', i); int pound = str.indexOf('#', i); int atSign = str.lastIndexOf('@'); StringValue user = null; StringValue pass = null; // username:password - if (0 <= atSign && atSign < question && hasHost) { + if (0 <= atSign && (question < 0 || atSign < question) && hasHost) { if (0 <= colon && colon < atSign) { if (i < colon) { user = env.createStringBuilder(); user.append(str, i, colon); } if (colon + 1 < atSign) { pass = env.createStringBuilder(); pass.append(str, colon + 1, atSign); } i = atSign + 1; colon = str.indexOf(':', i); } else { user = env.createStringBuilder(); user.append(str, i, atSign); i = atSign + 1; } } if (0 <= i && hasHost) { int slash = str.indexOf('/', i); if (i < colon) { StringValue sb = env.createStringBuilder(); sb.append(str, i, colon); array.put(HOST_V, HOST_U, sb, isUnicode); int end; if (i < slash) end = slash; else if (i < question) end = question + 1; else if (i < pound) end = pound + 1; else end = strlen; if (0 < end - (colon + 1)) { int port = 0; for (int j = colon + 1; j < end; j++) { ch = str.charAt(j); if ('0' <= ch && ch <= '9') port = port * 10 + ch - '0'; else break; } array.put(PORT_V, PORT_U, LongValue.create(port), isUnicode); } i = end; } else if (i < question && (slash < i || question < slash)) { StringValue sb = env.createStringBuilder(); sb.append(str, i, question); array.put(HOST_V, HOST_U, sb, isUnicode); i = question + 1; } else if (i < slash) { StringValue sb = env.createStringBuilder(); sb.append(str, i, slash); array.put(HOST_V, HOST_U, sb, isUnicode); i = slash; } else if (i < pound) { StringValue sb = env.createStringBuilder(); sb.append(str, i, pound); array.put(HOST_V, HOST_U, sb, isUnicode); i = pound + 1; } else { StringValue sb = env.createStringBuilder(); sb.append(str, i, strlen); array.put(HOST_V, HOST_U, sb, isUnicode); i = strlen; } } // insert user and password after port if (user != null) array.put(USER_V, USER_U, user, isUnicode); if (pass != null) array.put(PASS_V, PASS_U, pass, isUnicode); if (i < question) { StringValue sb = env.createStringBuilder(); sb.append(str, i, question); array.put(PATH_V, PATH_U, sb, isUnicode); i = question + 1; } if (0 <= pound) { if (i < pound) { StringValue sb = env.createStringBuilder(); sb.append(str, i, pound); if (0 <= question) array.put(QUERY_V, QUERY_U, sb, isUnicode); else array.put(PATH_V, PATH_U, sb, isUnicode); } if (pound + 1 < strlen) { StringValue sb = env.createStringBuilder(); sb.append(str, pound + 1, strlen); array.put(FRAGMENT_V, FRAGMENT_U, sb, isUnicode); } } else if (i < strlen) { StringValue sb = env.createStringBuilder(); sb.append(str, i, strlen); if (0 <= question) array.put(QUERY_V, QUERY_U, sb, isUnicode); else array.put(PATH_V, PATH_U, sb, isUnicode); } } /** * Returns the decoded string. */ public static String rawurldecode(String s) { if (s == null) return ""; int len = s.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { char ch = s.charAt(i); if (ch == '%' && i + 2 < len) { int d1 = s.charAt(i + 1); int d2 = s.charAt(i + 2); int v = 0; if ('0' <= d1 && d1 <= '9') v = 16 * (d1 - '0'); else if ('a' <= d1 && d1 <= 'f') v = 16 * (d1 - 'a' + 10); else if ('A' <= d1 && d1 <= 'F') v = 16 * (d1 - 'A' + 10); else { sb.append('%'); continue; } if ('0' <= d2 && d2 <= '9') v += (d2 - '0'); else if ('a' <= d2 && d2 <= 'f') v += (d2 - 'a' + 10); else if ('A' <= d2 && d2 <= 'F') v += (d2 - 'A' + 10); else { sb.append('%'); continue; } i += 2; sb.append((char) v); } else sb.append(ch); } return sb.toString(); } /** * Encodes the url */ public static String rawurlencode(String str) { if (str == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '0' <= ch && ch <= '9' || ch == '-' || ch == '_' || ch == '.' || ch == '~') { sb.append(ch); } else { sb.append('%'); sb.append(toHexDigit(ch >> 4)); sb.append(toHexDigit(ch)); } } return sb.toString(); } enum ParseUrlState { INIT, USER, PASS, HOST, PORT, PATH, QUERY, FRAGMENT }; /** * Gets the magic quotes value. */ public static StringValue urlencode(StringValue str) { StringValue sb = str.createStringBuilder(); urlencode(sb, str); return sb; } /** * Gets the magic quotes value. */ private static void urlencode(StringValue sb, StringValue str) { int len = str.length(); for (int i = 0; i < len; i++) { char ch = str.charAt(i); if ('a' <= ch && ch <= 'z') sb.append(ch); else if ('A' <= ch && ch <= 'Z') sb.append(ch); else if ('0' <= ch && ch <= '9') sb.append(ch); else if (ch == '-' || ch == '_' || ch == '.') sb.append(ch); else if (ch == ' ') sb.append('+'); else { sb.append('%'); sb.append(toHexDigit(ch / 16)); sb.append(toHexDigit(ch)); } } } /** * Returns the decoded string. */ public static String urldecode(String s) { if (s == null) return ""; int len = s.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { char ch = s.charAt(i); if (ch == '%' && i + 2 < len) { int d1 = s.charAt(i + 1); int d2 = s.charAt(i + 2); int v = 0; if ('0' <= d1 && d1 <= '9') v = 16 * (d1 - '0'); else if ('a' <= d1 && d1 <= 'f') v = 16 * (d1 - 'a' + 10); else if ('A' <= d1 && d1 <= 'F') v = 16 * (d1 - 'A' + 10); else { sb.append('%'); continue; } if ('0' <= d2 && d2 <= '9') v += (d2 - '0'); else if ('a' <= d2 && d2 <= 'f') v += (d2 - 'a' + 10); else if ('A' <= d2 && d2 <= 'F') v += (d2 - 'A' + 10); else { sb.append('%'); continue; } i += 2; sb.append((char) v); } else if (ch == '+') sb.append(' '); else sb.append(ch); } return sb.toString(); } private static String getNextTag(BinaryInput input) throws IOException { StringBuilder tag = new StringBuilder(); for (int ch = 0; ! input.isEOF() && ch != '<'; ch = input.read()) { // intentionally left empty } while (! input.isEOF()) { int ch = input.read(); if (Character.isWhitespace(ch)) break; tag.append((char) ch); } return tag.toString(); } /** * Finds the next attribute in the stream and return the key and value * as an array. */ private static String [] getNextAttribute(BinaryInput input) throws IOException { int ch; consumeWhiteSpace(input); StringBuilder attribute = new StringBuilder(); while (! input.isEOF()) { ch = input.read(); if (isValidAttributeCharacter(ch)) attribute.append((char) ch); else { input.unread(); break; } } if (attribute.length() == 0) return null; consumeWhiteSpace(input); if (input.isEOF()) return new String[] { attribute.toString() }; ch = input.read(); if (ch != '=') { input.unread(); return new String[] { attribute.toString() }; } consumeWhiteSpace(input); // check for quoting int quote = ' '; boolean quoted = false; if (input.isEOF()) return new String[] { attribute.toString() }; ch = input.read(); if (ch == '"' || ch == '\'') { quoted = true; quote = ch; } else input.unread(); StringBuilder value = new StringBuilder(); while (! input.isEOF()) { ch = input.read(); // mimics PHP behavior if ((quoted && ch == quote) || (! quoted && Character.isWhitespace(ch)) || ch == '>') break; value.append((char) ch); } return new String[] { attribute.toString(), value.toString() }; } private static void consumeWhiteSpace(BinaryInput input) throws IOException { int ch = 0; while (! input.isEOF() && Character.isWhitespace(ch = input.read())) { // intentionally left empty } if (! Character.isWhitespace(ch)) input.unread(); } private static boolean isValidAttributeCharacter(int ch) { return Character.isLetterOrDigit(ch) || (ch == '-') || (ch == '.') || (ch == '_') || (ch == ':'); } private static char toHexDigit(int d) { d = d & 0xf; if (d < 10) return (char) ('0' + d); else return (char) ('A' + d - 10); } }
true
true
private static void parseUrl(Env env, StringValue str, ArrayValue array, boolean isUnicode) { int strlen = str.length(); if (strlen == 0) { array.put(PATH_V, PATH_U, env.getEmptyString(), isUnicode); return; } int i = 0; char ch; int colon = str.indexOf(":"); boolean hasHost = false; if (0 <= colon) { int end = colon; if (colon + 1 < strlen && str.charAt(colon + 1) == '/') { if (colon + 2 < strlen && str.charAt(colon + 2) == '/') { end = colon + 2; if (colon + 3 < strlen && str.charAt(colon + 3) == '/') { } else { hasHost = true; } } StringValue sb = env.createStringBuilder(); sb.append(str, 0, colon); array.put(SCHEME_V, SCHEME_U, sb, isUnicode); i = end + 1; } else if (colon + 1 == strlen || (ch = str.charAt(colon + 1)) <= '0' || '9' <= ch) { StringValue sb = env.createStringBuilder(); sb.append(str, 0, colon); array.put(SCHEME_V, SCHEME_U, sb, isUnicode); i = colon + 1; } else { hasHost = true; } } colon = str.indexOf(':', i); int question = str.indexOf('?', i); int pound = str.indexOf('#', i); int atSign = str.lastIndexOf('@'); StringValue user = null; StringValue pass = null; // username:password if (0 <= atSign && atSign < question && hasHost) { if (0 <= colon && colon < atSign) { if (i < colon) { user = env.createStringBuilder(); user.append(str, i, colon); } if (colon + 1 < atSign) { pass = env.createStringBuilder(); pass.append(str, colon + 1, atSign); } i = atSign + 1; colon = str.indexOf(':', i); } else { user = env.createStringBuilder(); user.append(str, i, atSign); i = atSign + 1; } } if (0 <= i && hasHost) { int slash = str.indexOf('/', i); if (i < colon) { StringValue sb = env.createStringBuilder(); sb.append(str, i, colon); array.put(HOST_V, HOST_U, sb, isUnicode); int end; if (i < slash) end = slash; else if (i < question) end = question + 1; else if (i < pound) end = pound + 1; else end = strlen; if (0 < end - (colon + 1)) { int port = 0; for (int j = colon + 1; j < end; j++) { ch = str.charAt(j); if ('0' <= ch && ch <= '9') port = port * 10 + ch - '0'; else break; } array.put(PORT_V, PORT_U, LongValue.create(port), isUnicode); } i = end; } else if (i < question && (slash < i || question < slash)) { StringValue sb = env.createStringBuilder(); sb.append(str, i, question); array.put(HOST_V, HOST_U, sb, isUnicode); i = question + 1; } else if (i < slash) { StringValue sb = env.createStringBuilder(); sb.append(str, i, slash); array.put(HOST_V, HOST_U, sb, isUnicode); i = slash; } else if (i < pound) { StringValue sb = env.createStringBuilder(); sb.append(str, i, pound); array.put(HOST_V, HOST_U, sb, isUnicode); i = pound + 1; } else { StringValue sb = env.createStringBuilder(); sb.append(str, i, strlen); array.put(HOST_V, HOST_U, sb, isUnicode); i = strlen; } } // insert user and password after port if (user != null) array.put(USER_V, USER_U, user, isUnicode); if (pass != null) array.put(PASS_V, PASS_U, pass, isUnicode); if (i < question) { StringValue sb = env.createStringBuilder(); sb.append(str, i, question); array.put(PATH_V, PATH_U, sb, isUnicode); i = question + 1; } if (0 <= pound) { if (i < pound) { StringValue sb = env.createStringBuilder(); sb.append(str, i, pound); if (0 <= question) array.put(QUERY_V, QUERY_U, sb, isUnicode); else array.put(PATH_V, PATH_U, sb, isUnicode); } if (pound + 1 < strlen) { StringValue sb = env.createStringBuilder(); sb.append(str, pound + 1, strlen); array.put(FRAGMENT_V, FRAGMENT_U, sb, isUnicode); } } else if (i < strlen) { StringValue sb = env.createStringBuilder(); sb.append(str, i, strlen); if (0 <= question) array.put(QUERY_V, QUERY_U, sb, isUnicode); else array.put(PATH_V, PATH_U, sb, isUnicode); } }
private static void parseUrl(Env env, StringValue str, ArrayValue array, boolean isUnicode) { int strlen = str.length(); if (strlen == 0) { array.put(PATH_V, PATH_U, env.getEmptyString(), isUnicode); return; } int i = 0; char ch; int colon = str.indexOf(":"); boolean hasHost = false; if (0 <= colon) { int end = colon; if (colon + 1 < strlen && str.charAt(colon + 1) == '/') { if (colon + 2 < strlen && str.charAt(colon + 2) == '/') { end = colon + 2; if (colon + 3 < strlen && str.charAt(colon + 3) == '/') { } else { hasHost = true; } } StringValue sb = env.createStringBuilder(); sb.append(str, 0, colon); array.put(SCHEME_V, SCHEME_U, sb, isUnicode); i = end + 1; } else if (colon + 1 == strlen || (ch = str.charAt(colon + 1)) <= '0' || '9' <= ch) { StringValue sb = env.createStringBuilder(); sb.append(str, 0, colon); array.put(SCHEME_V, SCHEME_U, sb, isUnicode); i = colon + 1; } else { hasHost = true; } } colon = str.indexOf(':', i); int question = str.indexOf('?', i); int pound = str.indexOf('#', i); int atSign = str.lastIndexOf('@'); StringValue user = null; StringValue pass = null; // username:password if (0 <= atSign && (question < 0 || atSign < question) && hasHost) { if (0 <= colon && colon < atSign) { if (i < colon) { user = env.createStringBuilder(); user.append(str, i, colon); } if (colon + 1 < atSign) { pass = env.createStringBuilder(); pass.append(str, colon + 1, atSign); } i = atSign + 1; colon = str.indexOf(':', i); } else { user = env.createStringBuilder(); user.append(str, i, atSign); i = atSign + 1; } } if (0 <= i && hasHost) { int slash = str.indexOf('/', i); if (i < colon) { StringValue sb = env.createStringBuilder(); sb.append(str, i, colon); array.put(HOST_V, HOST_U, sb, isUnicode); int end; if (i < slash) end = slash; else if (i < question) end = question + 1; else if (i < pound) end = pound + 1; else end = strlen; if (0 < end - (colon + 1)) { int port = 0; for (int j = colon + 1; j < end; j++) { ch = str.charAt(j); if ('0' <= ch && ch <= '9') port = port * 10 + ch - '0'; else break; } array.put(PORT_V, PORT_U, LongValue.create(port), isUnicode); } i = end; } else if (i < question && (slash < i || question < slash)) { StringValue sb = env.createStringBuilder(); sb.append(str, i, question); array.put(HOST_V, HOST_U, sb, isUnicode); i = question + 1; } else if (i < slash) { StringValue sb = env.createStringBuilder(); sb.append(str, i, slash); array.put(HOST_V, HOST_U, sb, isUnicode); i = slash; } else if (i < pound) { StringValue sb = env.createStringBuilder(); sb.append(str, i, pound); array.put(HOST_V, HOST_U, sb, isUnicode); i = pound + 1; } else { StringValue sb = env.createStringBuilder(); sb.append(str, i, strlen); array.put(HOST_V, HOST_U, sb, isUnicode); i = strlen; } } // insert user and password after port if (user != null) array.put(USER_V, USER_U, user, isUnicode); if (pass != null) array.put(PASS_V, PASS_U, pass, isUnicode); if (i < question) { StringValue sb = env.createStringBuilder(); sb.append(str, i, question); array.put(PATH_V, PATH_U, sb, isUnicode); i = question + 1; } if (0 <= pound) { if (i < pound) { StringValue sb = env.createStringBuilder(); sb.append(str, i, pound); if (0 <= question) array.put(QUERY_V, QUERY_U, sb, isUnicode); else array.put(PATH_V, PATH_U, sb, isUnicode); } if (pound + 1 < strlen) { StringValue sb = env.createStringBuilder(); sb.append(str, pound + 1, strlen); array.put(FRAGMENT_V, FRAGMENT_U, sb, isUnicode); } } else if (i < strlen) { StringValue sb = env.createStringBuilder(); sb.append(str, i, strlen); if (0 <= question) array.put(QUERY_V, QUERY_U, sb, isUnicode); else array.put(PATH_V, PATH_U, sb, isUnicode); } }
diff --git a/tiles-freemarker/src/main/java/org/apache/tiles/freemarker/context/FreeMarkerUtil.java b/tiles-freemarker/src/main/java/org/apache/tiles/freemarker/context/FreeMarkerUtil.java index 1f04294a..af660d7f 100644 --- a/tiles-freemarker/src/main/java/org/apache/tiles/freemarker/context/FreeMarkerUtil.java +++ b/tiles-freemarker/src/main/java/org/apache/tiles/freemarker/context/FreeMarkerUtil.java @@ -1,331 +1,331 @@ /* * $Id$ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tiles.freemarker.context; import java.io.IOException; import java.io.StringWriter; import java.util.Stack; import javax.servlet.http.HttpServletRequest; import org.apache.tiles.TilesContainer; import org.apache.tiles.access.TilesAccess; import org.apache.tiles.freemarker.FreeMarkerTilesException; import org.apache.tiles.freemarker.io.NullWriter; import org.apache.tiles.impl.NoSuchContainerException; import org.apache.tiles.servlet.context.ServletUtil; import freemarker.core.Environment; import freemarker.ext.servlet.FreemarkerServlet; import freemarker.ext.servlet.HttpRequestHashModel; import freemarker.ext.servlet.ServletContextHashModel; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.utility.DeepUnwrap; /** * Utilities for FreeMarker usage in Tiles. * * @version $Rev$ $Date$ * @since 2.2.0 */ public class FreeMarkerUtil { /** * The name of the attribute that holds the compose stack. */ public static final String COMPOSE_STACK_ATTRIBUTE_NAME = "org.apache.tiles.template.COMPOSE_STACK"; /** * Private constructor to avoid instantiation. */ private FreeMarkerUtil() { } /** * Returns true if forced include of the result is needed. * * @param env The current FreeMarker environment. * @return If <code>true</code> the include operation must be forced. * @since 2.2.0 */ public static boolean isForceInclude(Environment env) { return ServletUtil .isForceInclude(getRequestHashModel(env).getRequest()); } /** * Sets the option that enables the forced include of the response. * * @param env The current FreeMarker environment. * @param forceInclude If <code>true</code> the include operation must be * forced. * @since 2.2.0 */ public static void setForceInclude(Environment env, boolean forceInclude) { ServletUtil.setForceInclude(getRequestHashModel(env).getRequest(), forceInclude); } /** * Returns a specific Tiles container. * * @param env The current FreeMarker environment. * @param key The key under which the container is stored. If null, the * default container will be returned. * @return The requested Tiles container. * @since 2.2.0 */ public static TilesContainer getContainer(Environment env, String key) { if (key == null) { key = TilesAccess.CONTAINER_ATTRIBUTE; } return (TilesContainer) getServletContextHashModel(env).getServlet() .getServletContext().getAttribute(key); } /** * Sets the current container to use in web pages. * * @param env The current FreeMarker environment. * @param key The key under which the container is stored. * @since 2.2.0 */ public static void setCurrentContainer(Environment env, String key) { TilesContainer container = getContainer(env, key); if (container != null) { getRequestHashModel(env).getRequest().setAttribute( ServletUtil.CURRENT_CONTAINER_ATTRIBUTE_NAME, container); } else { throw new NoSuchContainerException("The container with the key '" + key + "' cannot be found"); } } /** * Sets the current container to use in web pages. * * @param env The current FreeMarker environment. * @param container The container to use as the current container. * @since 2.2.0 */ public static void setCurrentContainer(Environment env, TilesContainer container) { ServletUtil.setCurrentContainer(getRequestHashModel(env).getRequest(), getServletContextHashModel(env).getServlet() .getServletContext(), container); } /** * Returns the current container that has been set, or the default one. * * @param env The current FreeMarker environment. * @return The current Tiles container to use in web pages. * @since 2.2.0 */ public static TilesContainer getCurrentContainer(Environment env) { return ServletUtil.getCurrentContainer(getRequestHashModel(env) .getRequest(), getServletContextHashModel(env).getServlet() .getServletContext()); } /** * Returns the HTTP request hash model. * * @param env The current FreeMarker environment. * @return The request hash model. * @since 2.2.0 */ public static HttpRequestHashModel getRequestHashModel(Environment env) { try { return (HttpRequestHashModel) env.getDataModel().get( FreemarkerServlet.KEY_REQUEST); } catch (TemplateModelException e) { throw new FreeMarkerTilesException( "Exception got when obtaining the request hash model", e); } } /** * Returns the servlet context hash model. * * @param env The current FreeMarker environment. * @return The servlet context hash model. * @since 2.2.0 */ public static ServletContextHashModel getServletContextHashModel( Environment env) { try { return (ServletContextHashModel) env.getDataModel().get( FreemarkerServlet.KEY_APPLICATION); } catch (TemplateModelException e) { throw new FreeMarkerTilesException( "Exception got when obtaining the application hash model", e); } } /** * Unwraps a TemplateModel to extract a string. * * @param model The TemplateModel to unwrap. * @return The unwrapped string. * @since 2.2.0 */ public static String getAsString(TemplateModel model) { try { return (String) DeepUnwrap.unwrap(model); } catch (TemplateModelException e) { throw new FreeMarkerTilesException("Cannot unwrap a model", e); } } /** * Unwraps a TemplateModel to extract a boolean. * * @param model The TemplateModel to unwrap. * @param defaultValue If the value is null, this value will be returned. * @return The unwrapped boolean. * @since 2.2.0 */ public static boolean getAsBoolean(TemplateModel model, boolean defaultValue) { try { Boolean retValue = (Boolean) DeepUnwrap.unwrap(model); return retValue != null ? retValue : defaultValue; } catch (TemplateModelException e) { throw new FreeMarkerTilesException("Cannot unwrap a model", e); } } /** * Unwraps a TemplateModel to extract an object. * * @param model The TemplateModel to unwrap. * @return The unwrapped object. * @since 2.2.0 */ public static Object getAsObject(TemplateModel model) { try { return DeepUnwrap.unwrap(model); } catch (TemplateModelException e) { throw new FreeMarkerTilesException("Cannot unwrap a model", e); } } /** * Sets an attribute in the desired scope. * * @param env The FreeMarker current environment. * @param name The name of the attribute. * @param obj The value of the attribute. * @param scope The scope. It can be <code>page</code>, <code>request</code>, <code>session</code>, <code>application</code>. * @since 2.2.0 */ public static void setAttribute(Environment env, String name, Object obj, String scope) { if (scope == null) { scope = "page"; } if ("page".equals(scope)) { try { TemplateModel model = env.getObjectWrapper().wrap(obj); env.setVariable(name, model); } catch (TemplateModelException e) { throw new FreeMarkerTilesException( "Error when wrapping an object", e); } } else if ("request".equals(scope)) { getRequestHashModel(env).getRequest().setAttribute(name, obj); } else if ("session".equals(scope)) { getRequestHashModel(env).getRequest().getSession().setAttribute( name, obj); - } else if ("application".equals("scope")) { + } else if ("application".equals(scope)) { getServletContextHashModel(env).getServlet().getServletContext() .setAttribute(name, obj); } } /** * Returns the current compose stack, or creates a new one if not present. * * @param env The current FreeMarker environment. * @return The compose stack. * @since 2.2.0 */ @SuppressWarnings("unchecked") public static Stack<Object> getComposeStack(Environment env) { HttpServletRequest request = getRequestHashModel(env).getRequest(); Stack<Object> composeStack = (Stack<Object>) request .getAttribute(COMPOSE_STACK_ATTRIBUTE_NAME); if (composeStack == null) { composeStack = new Stack<Object>(); request.setAttribute(COMPOSE_STACK_ATTRIBUTE_NAME, composeStack); } return composeStack; } /** * Evaluates the body without rendering it. * * @param body The body to evaluate. * @throws TemplateException If something goes wrong during evaluation. * @throws IOException If something goes wrong during writing the result. * @since 2.2.0 */ public static void evaluateBody(TemplateDirectiveBody body) throws TemplateException, IOException { if (body != null) { NullWriter writer = new NullWriter(); try { body.render(writer); } finally { writer.close(); } } } /** * Renders the body as a string. * * @param body The body to render. * @return The rendered string. * @throws TemplateException If something goes wrong during evaluation. * @throws IOException If something goes wrong during writing the result. * @since 2.2.0 */ public static String renderAsString(TemplateDirectiveBody body) throws TemplateException, IOException { String bodyString = null; if (body != null) { StringWriter stringWriter = new StringWriter(); try { body.render(stringWriter); } finally { stringWriter.close(); } bodyString = stringWriter.toString(); } return bodyString; } }
true
true
public static void setAttribute(Environment env, String name, Object obj, String scope) { if (scope == null) { scope = "page"; } if ("page".equals(scope)) { try { TemplateModel model = env.getObjectWrapper().wrap(obj); env.setVariable(name, model); } catch (TemplateModelException e) { throw new FreeMarkerTilesException( "Error when wrapping an object", e); } } else if ("request".equals(scope)) { getRequestHashModel(env).getRequest().setAttribute(name, obj); } else if ("session".equals(scope)) { getRequestHashModel(env).getRequest().getSession().setAttribute( name, obj); } else if ("application".equals("scope")) { getServletContextHashModel(env).getServlet().getServletContext() .setAttribute(name, obj); } }
public static void setAttribute(Environment env, String name, Object obj, String scope) { if (scope == null) { scope = "page"; } if ("page".equals(scope)) { try { TemplateModel model = env.getObjectWrapper().wrap(obj); env.setVariable(name, model); } catch (TemplateModelException e) { throw new FreeMarkerTilesException( "Error when wrapping an object", e); } } else if ("request".equals(scope)) { getRequestHashModel(env).getRequest().setAttribute(name, obj); } else if ("session".equals(scope)) { getRequestHashModel(env).getRequest().getSession().setAttribute( name, obj); } else if ("application".equals(scope)) { getServletContextHashModel(env).getServlet().getServletContext() .setAttribute(name, obj); } }
diff --git a/src/main/java/net/diegolemos/gameoflife/GameOfLife.java b/src/main/java/net/diegolemos/gameoflife/GameOfLife.java index 6ede7f8..e100225 100644 --- a/src/main/java/net/diegolemos/gameoflife/GameOfLife.java +++ b/src/main/java/net/diegolemos/gameoflife/GameOfLife.java @@ -1,50 +1,50 @@ package net.diegolemos.gameoflife; import static java.lang.Thread.sleep; /** * @author: Diego Lemos * @since: 12/9/12 */ public class GameOfLife { private static final Cell[] BLINDER = new Cell[] {new Cell(1,0), new Cell(1,1), new Cell(1,2)}; private static final Cell[] GLIDER = new Cell[] {new Cell(3,4), new Cell(4,4), new Cell(5,4), new Cell(5,5), new Cell(4,6)}; public static void main(String... args) throws InterruptedException { World world = new World(GLIDER); do { printSpace(world); } while(world.nextGeneration()); } private static void printSpace(World world) throws InterruptedException { String space = takeAPicture(world); System.out.println(space); sleep(500L); } private static String takeAPicture(World world) { int minX = 0; int minY = 0; - int maxX = 10; + int maxX = 30; int maxY = 10; StringBuilder space = new StringBuilder(); - for(int x = minX; x <= maxX; x++) { - for(int y = minY; y <= maxY; y++) { + for(int y = maxY; y >= minY; y--) { + for(int x = minX; x <= maxX; x++) { if(world.isAlive(new Cell(x, y))) { space.append("X"); } else { space.append(" "); } } space.append("\n"); } return space.toString(); } }
false
true
private static String takeAPicture(World world) { int minX = 0; int minY = 0; int maxX = 10; int maxY = 10; StringBuilder space = new StringBuilder(); for(int x = minX; x <= maxX; x++) { for(int y = minY; y <= maxY; y++) { if(world.isAlive(new Cell(x, y))) { space.append("X"); } else { space.append(" "); } } space.append("\n"); } return space.toString(); }
private static String takeAPicture(World world) { int minX = 0; int minY = 0; int maxX = 30; int maxY = 10; StringBuilder space = new StringBuilder(); for(int y = maxY; y >= minY; y--) { for(int x = minX; x <= maxX; x++) { if(world.isAlive(new Cell(x, y))) { space.append("X"); } else { space.append(" "); } } space.append("\n"); } return space.toString(); }
diff --git a/src/org/achartengine/chart/BarChart.java b/src/org/achartengine/chart/BarChart.java index bb4d927..fb3c695 100644 --- a/src/org/achartengine/chart/BarChart.java +++ b/src/org/achartengine/chart/BarChart.java @@ -1,312 +1,315 @@ /** * Copyright (C) 2009 - 2012 SC 4ViewSoft SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.achartengine.chart; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.SimpleSeriesRenderer; import org.achartengine.renderer.XYMultipleSeriesRenderer; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; /** * The bar chart rendering class. */ public class BarChart extends XYChart { /** The constant to identify this chart type. */ public static final String TYPE = "Bar"; /** The legend shape width. */ private static final int SHAPE_WIDTH = 12; /** The chart type. */ protected Type mType = Type.DEFAULT; /** * The bar chart type enum. */ public enum Type { DEFAULT, STACKED; } BarChart() { } /** * Builds a new bar chart instance. * * @param dataset the multiple series dataset * @param renderer the multiple series renderer * @param type the bar chart type */ public BarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) { super(dataset, renderer); mType = type; } @Override protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, float yAxisValue, int seriesIndex, int startIndex) { int seriesNr = mDataset.getSeriesCount(); int length = points.length; ClickableArea[] ret = new ClickableArea[length / 2]; float halfDiffX = getHalfDiffX(points, length, seriesNr); for (int i = 0; i < length; i += 2) { float x = points[i]; float y = points[i + 1]; if (mType == Type.STACKED) { ret[i / 2] = new ClickableArea(new RectF(x - halfDiffX, y, x + halfDiffX, yAxisValue), values[i], values[i + 1]); } else { float startX = x - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX; ret[i / 2] = new ClickableArea(new RectF(startX, y, startX + 2 * halfDiffX, yAxisValue), values[i], values[i + 1]); } } return ret; } /** * The graphical representation of a series. * * @param canvas the canvas to paint to * @param paint the paint to be used for drawing * @param points the array of points to be used for drawing the series * @param seriesRenderer the series renderer * @param yAxisValue the minimum value of the y axis * @param seriesIndex the index of the series currently being drawn * @param startIndex the start index of the rendering points */ public void drawSeries(Canvas canvas, Paint paint, float[] points, SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { int seriesNr = mDataset.getSeriesCount(); int length = points.length; paint.setColor(seriesRenderer.getColor()); paint.setStyle(Style.FILL); float halfDiffX = getHalfDiffX(points, length, seriesNr); for (int i = 0; i < length; i += 2) { float x = points[i]; float y = points[i + 1]; drawBar(canvas, x, yAxisValue, x, y, halfDiffX, seriesNr, seriesIndex, paint); } paint.setColor(seriesRenderer.getColor()); } /** * Draws a bar. * * @param canvas the canvas * @param xMin the X axis minimum * @param yMin the Y axis minimum * @param xMax the X axis maximum * @param yMax the Y axis maximum * @param halfDiffX half the size of a bar * @param seriesNr the total number of series * @param seriesIndex the current series index * @param paint the paint */ protected void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, float halfDiffX, int seriesNr, int seriesIndex, Paint paint) { int scale = mDataset.getSeriesAt(seriesIndex).getScaleNumber(); if (mType == Type.STACKED) { drawBar(canvas, xMin - halfDiffX, yMax, xMax + halfDiffX, yMin, scale, seriesIndex, paint); } else { float startX = xMin - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX; drawBar(canvas, startX, yMax, startX + 2 * halfDiffX, yMin, scale, seriesIndex, paint); } } /** * Draws a bar. * * @param canvas the canvas * @param xMin the X axis minimum * @param yMin the Y axis minimum * @param xMax the X axis maximum * @param yMax the Y axis maximum * @param scale the scale index * @param seriesIndex the current series index * @param paint the paint */ private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, int seriesIndex, Paint paint) { SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); if (renderer.isGradientEnabled()) { float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, scale)[1]; float gradientMinY = Math.max(minY, yMin); float gradientMaxY = Math.min(maxY, yMax); int gradientMinColor = renderer.getGradientStopColor(); int gradientMaxColor = renderer.getGradientStartColor(); int gradientStartColor = gradientMaxColor; int gradientStopColor = gradientMinColor; if (yMin < minY) { paint.setColor(gradientMinColor); canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(gradientMinY), paint); } else { gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, (maxY - gradientMinY) / (maxY - minY)); } if (yMax > maxY) { paint.setColor(gradientMaxColor); canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), Math.round(yMax), paint); } else { gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, (gradientMaxY - minY) / (maxY - minY)); } GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { gradientStartColor, gradientStopColor }); gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), Math.round(gradientMaxY)); gradient.draw(canvas); } else { + if (yMin == yMax) { + yMin = yMax - 1; + } canvas .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); } } private int getGradientPartialColor(int minColor, int maxColor, float fraction) { int alpha = Math.round(fraction * Color.alpha(minColor) + (1 - fraction) * Color.alpha(maxColor)); int r = Math.round(fraction * Color.red(minColor) + (1 - fraction) * Color.red(maxColor)); int g = Math.round(fraction * Color.green(minColor) + (1 - fraction) * Color.green(maxColor)); int b = Math.round(fraction * Color.blue(minColor) + (1 - fraction) * Color.blue((maxColor))); return Color.argb(alpha, r, g, b); } /** * The graphical representation of the series values as text. * * @param canvas the canvas to paint to * @param series the series to be painted * @param renderer the series renderer * @param paint the paint to be used for drawing * @param points the array of points to be used for drawing the series * @param seriesIndex the index of the series currently being drawn * @param startIndex the start index of the rendering points */ protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer, Paint paint, float[] points, int seriesIndex, int startIndex) { int seriesNr = mDataset.getSeriesCount(); float halfDiffX = getHalfDiffX(points, points.length, seriesNr); for (int i = 0; i < points.length; i += 2) { int index = startIndex + i / 2; if (!isNullValue(series.getY(index))) { float x = points[i]; if (mType == Type.DEFAULT) { x += seriesIndex * 2 * halfDiffX - (seriesNr - 1.5f) * halfDiffX; } drawText(canvas, getLabel(series.getY(index)), x, points[i + 1] - renderer.getChartValuesSpacing(), paint, 0); } } } /** * Returns the legend shape width. * * @param seriesIndex the series index * @return the legend shape width */ public int getLegendShapeWidth(int seriesIndex) { return SHAPE_WIDTH; } /** * The graphical representation of the legend shape. * * @param canvas the canvas to paint to * @param renderer the series renderer * @param x the x value of the point the shape should be drawn at * @param y the y value of the point the shape should be drawn at * @param seriesIndex the series index * @param paint the paint to be used for drawing */ public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, int seriesIndex, Paint paint) { float halfShapeWidth = SHAPE_WIDTH / 2; canvas.drawRect(x, y - halfShapeWidth, x + SHAPE_WIDTH, y + halfShapeWidth, paint); } /** * Calculates and returns the half-distance in the graphical representation of * 2 consecutive points. * * @param points the points * @param length the points length * @param seriesNr the series number * @return the calculated half-distance value */ protected float getHalfDiffX(float[] points, int length, int seriesNr) { int div = length; if (length > 2) { div = length - 2; } float halfDiffX = (points[length - 2] - points[0]) / div; if (halfDiffX == 0) { halfDiffX = 10; } if (mType != Type.STACKED) { halfDiffX /= seriesNr; } return (float) (halfDiffX / (getCoeficient() * (1 + mRenderer.getBarSpacing()))); } /** * Returns the value of a constant used to calculate the half-distance. * * @return the constant value */ protected float getCoeficient() { return 1f; } /** * Returns if the chart should display the null values. * * @return if null values should be rendered */ protected boolean isRenderNullValues() { return true; } /** * Returns the default axis minimum. * * @return the default axis minimum */ public double getDefaultMinimum() { return 0; } /** * Returns the chart type identifier. * * @return the chart type */ public String getChartType() { return TYPE; } }
true
true
private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, int seriesIndex, Paint paint) { SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); if (renderer.isGradientEnabled()) { float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, scale)[1]; float gradientMinY = Math.max(minY, yMin); float gradientMaxY = Math.min(maxY, yMax); int gradientMinColor = renderer.getGradientStopColor(); int gradientMaxColor = renderer.getGradientStartColor(); int gradientStartColor = gradientMaxColor; int gradientStopColor = gradientMinColor; if (yMin < minY) { paint.setColor(gradientMinColor); canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(gradientMinY), paint); } else { gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, (maxY - gradientMinY) / (maxY - minY)); } if (yMax > maxY) { paint.setColor(gradientMaxColor); canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), Math.round(yMax), paint); } else { gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, (gradientMaxY - minY) / (maxY - minY)); } GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { gradientStartColor, gradientStopColor }); gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), Math.round(gradientMaxY)); gradient.draw(canvas); } else { canvas .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); } }
private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, int seriesIndex, Paint paint) { SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); if (renderer.isGradientEnabled()) { float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, scale)[1]; float gradientMinY = Math.max(minY, yMin); float gradientMaxY = Math.min(maxY, yMax); int gradientMinColor = renderer.getGradientStopColor(); int gradientMaxColor = renderer.getGradientStartColor(); int gradientStartColor = gradientMaxColor; int gradientStopColor = gradientMinColor; if (yMin < minY) { paint.setColor(gradientMinColor); canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(gradientMinY), paint); } else { gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, (maxY - gradientMinY) / (maxY - minY)); } if (yMax > maxY) { paint.setColor(gradientMaxColor); canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), Math.round(yMax), paint); } else { gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, (gradientMaxY - minY) / (maxY - minY)); } GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { gradientStartColor, gradientStopColor }); gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), Math.round(gradientMaxY)); gradient.draw(canvas); } else { if (yMin == yMax) { yMin = yMax - 1; } canvas .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); } }
diff --git a/src/portablejim/veinminer/lib/BlockLib.java b/src/portablejim/veinminer/lib/BlockLib.java index 6dcadf8..ccf8452 100644 --- a/src/portablejim/veinminer/lib/BlockLib.java +++ b/src/portablejim/veinminer/lib/BlockLib.java @@ -1,49 +1,49 @@ /* This file is part of VeinMiner. * * VeinMiner is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * VeinMiner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VeinMiner. * If not, see <http://www.gnu.org/licenses/>. */ package portablejim.veinminer.lib; import net.minecraft.block.Block; import portablejim.veinminer.util.BlockID; /** * Provides extra functions dealing with blocks. */ public class BlockLib { /** * Uses the hooks from Block.getPickBlock() to check if the first and * second blocks give different metadata. * @param first BlockID of the first block. * @param second BlockID of the secound block. * @return If pick block on both blocks are the same. */ public static boolean arePickBlockEqual(BlockID first, BlockID second) { if(first == null || second == null || first.id >= Block.blocksList.length || second.id >= Block.blocksList.length) { return false; } Block firstBlock = Block.blocksList[first.id]; Block secondBlock = Block.blocksList[second.id]; int firstResultMeta = firstBlock.damageDropped(first.metadata); int secondResultMeta = secondBlock.damageDropped(second.metadata); - return firstResultMeta == secondResultMeta; + return firstBlock.equals(secondBlock) && firstResultMeta == secondResultMeta; } }
true
true
public static boolean arePickBlockEqual(BlockID first, BlockID second) { if(first == null || second == null || first.id >= Block.blocksList.length || second.id >= Block.blocksList.length) { return false; } Block firstBlock = Block.blocksList[first.id]; Block secondBlock = Block.blocksList[second.id]; int firstResultMeta = firstBlock.damageDropped(first.metadata); int secondResultMeta = secondBlock.damageDropped(second.metadata); return firstResultMeta == secondResultMeta; }
public static boolean arePickBlockEqual(BlockID first, BlockID second) { if(first == null || second == null || first.id >= Block.blocksList.length || second.id >= Block.blocksList.length) { return false; } Block firstBlock = Block.blocksList[first.id]; Block secondBlock = Block.blocksList[second.id]; int firstResultMeta = firstBlock.damageDropped(first.metadata); int secondResultMeta = secondBlock.damageDropped(second.metadata); return firstBlock.equals(secondBlock) && firstResultMeta == secondResultMeta; }
diff --git a/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SubjectCoordinatorDashboardService.java b/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SubjectCoordinatorDashboardService.java index 1e9e575b2..6b3b06f71 100644 --- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SubjectCoordinatorDashboardService.java +++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SubjectCoordinatorDashboardService.java @@ -1,182 +1,189 @@ package edu.northwestern.bioinformatics.studycalendar.service; import edu.northwestern.bioinformatics.studycalendar.domain.*; import edu.northwestern.bioinformatics.studycalendar.dao.ScheduledActivityDao; import java.util.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import org.springframework.beans.factory.annotation.Required; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SubjectCoordinatorDashboardService { private ScheduledActivityDao scheduledActivityDao; final String dayNames[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; private static final Logger log = LoggerFactory.getLogger(SubjectCoordinatorDashboardService.class.getName()); public Map<String, Object> getMapOfCurrentEvents(List<StudySubjectAssignment> studySubjectAssignments, int initialShiftDate) { Date startDate = new Date(); Collection<ScheduledActivity> collectionOfEvents; SortedMap<String, Object> mapOfUserAndCalendar = new TreeMap<String, Object>(); Map <String, Object> subjectAndEvents; for (int i =0; i< initialShiftDate; i++) { Date tempStartDate = shiftStartDayByNumberOfDays(startDate, i); subjectAndEvents = new HashMap<String, Object>(); for (StudySubjectAssignment studySubjectAssignment : studySubjectAssignments) { List<ScheduledActivity> events = new ArrayList<ScheduledActivity>(); ScheduledCalendar calendar = studySubjectAssignment.getScheduledCalendar(); collectionOfEvents = getScheduledActivityDao().getEventsByDate(calendar, tempStartDate, tempStartDate); Subject subject = studySubjectAssignment.getSubject(); String subjectName = subject.getFullName(); if (collectionOfEvents.size()>0) { for (ScheduledActivity event : collectionOfEvents) { events.add(event); } } if (events != null && events.size() > 0) { subjectAndEvents.put(subjectName, events); } } String keyDate = formatDateToString(tempStartDate); keyDate = keyDate + " - " + convertDateKeyToString(tempStartDate); if (subjectAndEvents!= null && subjectAndEvents.size()>0) { mapOfUserAndCalendar.put(keyDate, subjectAndEvents); } } return mapOfUserAndCalendar; } public Map<String, Object> getMapOfCurrentEventsForSpecificActivity( List<StudySubjectAssignment> studySubjectAssignments, int initialShiftDate, Map<ActivityType, Boolean> activities) { Date startDate = new Date(); Collection<ScheduledActivity> collectionOfEvents; SortedMap<String, Object> mapOfUserAndCalendar = new TreeMap<String, Object>(); Map <String, Object> subjectAndEvents; - for (int i =0; i< initialShiftDate; i++) { - Date tempStartDate = shiftStartDayByNumberOfDays(startDate, i); + for (int i = 0; i< initialShiftDate; i++) { + Date tempStartDate; + if (i == 0) { + //need to get activities for the startDate itself + tempStartDate = shiftStartDayByNumberOfDays(startDate, i); + } else { + tempStartDate = shiftStartDayByNumberOfDays(startDate, 1); + } subjectAndEvents = new HashMap<String, Object>(); for (StudySubjectAssignment studySubjectAssignment : studySubjectAssignments) { List<ScheduledActivity> events = new ArrayList<ScheduledActivity>(); ScheduledCalendar calendar = studySubjectAssignment.getScheduledCalendar(); collectionOfEvents = getScheduledActivityDao().getEventsByDate(calendar, tempStartDate, tempStartDate); Subject subject = studySubjectAssignment.getSubject(); String subjectName = subject.getFullName(); if (collectionOfEvents.size()>0) { for (ScheduledActivity event : collectionOfEvents) { ActivityType eventActivityType = event.getActivity().getType(); Boolean value; if(!activities.containsKey(eventActivityType)) { value = false; } else { value = activities.get(eventActivityType); } if (value) { events.add(event); } } } if (events != null && events.size()> 0) { subjectAndEvents.put(subjectName, events); } } String keyDate = formatDateToString(tempStartDate); keyDate = keyDate + " - " + convertDateKeyToString(tempStartDate); if (subjectAndEvents!= null && subjectAndEvents.size()>0) { mapOfUserAndCalendar.put(keyDate, subjectAndEvents); } + startDate = tempStartDate; } return mapOfUserAndCalendar; } public String convertDateKeyToString(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); int dayOfTheWeek = c.get(Calendar.DAY_OF_WEEK); return dayNames[dayOfTheWeek-1]; } public Map<Object, Object> getMapOfOverdueEvents(List<StudySubjectAssignment> studySubjectAssignments) { Date currentDate = new Date(); Date endDate = shiftStartDayByNumberOfDays(currentDate, -1); //list of events overtue Map <Object, Object> subjectAndOverDueEvents = new HashMap<Object, Object>(); for (StudySubjectAssignment studySubjectAssignment : studySubjectAssignments) { List<ScheduledActivity> events = new ArrayList<ScheduledActivity>(); Map<Object, Integer> key = new HashMap<Object, Integer>(); ScheduledCalendar calendar = studySubjectAssignment.getScheduledCalendar(); Date startDate = studySubjectAssignment.getStartDateEpoch(); Collection<ScheduledActivity> collectionOfEvents = getScheduledActivityDao().getEventsByDate(calendar, startDate, endDate); Subject subject = studySubjectAssignment.getSubject(); for (ScheduledActivity event : collectionOfEvents) { if(event.getCurrentState().getMode().equals(ScheduledActivityMode.SCHEDULED)) { events.add(event); } } if (events.size()>0) { key.put(subject, events.size()); subjectAndOverDueEvents.put(key, studySubjectAssignment); } } return subjectAndOverDueEvents; } public Date shiftStartDayByNumberOfDays(Date startDate, Integer numberOfDays) { java.sql.Timestamp timestampTo = new java.sql.Timestamp(startDate.getTime()); long numberOfDaysToShift = numberOfDays * 24 * 60 * 60 * 1000; timestampTo.setTime(timestampTo.getTime() + numberOfDaysToShift); Date d = timestampTo; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String dateString = df.format(d); Date d1; try { d1 = df.parse(dateString); } catch (ParseException e) { log.debug("Exception " + e); d1 = startDate; } return d1; } public String formatDateToString(Date date) { DateFormat df = new SimpleDateFormat("MM/dd"); return df.format(date); } @Required public void setScheduledActivityDao(ScheduledActivityDao scheduledActivityDao) { this.scheduledActivityDao = scheduledActivityDao; } public ScheduledActivityDao getScheduledActivityDao() { return scheduledActivityDao; } }
false
true
public Map<String, Object> getMapOfCurrentEventsForSpecificActivity( List<StudySubjectAssignment> studySubjectAssignments, int initialShiftDate, Map<ActivityType, Boolean> activities) { Date startDate = new Date(); Collection<ScheduledActivity> collectionOfEvents; SortedMap<String, Object> mapOfUserAndCalendar = new TreeMap<String, Object>(); Map <String, Object> subjectAndEvents; for (int i =0; i< initialShiftDate; i++) { Date tempStartDate = shiftStartDayByNumberOfDays(startDate, i); subjectAndEvents = new HashMap<String, Object>(); for (StudySubjectAssignment studySubjectAssignment : studySubjectAssignments) { List<ScheduledActivity> events = new ArrayList<ScheduledActivity>(); ScheduledCalendar calendar = studySubjectAssignment.getScheduledCalendar(); collectionOfEvents = getScheduledActivityDao().getEventsByDate(calendar, tempStartDate, tempStartDate); Subject subject = studySubjectAssignment.getSubject(); String subjectName = subject.getFullName(); if (collectionOfEvents.size()>0) { for (ScheduledActivity event : collectionOfEvents) { ActivityType eventActivityType = event.getActivity().getType(); Boolean value; if(!activities.containsKey(eventActivityType)) { value = false; } else { value = activities.get(eventActivityType); } if (value) { events.add(event); } } } if (events != null && events.size()> 0) { subjectAndEvents.put(subjectName, events); } } String keyDate = formatDateToString(tempStartDate); keyDate = keyDate + " - " + convertDateKeyToString(tempStartDate); if (subjectAndEvents!= null && subjectAndEvents.size()>0) { mapOfUserAndCalendar.put(keyDate, subjectAndEvents); } } return mapOfUserAndCalendar; }
public Map<String, Object> getMapOfCurrentEventsForSpecificActivity( List<StudySubjectAssignment> studySubjectAssignments, int initialShiftDate, Map<ActivityType, Boolean> activities) { Date startDate = new Date(); Collection<ScheduledActivity> collectionOfEvents; SortedMap<String, Object> mapOfUserAndCalendar = new TreeMap<String, Object>(); Map <String, Object> subjectAndEvents; for (int i = 0; i< initialShiftDate; i++) { Date tempStartDate; if (i == 0) { //need to get activities for the startDate itself tempStartDate = shiftStartDayByNumberOfDays(startDate, i); } else { tempStartDate = shiftStartDayByNumberOfDays(startDate, 1); } subjectAndEvents = new HashMap<String, Object>(); for (StudySubjectAssignment studySubjectAssignment : studySubjectAssignments) { List<ScheduledActivity> events = new ArrayList<ScheduledActivity>(); ScheduledCalendar calendar = studySubjectAssignment.getScheduledCalendar(); collectionOfEvents = getScheduledActivityDao().getEventsByDate(calendar, tempStartDate, tempStartDate); Subject subject = studySubjectAssignment.getSubject(); String subjectName = subject.getFullName(); if (collectionOfEvents.size()>0) { for (ScheduledActivity event : collectionOfEvents) { ActivityType eventActivityType = event.getActivity().getType(); Boolean value; if(!activities.containsKey(eventActivityType)) { value = false; } else { value = activities.get(eventActivityType); } if (value) { events.add(event); } } } if (events != null && events.size()> 0) { subjectAndEvents.put(subjectName, events); } } String keyDate = formatDateToString(tempStartDate); keyDate = keyDate + " - " + convertDateKeyToString(tempStartDate); if (subjectAndEvents!= null && subjectAndEvents.size()>0) { mapOfUserAndCalendar.put(keyDate, subjectAndEvents); } startDate = tempStartDate; } return mapOfUserAndCalendar; }
diff --git a/src/main/java/org/jpos/jposext/isomsgaction/testing/service/support/MappingTest.java b/src/main/java/org/jpos/jposext/isomsgaction/testing/service/support/MappingTest.java index 8a70280..1ad269b 100644 --- a/src/main/java/org/jpos/jposext/isomsgaction/testing/service/support/MappingTest.java +++ b/src/main/java/org/jpos/jposext/isomsgaction/testing/service/support/MappingTest.java @@ -1,520 +1,520 @@ package org.jpos.jposext.isomsgaction.testing.service.support; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.betwixt.io.BeanWriter; import org.jpos.iso.ISOMsg; import org.jpos.iso.ISOUtil; import org.jpos.jposext.isomsgaction.model.SimpleContextWrapper; import org.jpos.jposext.isomsgaction.model.validation.ValidationError; import org.jpos.jposext.isomsgaction.model.validation.ValidationErrorTypeEnum; import org.jpos.jposext.isomsgaction.service.IISOMsgAction; import org.jpos.jposext.isomsgaction.service.support.ISOMsgActionCheckField; import org.jpos.jposext.isomsgaction.testing.model.ComparisonContext; import org.jpos.jposext.isomsgaction.testing.model.ISOCmpDiff; import org.jpos.jposext.isomsgaction.testing.model.ManualCheck; public class MappingTest extends TestCase { class MyErreurValidation extends ValidationError { private MyErreurValidation() { super(); } private MyErreurValidation(ValidationError validationError) { super(); setTypeErreur(validationError.getTypeErreur()); setParamName(validationError.getParamName()); } private MyErreurValidation(ValidationErrorTypeEnum typeErreur, String paramName) { super(typeErreur, paramName); } private MyErreurValidation(ValidationErrorTypeEnum typeErreur) { super(typeErreur); } public int hashCode() { // On choisit les deux nombres impairs int result = 7; final int multiplier = 17; // Pour chaque attribut, on calcule le hashcode // que l'on ajoute au r�sultat apr�s l'avoir multipli� // par le nombre "multiplieur" : result = multiplier * result + this.getParamName().hashCode(); result = multiplier * result + this.getTypeErreur().hashCode(); // On retourne le r�sultat : return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MyErreurValidation other = (MyErreurValidation) obj; if (getParamName() == null) { if (other.getParamName() != null) { return false; } } else if (!(getParamName().equals(other.getParamName()))) { return false; } if (getTypeErreur() == null) { if (other.getTypeErreur() != null) { return false; } } else if (!(getTypeErreur().equals(other.getTypeErreur()))) { return false; } return true; } } private List<ISOMsg> lstSrcISOMsg = new ArrayList<ISOMsg>(); private ISOMsg expectedISOMsg; private Map<String, Object> context = new HashMap<String, Object>(); private Map<String, ManualCheck> mapManualChecks = new TreeMap<String, ManualCheck>(); private Map<String, List<ValidationErrorTypeEnum>> mapExpectedErrsByIdPath; private IISOMsgAction action; private boolean showManualCheckReminder; private Map<String, Object> expectedContext = new HashMap<String, Object>(); private List<String> expectedContextBinaryAttrs = new ArrayList<String>(); private List<String> expectedContextNullAttrs = new ArrayList<String>(); @Override protected void runTest() throws Throwable { List<ISOCmpDiff> resList = new ArrayList<ISOCmpDiff>(); try { ISOMsg targetMsg = new ISOMsg(); ISOMsg[] tabISOMsg = new ISOMsg[1 + lstSrcISOMsg.size()]; tabISOMsg[0] = targetMsg; for (int i = 1; i <= lstSrcISOMsg.size(); i++) { tabISOMsg[i] = lstSrcISOMsg.get(i - 1); dumpMessage(System.out, tabISOMsg[i], String.format("Source ISO Message [%d]", i)); } if (null != expectedISOMsg) { dumpMessage(System.out, expectedISOMsg, "Expected ISO Message (excluding fields needing manual check)"); } action.process(tabISOMsg, context); if (null != targetMsg) { dumpMessage(System.out, targetMsg, "Result ISO message"); } ComparisonContext ctx = new ComparisonContext(); ctx.setResList(resList); ctx.setMapManualChecks(mapManualChecks); Map<MyErreurValidation, ValidationError> mapErrsInattendues = new HashMap<MyErreurValidation, ValidationError>(); Map<MyErreurValidation, ValidationError> mapErrsAttenduesTrouvees = new HashMap<MyErreurValidation, ValidationError>(); Map<MyErreurValidation, ValidationError> mapErrsAttenduesNonTrouvees = new HashMap<MyErreurValidation, ValidationError>(); List<ValidationError> lstErrsEnSortie = null; if (context .containsKey(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME)) { lstErrsEnSortie = (List<ValidationError>) context .get(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME); if (lstErrsEnSortie.size() > 0) { dumpErrorsList( System.out, (List<ValidationError>) context .get(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME)); } for (ValidationError validationError : lstErrsEnSortie) { if (mapExpectedErrsByIdPath.containsKey(validationError .getParamName())) { List<ValidationErrorTypeEnum> typesErreurAttendus = mapExpectedErrsByIdPath .get(validationError.getParamName()); if (!typesErreurAttendus.contains(validationError .getTypeErreur())) { mapErrsInattendues.put(new MyErreurValidation( validationError), validationError); } else { mapErrsAttenduesTrouvees.put( new MyErreurValidation(validationError), validationError); } } else { mapErrsInattendues.put(new MyErreurValidation( validationError), validationError); } } for (Entry<String, List<ValidationErrorTypeEnum>> entry : mapExpectedErrsByIdPath .entrySet()) { String idPath = entry.getKey(); for (ValidationErrorTypeEnum validationErrorTypeEnum : entry .getValue()) { MyErreurValidation errValid = new MyErreurValidation( validationErrorTypeEnum, idPath); if (!(mapErrsAttenduesTrouvees.containsKey(errValid))) { mapErrsAttenduesNonTrouvees.put( new MyErreurValidation(errValid), errValid); } } } for (Entry<MyErreurValidation, ValidationError> entry : mapErrsAttenduesNonTrouvees .entrySet()) { MyErreurValidation erreurValidation = entry.getKey(); resList.add(new ISOCmpDiff( erreurValidation.getParamName(), String.format( "Field %s : a validation error [%s] was expected", erreurValidation.getParamName(), erreurValidation.getTypeErreur().name()))); } for (Entry<MyErreurValidation, ValidationError> entry : mapErrsInattendues .entrySet()) { MyErreurValidation erreurValidation = entry.getKey(); resList.add(new ISOCmpDiff( erreurValidation.getParamName(), String.format( "Field %s : validation error [%s] was not expected", erreurValidation.getParamName(), erreurValidation.getTypeErreur().name()))); } } boolean expectedContextPopulationFailure = false; if (null != expectedContext) { for (Entry<String, Object> entry : expectedContext.entrySet()) { String ctxPath = entry.getKey(); String expectedValue = (String) entry.getValue(); Object effectiveObject = PropertyUtils.getProperty( new SimpleContextWrapper(context), ctxPath); boolean nullValueExpected = expectedContextNullAttrs.contains(ctxPath); if (nullValueExpected) { if (null != effectiveObject) { expectedContextPopulationFailure = true; resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : null expected, but set=[%s]", ctxPath, effectiveObject.toString()))); } } else { String effectiveValue = null; - if (effectiveObject.getClass().isPrimitive()) { + if (null == effectiveObject) { + effectiveValue = null; + } else if (effectiveObject.getClass().isPrimitive()) { effectiveValue = (String) effectiveObject; } else if (effectiveObject instanceof String) { effectiveValue = (String) effectiveObject; } else { - if (null != effectiveObject) { - effectiveValue = effectiveObject.toString(); - } + effectiveValue = effectiveObject.toString(); } if (!(expectedValue.equals(effectiveValue))) { expectedContextPopulationFailure = true; boolean dumpHex = expectedContextBinaryAttrs .contains(ctxPath); if (null != effectiveValue) { resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : expected %s=[%s], was %s=[%s]", ctxPath, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(expectedValue .getBytes()) : expectedValue, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(effectiveValue .getBytes()) : effectiveValue))); } else { resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : expected %s=[%s], but not set", ctxPath, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(expectedValue .getBytes()) : expectedValue))); } } } } } if (null != expectedISOMsg) { ISOComponentComparator comparator = new ISOComponentComparator( ctx, "", ""); if (comparator.compare(expectedISOMsg, targetMsg) != 0) { throw new AssertionFailedError("Test failed"); } } if (mapErrsAttenduesNonTrouvees.size() + mapErrsInattendues.size() > 0) { throw new AssertionFailedError("Test failed"); } if (expectedContextPopulationFailure) { throw new AssertionFailedError("Test failed"); } if (mapManualChecks.size() > 0) { if (showManualCheckReminder) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(bos); printStream.println("Generated ISO message :"); targetMsg.dump(printStream, ""); printStream.println(); printStream.println("Resulting context :"); BeanWriter beanWriter = new BeanWriter(printStream); beanWriter.enablePrettyPrint(); beanWriter.write(context); final JTextArea textArea = new JTextArea(); textArea.setFont(new Font("Sans-Serif", Font.PLAIN, 12)); textArea.setEditable(false); textArea.setText(bos.toString()); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setPreferredSize(new Dimension(450, 350)); JPanel panel = new JPanel(); BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.add(scrollPane, BorderLayout.CENTER); JPanel panLstVerif = new JPanel(); panLstVerif.setLayout(new BoxLayout(panLstVerif, BoxLayout.Y_AXIS)); panLstVerif.add(new JLabel("Manual checks :")); for (Entry<String, ManualCheck> entry : mapManualChecks .entrySet()) { panLstVerif.add(new JLabel(String.format("\t* %s : %s", entry.getKey(), entry.getValue().getDesc()))); } panLstVerif .add(new JLabel( "Do you confirm that checked values complies to their expected check rules ?")); panel.add(panLstVerif, BorderLayout.SOUTH); Object[] options = { "Yes", "No" }; int n = JOptionPane .showOptionDialog( null, panel, String.format("Manual checks (%s)", this.getName()), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 1) { throw new AssertionFailedError("Test failed"); } } } } catch (AssertionFailedError t) { t.setStackTrace(new StackTraceElement[] {}); StringBuffer buf = new StringBuffer(); buf.append(t.getMessage()); buf.append("\n\n"); if (resList.size() > 0) { buf.append("Differences list :"); buf.append("\n"); for (ISOCmpDiff resElt : resList) { buf.append(String.format("\t* %s", resElt)); buf.append("\n"); } buf.append("\n"); } if (mapManualChecks.size() > 0) { buf.append("Some of the manual checks have failed among :"); buf.append("\n"); for (Entry<String, ManualCheck> entry : mapManualChecks .entrySet()) { buf.append(String.format("\t* champ %s : %s", entry.getKey(), entry.getValue().getDesc())); buf.append("\n"); } buf.append("\n"); } throw new AssertionFailedError(buf.toString()); } } protected void dumpErrorsList(PrintStream ps, List<ValidationError> lstErrs) { if (null != lstErrs) { for (ValidationError err : lstErrs) { ps.println(String.format("id=%s, error=%s", err.getParamName(), err.getTypeErreur())); } } } protected String genIdPathFromTab(int[] tab, String sep) { StringBuffer buf = new StringBuffer(); String sepInter = ""; for (int idx : tab) { buf.append(sepInter); buf.append(idx); sepInter = sep; } return buf.toString(); } private void dumpMessage(PrintStream ps, ISOMsg msg, String libelleMsg) { String lineSep = "================================================================================"; ps.println(lineSep); ps.println(libelleMsg); ps.println(lineSep); msg.dump(ps, ""); ps.println(lineSep); ps.println(""); } public void addSrcISOMsg(ISOMsg isoMsg) { lstSrcISOMsg.add(isoMsg); } public void addManualCheck(String idPath, String desc) { mapManualChecks.put(idPath, new ManualCheck(idPath, desc)); } public List<ISOMsg> getLstSrcISOMsg() { return lstSrcISOMsg; } public void setLstSrcISOMsg(List<ISOMsg> lstSrcISOMsg) { this.lstSrcISOMsg = lstSrcISOMsg; } public Map<String, Object> getContext() { return context; } public void setContext(Map<String, Object> context) { this.context = context; } public ISOMsg getExpectedISOMsg() { return expectedISOMsg; } public void setExpectedISOMsg(ISOMsg expectedISOMsg) { this.expectedISOMsg = expectedISOMsg; } public IISOMsgAction getAction() { return action; } public void setAction(IISOMsgAction action) { this.action = action; } public Map<String, List<ValidationErrorTypeEnum>> getMapExpectedErrsByIdPath() { return mapExpectedErrsByIdPath; } public void setMapExpectedErrsByIdPath( Map<String, List<ValidationErrorTypeEnum>> mapExpectedErrsByIdPath) { this.mapExpectedErrsByIdPath = mapExpectedErrsByIdPath; } public boolean isShowManualCheckReminder() { return showManualCheckReminder; } public void setShowManualCheckReminder(boolean showManualCheckReminder) { this.showManualCheckReminder = showManualCheckReminder; } public Map<String, Object> getExpectedContext() { return expectedContext; } public void setExpectedContext(Map<String, Object> expectedContext) { this.expectedContext = expectedContext; } public List<String> getExpectedContextBinaryAttrs() { return expectedContextBinaryAttrs; } public void setExpectedContextBinaryAttrs( List<String> expectedContextBinaryAttrs) { this.expectedContextBinaryAttrs = expectedContextBinaryAttrs; } public List<String> getExpectedContextNullAttrs() { return expectedContextNullAttrs; } public void setExpectedContextNullAttrs( List<String> expectedContextNullAttrs) { this.expectedContextNullAttrs = expectedContextNullAttrs; } }
false
true
protected void runTest() throws Throwable { List<ISOCmpDiff> resList = new ArrayList<ISOCmpDiff>(); try { ISOMsg targetMsg = new ISOMsg(); ISOMsg[] tabISOMsg = new ISOMsg[1 + lstSrcISOMsg.size()]; tabISOMsg[0] = targetMsg; for (int i = 1; i <= lstSrcISOMsg.size(); i++) { tabISOMsg[i] = lstSrcISOMsg.get(i - 1); dumpMessage(System.out, tabISOMsg[i], String.format("Source ISO Message [%d]", i)); } if (null != expectedISOMsg) { dumpMessage(System.out, expectedISOMsg, "Expected ISO Message (excluding fields needing manual check)"); } action.process(tabISOMsg, context); if (null != targetMsg) { dumpMessage(System.out, targetMsg, "Result ISO message"); } ComparisonContext ctx = new ComparisonContext(); ctx.setResList(resList); ctx.setMapManualChecks(mapManualChecks); Map<MyErreurValidation, ValidationError> mapErrsInattendues = new HashMap<MyErreurValidation, ValidationError>(); Map<MyErreurValidation, ValidationError> mapErrsAttenduesTrouvees = new HashMap<MyErreurValidation, ValidationError>(); Map<MyErreurValidation, ValidationError> mapErrsAttenduesNonTrouvees = new HashMap<MyErreurValidation, ValidationError>(); List<ValidationError> lstErrsEnSortie = null; if (context .containsKey(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME)) { lstErrsEnSortie = (List<ValidationError>) context .get(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME); if (lstErrsEnSortie.size() > 0) { dumpErrorsList( System.out, (List<ValidationError>) context .get(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME)); } for (ValidationError validationError : lstErrsEnSortie) { if (mapExpectedErrsByIdPath.containsKey(validationError .getParamName())) { List<ValidationErrorTypeEnum> typesErreurAttendus = mapExpectedErrsByIdPath .get(validationError.getParamName()); if (!typesErreurAttendus.contains(validationError .getTypeErreur())) { mapErrsInattendues.put(new MyErreurValidation( validationError), validationError); } else { mapErrsAttenduesTrouvees.put( new MyErreurValidation(validationError), validationError); } } else { mapErrsInattendues.put(new MyErreurValidation( validationError), validationError); } } for (Entry<String, List<ValidationErrorTypeEnum>> entry : mapExpectedErrsByIdPath .entrySet()) { String idPath = entry.getKey(); for (ValidationErrorTypeEnum validationErrorTypeEnum : entry .getValue()) { MyErreurValidation errValid = new MyErreurValidation( validationErrorTypeEnum, idPath); if (!(mapErrsAttenduesTrouvees.containsKey(errValid))) { mapErrsAttenduesNonTrouvees.put( new MyErreurValidation(errValid), errValid); } } } for (Entry<MyErreurValidation, ValidationError> entry : mapErrsAttenduesNonTrouvees .entrySet()) { MyErreurValidation erreurValidation = entry.getKey(); resList.add(new ISOCmpDiff( erreurValidation.getParamName(), String.format( "Field %s : a validation error [%s] was expected", erreurValidation.getParamName(), erreurValidation.getTypeErreur().name()))); } for (Entry<MyErreurValidation, ValidationError> entry : mapErrsInattendues .entrySet()) { MyErreurValidation erreurValidation = entry.getKey(); resList.add(new ISOCmpDiff( erreurValidation.getParamName(), String.format( "Field %s : validation error [%s] was not expected", erreurValidation.getParamName(), erreurValidation.getTypeErreur().name()))); } } boolean expectedContextPopulationFailure = false; if (null != expectedContext) { for (Entry<String, Object> entry : expectedContext.entrySet()) { String ctxPath = entry.getKey(); String expectedValue = (String) entry.getValue(); Object effectiveObject = PropertyUtils.getProperty( new SimpleContextWrapper(context), ctxPath); boolean nullValueExpected = expectedContextNullAttrs.contains(ctxPath); if (nullValueExpected) { if (null != effectiveObject) { expectedContextPopulationFailure = true; resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : null expected, but set=[%s]", ctxPath, effectiveObject.toString()))); } } else { String effectiveValue = null; if (effectiveObject.getClass().isPrimitive()) { effectiveValue = (String) effectiveObject; } else if (effectiveObject instanceof String) { effectiveValue = (String) effectiveObject; } else { if (null != effectiveObject) { effectiveValue = effectiveObject.toString(); } } if (!(expectedValue.equals(effectiveValue))) { expectedContextPopulationFailure = true; boolean dumpHex = expectedContextBinaryAttrs .contains(ctxPath); if (null != effectiveValue) { resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : expected %s=[%s], was %s=[%s]", ctxPath, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(expectedValue .getBytes()) : expectedValue, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(effectiveValue .getBytes()) : effectiveValue))); } else { resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : expected %s=[%s], but not set", ctxPath, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(expectedValue .getBytes()) : expectedValue))); } } } } } if (null != expectedISOMsg) { ISOComponentComparator comparator = new ISOComponentComparator( ctx, "", ""); if (comparator.compare(expectedISOMsg, targetMsg) != 0) { throw new AssertionFailedError("Test failed"); } } if (mapErrsAttenduesNonTrouvees.size() + mapErrsInattendues.size() > 0) { throw new AssertionFailedError("Test failed"); } if (expectedContextPopulationFailure) { throw new AssertionFailedError("Test failed"); } if (mapManualChecks.size() > 0) { if (showManualCheckReminder) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(bos); printStream.println("Generated ISO message :"); targetMsg.dump(printStream, ""); printStream.println(); printStream.println("Resulting context :"); BeanWriter beanWriter = new BeanWriter(printStream); beanWriter.enablePrettyPrint(); beanWriter.write(context); final JTextArea textArea = new JTextArea(); textArea.setFont(new Font("Sans-Serif", Font.PLAIN, 12)); textArea.setEditable(false); textArea.setText(bos.toString()); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setPreferredSize(new Dimension(450, 350)); JPanel panel = new JPanel(); BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.add(scrollPane, BorderLayout.CENTER); JPanel panLstVerif = new JPanel(); panLstVerif.setLayout(new BoxLayout(panLstVerif, BoxLayout.Y_AXIS)); panLstVerif.add(new JLabel("Manual checks :")); for (Entry<String, ManualCheck> entry : mapManualChecks .entrySet()) { panLstVerif.add(new JLabel(String.format("\t* %s : %s", entry.getKey(), entry.getValue().getDesc()))); } panLstVerif .add(new JLabel( "Do you confirm that checked values complies to their expected check rules ?")); panel.add(panLstVerif, BorderLayout.SOUTH); Object[] options = { "Yes", "No" }; int n = JOptionPane .showOptionDialog( null, panel, String.format("Manual checks (%s)", this.getName()), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 1) { throw new AssertionFailedError("Test failed"); } } } } catch (AssertionFailedError t) { t.setStackTrace(new StackTraceElement[] {}); StringBuffer buf = new StringBuffer(); buf.append(t.getMessage()); buf.append("\n\n"); if (resList.size() > 0) { buf.append("Differences list :"); buf.append("\n"); for (ISOCmpDiff resElt : resList) { buf.append(String.format("\t* %s", resElt)); buf.append("\n"); } buf.append("\n"); } if (mapManualChecks.size() > 0) { buf.append("Some of the manual checks have failed among :"); buf.append("\n"); for (Entry<String, ManualCheck> entry : mapManualChecks .entrySet()) { buf.append(String.format("\t* champ %s : %s", entry.getKey(), entry.getValue().getDesc())); buf.append("\n"); } buf.append("\n"); } throw new AssertionFailedError(buf.toString()); } }
protected void runTest() throws Throwable { List<ISOCmpDiff> resList = new ArrayList<ISOCmpDiff>(); try { ISOMsg targetMsg = new ISOMsg(); ISOMsg[] tabISOMsg = new ISOMsg[1 + lstSrcISOMsg.size()]; tabISOMsg[0] = targetMsg; for (int i = 1; i <= lstSrcISOMsg.size(); i++) { tabISOMsg[i] = lstSrcISOMsg.get(i - 1); dumpMessage(System.out, tabISOMsg[i], String.format("Source ISO Message [%d]", i)); } if (null != expectedISOMsg) { dumpMessage(System.out, expectedISOMsg, "Expected ISO Message (excluding fields needing manual check)"); } action.process(tabISOMsg, context); if (null != targetMsg) { dumpMessage(System.out, targetMsg, "Result ISO message"); } ComparisonContext ctx = new ComparisonContext(); ctx.setResList(resList); ctx.setMapManualChecks(mapManualChecks); Map<MyErreurValidation, ValidationError> mapErrsInattendues = new HashMap<MyErreurValidation, ValidationError>(); Map<MyErreurValidation, ValidationError> mapErrsAttenduesTrouvees = new HashMap<MyErreurValidation, ValidationError>(); Map<MyErreurValidation, ValidationError> mapErrsAttenduesNonTrouvees = new HashMap<MyErreurValidation, ValidationError>(); List<ValidationError> lstErrsEnSortie = null; if (context .containsKey(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME)) { lstErrsEnSortie = (List<ValidationError>) context .get(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME); if (lstErrsEnSortie.size() > 0) { dumpErrorsList( System.out, (List<ValidationError>) context .get(ISOMsgActionCheckField.VALIDATION_ERRORS_LIST_ATTRNAME)); } for (ValidationError validationError : lstErrsEnSortie) { if (mapExpectedErrsByIdPath.containsKey(validationError .getParamName())) { List<ValidationErrorTypeEnum> typesErreurAttendus = mapExpectedErrsByIdPath .get(validationError.getParamName()); if (!typesErreurAttendus.contains(validationError .getTypeErreur())) { mapErrsInattendues.put(new MyErreurValidation( validationError), validationError); } else { mapErrsAttenduesTrouvees.put( new MyErreurValidation(validationError), validationError); } } else { mapErrsInattendues.put(new MyErreurValidation( validationError), validationError); } } for (Entry<String, List<ValidationErrorTypeEnum>> entry : mapExpectedErrsByIdPath .entrySet()) { String idPath = entry.getKey(); for (ValidationErrorTypeEnum validationErrorTypeEnum : entry .getValue()) { MyErreurValidation errValid = new MyErreurValidation( validationErrorTypeEnum, idPath); if (!(mapErrsAttenduesTrouvees.containsKey(errValid))) { mapErrsAttenduesNonTrouvees.put( new MyErreurValidation(errValid), errValid); } } } for (Entry<MyErreurValidation, ValidationError> entry : mapErrsAttenduesNonTrouvees .entrySet()) { MyErreurValidation erreurValidation = entry.getKey(); resList.add(new ISOCmpDiff( erreurValidation.getParamName(), String.format( "Field %s : a validation error [%s] was expected", erreurValidation.getParamName(), erreurValidation.getTypeErreur().name()))); } for (Entry<MyErreurValidation, ValidationError> entry : mapErrsInattendues .entrySet()) { MyErreurValidation erreurValidation = entry.getKey(); resList.add(new ISOCmpDiff( erreurValidation.getParamName(), String.format( "Field %s : validation error [%s] was not expected", erreurValidation.getParamName(), erreurValidation.getTypeErreur().name()))); } } boolean expectedContextPopulationFailure = false; if (null != expectedContext) { for (Entry<String, Object> entry : expectedContext.entrySet()) { String ctxPath = entry.getKey(); String expectedValue = (String) entry.getValue(); Object effectiveObject = PropertyUtils.getProperty( new SimpleContextWrapper(context), ctxPath); boolean nullValueExpected = expectedContextNullAttrs.contains(ctxPath); if (nullValueExpected) { if (null != effectiveObject) { expectedContextPopulationFailure = true; resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : null expected, but set=[%s]", ctxPath, effectiveObject.toString()))); } } else { String effectiveValue = null; if (null == effectiveObject) { effectiveValue = null; } else if (effectiveObject.getClass().isPrimitive()) { effectiveValue = (String) effectiveObject; } else if (effectiveObject instanceof String) { effectiveValue = (String) effectiveObject; } else { effectiveValue = effectiveObject.toString(); } if (!(expectedValue.equals(effectiveValue))) { expectedContextPopulationFailure = true; boolean dumpHex = expectedContextBinaryAttrs .contains(ctxPath); if (null != effectiveValue) { resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : expected %s=[%s], was %s=[%s]", ctxPath, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(expectedValue .getBytes()) : expectedValue, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(effectiveValue .getBytes()) : effectiveValue))); } else { resList.add(new ISOCmpDiff( ctxPath, String.format( "Attribute %s : expected %s=[%s], but not set", ctxPath, dumpHex ? "(hex dump)" : "", dumpHex ? ISOUtil .hexdump(expectedValue .getBytes()) : expectedValue))); } } } } } if (null != expectedISOMsg) { ISOComponentComparator comparator = new ISOComponentComparator( ctx, "", ""); if (comparator.compare(expectedISOMsg, targetMsg) != 0) { throw new AssertionFailedError("Test failed"); } } if (mapErrsAttenduesNonTrouvees.size() + mapErrsInattendues.size() > 0) { throw new AssertionFailedError("Test failed"); } if (expectedContextPopulationFailure) { throw new AssertionFailedError("Test failed"); } if (mapManualChecks.size() > 0) { if (showManualCheckReminder) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(bos); printStream.println("Generated ISO message :"); targetMsg.dump(printStream, ""); printStream.println(); printStream.println("Resulting context :"); BeanWriter beanWriter = new BeanWriter(printStream); beanWriter.enablePrettyPrint(); beanWriter.write(context); final JTextArea textArea = new JTextArea(); textArea.setFont(new Font("Sans-Serif", Font.PLAIN, 12)); textArea.setEditable(false); textArea.setText(bos.toString()); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setPreferredSize(new Dimension(450, 350)); JPanel panel = new JPanel(); BorderLayout layout = new BorderLayout(); panel.setLayout(layout); panel.add(scrollPane, BorderLayout.CENTER); JPanel panLstVerif = new JPanel(); panLstVerif.setLayout(new BoxLayout(panLstVerif, BoxLayout.Y_AXIS)); panLstVerif.add(new JLabel("Manual checks :")); for (Entry<String, ManualCheck> entry : mapManualChecks .entrySet()) { panLstVerif.add(new JLabel(String.format("\t* %s : %s", entry.getKey(), entry.getValue().getDesc()))); } panLstVerif .add(new JLabel( "Do you confirm that checked values complies to their expected check rules ?")); panel.add(panLstVerif, BorderLayout.SOUTH); Object[] options = { "Yes", "No" }; int n = JOptionPane .showOptionDialog( null, panel, String.format("Manual checks (%s)", this.getName()), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 1) { throw new AssertionFailedError("Test failed"); } } } } catch (AssertionFailedError t) { t.setStackTrace(new StackTraceElement[] {}); StringBuffer buf = new StringBuffer(); buf.append(t.getMessage()); buf.append("\n\n"); if (resList.size() > 0) { buf.append("Differences list :"); buf.append("\n"); for (ISOCmpDiff resElt : resList) { buf.append(String.format("\t* %s", resElt)); buf.append("\n"); } buf.append("\n"); } if (mapManualChecks.size() > 0) { buf.append("Some of the manual checks have failed among :"); buf.append("\n"); for (Entry<String, ManualCheck> entry : mapManualChecks .entrySet()) { buf.append(String.format("\t* champ %s : %s", entry.getKey(), entry.getValue().getDesc())); buf.append("\n"); } buf.append("\n"); } throw new AssertionFailedError(buf.toString()); } }
diff --git a/src/main/java/net/vz/mongodb/jackson/internal/object/BsonObjectCursor.java b/src/main/java/net/vz/mongodb/jackson/internal/object/BsonObjectCursor.java index aba02f7..5306bcd 100644 --- a/src/main/java/net/vz/mongodb/jackson/internal/object/BsonObjectCursor.java +++ b/src/main/java/net/vz/mongodb/jackson/internal/object/BsonObjectCursor.java @@ -1,216 +1,216 @@ /* * Copyright 2011 VZ Netzwerke Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.vz.mongodb.jackson.internal.object; import com.mongodb.DBRef; import org.bson.BSONObject; import org.bson.types.ObjectId; import org.codehaus.jackson.JsonStreamContext; import org.codehaus.jackson.JsonToken; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Map; /** * Helper class for MongoDbObjectJsonParser * * @author James Roper * @since 1.0 */ abstract class BsonObjectCursor extends JsonStreamContext { /** * Parent cursor of this cursor, if any; null for root * cursors. */ private final BsonObjectCursor parent; public BsonObjectCursor(int contextType, BsonObjectCursor p) { super(); _type = contextType; _index = -1; parent = p; } // note: co-variant return type @Override public final BsonObjectCursor getParent() { return parent; } @Override public abstract String getCurrentName(); public abstract JsonToken nextToken(); public abstract JsonToken endToken(); public abstract Object currentNode(); public boolean currentHasChildren() { Object o = currentNode(); if (o instanceof Collection) { return !((Collection) o).isEmpty(); } else if (o instanceof Map) { return !((Map) o).isEmpty(); } return currentNode() != null; } /** * Method called to create a new context for iterating all * contents of the currentFieldName structured value (JSON array or object) * * @return A cursor for the children */ public final BsonObjectCursor iterateChildren() { Object n = currentNode(); if (n == null) throw new IllegalStateException("No current node"); if (n instanceof Iterable) { // false since we have already returned START_ARRAY return new ArrayCursor((Iterable) n, this); } if (n instanceof BSONObject) { return new ObjectCursor((BSONObject) n, this); } throw new IllegalStateException("Current node of type " + n.getClass().getName()); } /** * Cursor used for traversing iterables */ protected final static class ArrayCursor extends BsonObjectCursor { Iterator<?> contents; Object currentNode; public ArrayCursor(Iterable n, BsonObjectCursor p) { super(JsonStreamContext.TYPE_ARRAY, p); contents = n.iterator(); } @Override public String getCurrentName() { return null; } @Override public JsonToken nextToken() { if (!contents.hasNext()) { currentNode = null; return null; } currentNode = contents.next(); return getToken(currentNode); } @Override public JsonToken endToken() { return JsonToken.END_ARRAY; } @Override public Object currentNode() { return currentNode; } } /** * Cursor used for traversing non-empty JSON Object nodes */ protected final static class ObjectCursor extends BsonObjectCursor { Iterator<String> fields; BSONObject object; String currentFieldName; boolean needField; public ObjectCursor(BSONObject object, BsonObjectCursor p) { super(JsonStreamContext.TYPE_OBJECT, p); this.object = object; this.fields = object.keySet().iterator(); needField = true; } @Override public String getCurrentName() { return currentFieldName; } @Override public JsonToken nextToken() { // Need a new entry? if (needField) { if (!fields.hasNext()) { currentFieldName = null; return null; } needField = false; currentFieldName = fields.next(); return JsonToken.FIELD_NAME; } needField = true; return getToken(object.get(currentFieldName)); } @Override public JsonToken endToken() { return JsonToken.END_OBJECT; } @Override public Object currentNode() { return (currentFieldName == null) ? null : object.get(currentFieldName); } } private static JsonToken getToken(Object o) { if (o == null) { return JsonToken.VALUE_NULL; } else if (o instanceof Iterable) { return JsonToken.START_ARRAY; } else if (o instanceof BSONObject) { return JsonToken.START_OBJECT; } else if (o instanceof Number) { if (o instanceof Double || o instanceof Float || o instanceof BigDecimal) { return JsonToken.VALUE_NUMBER_FLOAT; } else { return JsonToken.VALUE_NUMBER_INT; } } else if (o instanceof Boolean) { if ((Boolean) o) { return JsonToken.VALUE_TRUE; } else { return JsonToken.VALUE_FALSE; } } else if (o instanceof CharSequence) { return JsonToken.VALUE_STRING; } else if (o instanceof ObjectId) { - return JsonToken.VALUE_STRING; + return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof DBRef) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof Date) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof byte[]) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else { throw new IllegalStateException("Don't know how to parse type: " + o.getClass()); } } }
true
true
private static JsonToken getToken(Object o) { if (o == null) { return JsonToken.VALUE_NULL; } else if (o instanceof Iterable) { return JsonToken.START_ARRAY; } else if (o instanceof BSONObject) { return JsonToken.START_OBJECT; } else if (o instanceof Number) { if (o instanceof Double || o instanceof Float || o instanceof BigDecimal) { return JsonToken.VALUE_NUMBER_FLOAT; } else { return JsonToken.VALUE_NUMBER_INT; } } else if (o instanceof Boolean) { if ((Boolean) o) { return JsonToken.VALUE_TRUE; } else { return JsonToken.VALUE_FALSE; } } else if (o instanceof CharSequence) { return JsonToken.VALUE_STRING; } else if (o instanceof ObjectId) { return JsonToken.VALUE_STRING; } else if (o instanceof DBRef) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof Date) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof byte[]) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else { throw new IllegalStateException("Don't know how to parse type: " + o.getClass()); } }
private static JsonToken getToken(Object o) { if (o == null) { return JsonToken.VALUE_NULL; } else if (o instanceof Iterable) { return JsonToken.START_ARRAY; } else if (o instanceof BSONObject) { return JsonToken.START_OBJECT; } else if (o instanceof Number) { if (o instanceof Double || o instanceof Float || o instanceof BigDecimal) { return JsonToken.VALUE_NUMBER_FLOAT; } else { return JsonToken.VALUE_NUMBER_INT; } } else if (o instanceof Boolean) { if ((Boolean) o) { return JsonToken.VALUE_TRUE; } else { return JsonToken.VALUE_FALSE; } } else if (o instanceof CharSequence) { return JsonToken.VALUE_STRING; } else if (o instanceof ObjectId) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof DBRef) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof Date) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else if (o instanceof byte[]) { return JsonToken.VALUE_EMBEDDED_OBJECT; } else { throw new IllegalStateException("Don't know how to parse type: " + o.getClass()); } }
diff --git a/src/com/bel/android/dspmanager/activity/DSPScreen.java b/src/com/bel/android/dspmanager/activity/DSPScreen.java index 4f4da2c..0bb09bf 100644 --- a/src/com/bel/android/dspmanager/activity/DSPScreen.java +++ b/src/com/bel/android/dspmanager/activity/DSPScreen.java @@ -1,100 +1,100 @@ package com.bel.android.dspmanager.activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.bel.android.dspmanager.HeadsetService; import com.bel.android.dspmanager.R; /** * This class implements a general PreferencesActivity that we can use to * adjust DSP settings. It adds a menu to clear the preferences on this page, * and a listener that ensures that our {@link HeadsetService} is running if * required. * * @author alankila */ public final class DSPScreen extends PreferenceActivity { private final OnSharedPreferenceChangeListener serviceLauncher = new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { sendBroadcast(new Intent("com.bel.android.dspmanager.UPDATE")); } }; /** Return the last component of the activity. */ private String getSubPage() { String[] action = getIntent().getAction().split("\\."); return action[action.length - 1].toLowerCase(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { - addPreferencesFromResource((Integer) R.xml.class.getField(getSubPage() + "_preferences").get(null)); + addPreferencesFromResource((Integer) this.getResources().getIdentifier(getSubPage() + "_preferences","xml",this.getPackageName())); } catch (Exception e) { throw new RuntimeException(e); } /* Register a listener that publishes UPDATE requests to the service starter. */ SharedPreferences preferences = getSharedPreferences(null, 0); preferences.registerOnSharedPreferenceChangeListener(serviceLauncher); } @Override protected void onDestroy() { super.onDestroy(); SharedPreferences preferences = getSharedPreferences(null, 0); preferences.unregisterOnSharedPreferenceChangeListener(serviceLauncher); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.reset: clearPrefs(); return true; default: return super.onMenuItemSelected(featureId, item); } } /** * We select the specific SharedPreferences repository based on the details of the * Intent used to reach this action. */ @Override public SharedPreferences getSharedPreferences(String name, int mode) { return super.getSharedPreferences(DSPManager.SHARED_PREFERENCES_BASENAME + "." + getSubPage(), mode); } private void clearPrefs() { SharedPreferences preferences = getSharedPreferences(null, 0); SharedPreferences.Editor preferencesEditor = preferences.edit(); for (String preference : preferences.getAll().keySet()) { preferencesEditor.remove(preference); } preferencesEditor.commit(); /* Now do something to make existing preferences to notice that things changed. */ finish(); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { addPreferencesFromResource((Integer) R.xml.class.getField(getSubPage() + "_preferences").get(null)); } catch (Exception e) { throw new RuntimeException(e); } /* Register a listener that publishes UPDATE requests to the service starter. */ SharedPreferences preferences = getSharedPreferences(null, 0); preferences.registerOnSharedPreferenceChangeListener(serviceLauncher); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { addPreferencesFromResource((Integer) this.getResources().getIdentifier(getSubPage() + "_preferences","xml",this.getPackageName())); } catch (Exception e) { throw new RuntimeException(e); } /* Register a listener that publishes UPDATE requests to the service starter. */ SharedPreferences preferences = getSharedPreferences(null, 0); preferences.registerOnSharedPreferenceChangeListener(serviceLauncher); }
diff --git a/warlock2-rcp/com.arcaner.warlock.rcp/src/com/arcaner/warlock/rcp/menu/ProfileConnectContributionItem.java b/warlock2-rcp/com.arcaner.warlock.rcp/src/com/arcaner/warlock/rcp/menu/ProfileConnectContributionItem.java index 32814752..edf3f6f2 100644 --- a/warlock2-rcp/com.arcaner.warlock.rcp/src/com/arcaner/warlock/rcp/menu/ProfileConnectContributionItem.java +++ b/warlock2-rcp/com.arcaner.warlock.rcp/src/com/arcaner/warlock/rcp/menu/ProfileConnectContributionItem.java @@ -1,36 +1,37 @@ package com.arcaner.warlock.rcp.menu; import java.util.Collection; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IContributionItem; import org.eclipse.ui.actions.CompoundContributionItem; import com.arcaner.warlock.configuration.Profile; import com.arcaner.warlock.configuration.SavedProfiles; import com.arcaner.warlock.rcp.actions.ProfileConnectAction; public class ProfileConnectContributionItem extends CompoundContributionItem { public ProfileConnectContributionItem() { super(); } public ProfileConnectContributionItem(String id) { super(id); } @Override protected IContributionItem[] getContributionItems() { Collection<Profile> profiles = SavedProfiles.getAllProfiles(); IContributionItem[] items = new IContributionItem[profiles.size()]; int i = 0; for (Profile profile : profiles) { items[i] = new ActionContributionItem(new ProfileConnectAction(profile)); + i++; } return items; } }
true
true
protected IContributionItem[] getContributionItems() { Collection<Profile> profiles = SavedProfiles.getAllProfiles(); IContributionItem[] items = new IContributionItem[profiles.size()]; int i = 0; for (Profile profile : profiles) { items[i] = new ActionContributionItem(new ProfileConnectAction(profile)); } return items; }
protected IContributionItem[] getContributionItems() { Collection<Profile> profiles = SavedProfiles.getAllProfiles(); IContributionItem[] items = new IContributionItem[profiles.size()]; int i = 0; for (Profile profile : profiles) { items[i] = new ActionContributionItem(new ProfileConnectAction(profile)); i++; } return items; }
diff --git a/src/de/azapps/mirakel/helper/export_import/AnyDoImport.java b/src/de/azapps/mirakel/helper/export_import/AnyDoImport.java index 23c2627c..167b4a3b 100644 --- a/src/de/azapps/mirakel/helper/export_import/AnyDoImport.java +++ b/src/de/azapps/mirakel/helper/export_import/AnyDoImport.java @@ -1,270 +1,277 @@ /******************************************************************************* * Mirakel is an Android App for managing your ToDo-Lists * * Copyright (c) 2013-2014 Anatolij Zelenin, Georg Semmler. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package de.azapps.mirakel.helper.export_import; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Environment; import android.util.Pair; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import de.azapps.mirakel.DefinitionsHelper; import de.azapps.mirakel.helper.Helpers; import de.azapps.mirakel.model.R; import de.azapps.mirakel.model.list.ListMirakel; import de.azapps.mirakel.model.recurring.Recurring; import de.azapps.mirakel.model.task.Task; import de.azapps.tools.Log; public class AnyDoImport { private static final String TAG = "AnyDoImport"; private static SparseIntArray taskMapping; public static boolean exec(Context ctx, String path_any_do) { String json; try { json = ExportImport.getStringFromFile(path_any_do, ctx); } catch (IOException e) { Log.e(TAG, "cannot read File"); return false; } Log.i(TAG, json); JsonObject i; try { i = new JsonParser().parse(json).getAsJsonObject(); } catch (JsonSyntaxException e2) { Log.e(TAG, "malformed backup"); return false; } Set<Entry<String, JsonElement>> f = i.entrySet(); SparseIntArray listMapping = new SparseIntArray(); List<Pair<Integer, String>> contents = new ArrayList<Pair<Integer, String>>(); taskMapping = new SparseIntArray(); for (Entry<String, JsonElement> e : f) { if (e.getKey().equals("categorys")) { Iterator<JsonElement> iter = e.getValue().getAsJsonArray() .iterator(); while (iter.hasNext()) { listMapping = parseList(iter.next().getAsJsonObject(), listMapping); } } else if (e.getKey().equals("tasks")) { Iterator<JsonElement> iter = e.getValue().getAsJsonArray() .iterator(); while (iter.hasNext()) { contents = parseTask(iter.next().getAsJsonObject(), listMapping, contents, ctx); } } else { Log.d(TAG, e.getKey()); } } for (Pair<Integer, String> pair : contents) { Task t = Task.get(taskMapping.get(pair.first)); if (t == null) { Log.d(TAG, "Task not found"); continue; } String oldContent = t.getContent(); t.setContent(oldContent == null || oldContent.equals("") ? pair.second : oldContent + "\n" + pair.second); t.safeSave(false); } return true; } public static void handleImportAnyDo(final Activity activity) { File dir = new File(Environment.getExternalStorageDirectory() + "/data/anydo/backups"); if (dir.isDirectory()) { File lastBackup = null; for (File f : dir.listFiles()) { if (lastBackup == null) { lastBackup = f; } else if (f.getAbsolutePath().compareTo( lastBackup.getAbsolutePath()) > 0) { lastBackup = f; } } final File backupFile = lastBackup; if (backupFile == null) return; new AlertDialog.Builder(activity) .setTitle(activity.getString(R.string.import_any_do_click)) .setMessage( activity.getString(R.string.any_do_this_file, backupFile.getAbsolutePath())) .setPositiveButton(activity.getString(android.R.string.ok), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { exec(activity, backupFile.getAbsolutePath()); android.os.Process .killProcess(android.os.Process .myPid()); } }) .setNegativeButton( activity.getString(R.string.select_file), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Helpers.showFileChooser( DefinitionsHelper.REQUEST_FILE_ANY_DO, activity.getString(R.string.any_do_import_title), activity); } }).show(); } else { new AlertDialog.Builder(activity) .setTitle(activity.getString(R.string.import_any_do_click)) .setMessage(activity.getString(R.string.any_do_how_to)) .setPositiveButton(activity.getString(android.R.string.ok), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handleImportAnyDo(activity); } }) .setNegativeButton( activity.getString(R.string.select_file), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Helpers.showFileChooser( DefinitionsHelper.REQUEST_FILE_ANY_DO, activity.getString(R.string.any_do_import_title), activity); } }).show(); // TODO show dialog with tutorial } } private static SparseIntArray parseList(JsonObject jsonList, SparseIntArray listMapping) { String name = jsonList.get("name").getAsString(); int id = jsonList.get("id").getAsInt(); ListMirakel l = ListMirakel.newList(name); listMapping.put(id, l.getId()); return listMapping; } private static List<Pair<Integer, String>> parseTask(JsonObject jsonTask, SparseIntArray listMapping, List<Pair<Integer, String>> contents, Context ctx) { String name = jsonTask.get("title").getAsString(); if (jsonTask.has("parentId")) { contents.add(new Pair<Integer, String>(jsonTask.get("parentId") .getAsInt(), name)); return contents; } int list_id = jsonTask.get("categoryId").getAsInt(); Task t = Task.newTask(name, ListMirakel.getList(listMapping.get(list_id))); taskMapping.put(jsonTask.get("id").getAsInt(), (int) t.getId()); if (jsonTask.has("dueDate")) { Calendar due = new GregorianCalendar(); long dueMs = jsonTask.get("dueDate").getAsLong(); if (dueMs > 0) { due.setTimeInMillis(dueMs); t.setDue(due); } } if (jsonTask.has("priority")) { int prio = 0; if (jsonTask.get("priority").getAsString().equals("High")) { prio = 2; } t.setPriority(prio); } if (jsonTask.has("status")) { - t.setDone(jsonTask.get("status").getAsString().equals("DONE")); + boolean done=false; + String status=jsonTask.get("status").getAsString(); + if(status.equals("DONE")||status.equals("CHECKED")){ + done=true; + }else if(status.equals("UNCHECKED")){ + done=false; + } + t.setDone(done); } if (jsonTask.has("repeatMethod")) { String repeat = jsonTask.get("repeatMethod").getAsString(); if (!repeat.equals("TASK_REPEAT_OFF")) { Recurring r = null; if (repeat.equals("TASK_REPEAT_DAY")) { r = Recurring.get(1, 0, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.daily), 0, 0, 1, 0, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_WEEK")) { r = Recurring.get(7, 0, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.weekly), 0, 0, 7, 0, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_MONTH")) { r = Recurring.get(0, 1, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.monthly), 0, 0, 0, 1, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_YEAR")) { r = Recurring.get(0, 0, 1); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.yearly), 0, 0, 0, 0, 1, true, null, null, false, false, new SparseBooleanArray()); } } if (r != null) { t.setRecurrence(r.getId()); } else { Log.d(TAG, repeat); } } } t.safeSave(false); return contents; } }
true
true
private static List<Pair<Integer, String>> parseTask(JsonObject jsonTask, SparseIntArray listMapping, List<Pair<Integer, String>> contents, Context ctx) { String name = jsonTask.get("title").getAsString(); if (jsonTask.has("parentId")) { contents.add(new Pair<Integer, String>(jsonTask.get("parentId") .getAsInt(), name)); return contents; } int list_id = jsonTask.get("categoryId").getAsInt(); Task t = Task.newTask(name, ListMirakel.getList(listMapping.get(list_id))); taskMapping.put(jsonTask.get("id").getAsInt(), (int) t.getId()); if (jsonTask.has("dueDate")) { Calendar due = new GregorianCalendar(); long dueMs = jsonTask.get("dueDate").getAsLong(); if (dueMs > 0) { due.setTimeInMillis(dueMs); t.setDue(due); } } if (jsonTask.has("priority")) { int prio = 0; if (jsonTask.get("priority").getAsString().equals("High")) { prio = 2; } t.setPriority(prio); } if (jsonTask.has("status")) { t.setDone(jsonTask.get("status").getAsString().equals("DONE")); } if (jsonTask.has("repeatMethod")) { String repeat = jsonTask.get("repeatMethod").getAsString(); if (!repeat.equals("TASK_REPEAT_OFF")) { Recurring r = null; if (repeat.equals("TASK_REPEAT_DAY")) { r = Recurring.get(1, 0, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.daily), 0, 0, 1, 0, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_WEEK")) { r = Recurring.get(7, 0, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.weekly), 0, 0, 7, 0, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_MONTH")) { r = Recurring.get(0, 1, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.monthly), 0, 0, 0, 1, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_YEAR")) { r = Recurring.get(0, 0, 1); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.yearly), 0, 0, 0, 0, 1, true, null, null, false, false, new SparseBooleanArray()); } } if (r != null) { t.setRecurrence(r.getId()); } else { Log.d(TAG, repeat); } } } t.safeSave(false); return contents; }
private static List<Pair<Integer, String>> parseTask(JsonObject jsonTask, SparseIntArray listMapping, List<Pair<Integer, String>> contents, Context ctx) { String name = jsonTask.get("title").getAsString(); if (jsonTask.has("parentId")) { contents.add(new Pair<Integer, String>(jsonTask.get("parentId") .getAsInt(), name)); return contents; } int list_id = jsonTask.get("categoryId").getAsInt(); Task t = Task.newTask(name, ListMirakel.getList(listMapping.get(list_id))); taskMapping.put(jsonTask.get("id").getAsInt(), (int) t.getId()); if (jsonTask.has("dueDate")) { Calendar due = new GregorianCalendar(); long dueMs = jsonTask.get("dueDate").getAsLong(); if (dueMs > 0) { due.setTimeInMillis(dueMs); t.setDue(due); } } if (jsonTask.has("priority")) { int prio = 0; if (jsonTask.get("priority").getAsString().equals("High")) { prio = 2; } t.setPriority(prio); } if (jsonTask.has("status")) { boolean done=false; String status=jsonTask.get("status").getAsString(); if(status.equals("DONE")||status.equals("CHECKED")){ done=true; }else if(status.equals("UNCHECKED")){ done=false; } t.setDone(done); } if (jsonTask.has("repeatMethod")) { String repeat = jsonTask.get("repeatMethod").getAsString(); if (!repeat.equals("TASK_REPEAT_OFF")) { Recurring r = null; if (repeat.equals("TASK_REPEAT_DAY")) { r = Recurring.get(1, 0, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.daily), 0, 0, 1, 0, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_WEEK")) { r = Recurring.get(7, 0, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.weekly), 0, 0, 7, 0, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_MONTH")) { r = Recurring.get(0, 1, 0); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.monthly), 0, 0, 0, 1, 0, true, null, null, false, false, new SparseBooleanArray()); } } else if (repeat.equals("TASK_REPEAT_YEAR")) { r = Recurring.get(0, 0, 1); if (r == null) { r = Recurring.newRecurring( ctx.getString(R.string.yearly), 0, 0, 0, 0, 1, true, null, null, false, false, new SparseBooleanArray()); } } if (r != null) { t.setRecurrence(r.getId()); } else { Log.d(TAG, repeat); } } } t.safeSave(false); return contents; }
diff --git a/src/gov/nih/ncgc/bard/tools/JettyRunner.java b/src/gov/nih/ncgc/bard/tools/JettyRunner.java index 3a11ae8..7f68682 100644 --- a/src/gov/nih/ncgc/bard/tools/JettyRunner.java +++ b/src/gov/nih/ncgc/bard/tools/JettyRunner.java @@ -1,76 +1,80 @@ package gov.nih.ncgc.bard.tools; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; import java.io.File; import java.io.FileInputStream; /** * Runs the API standalong using an embedded Jetty container. * <p/> * This is useful for debugging and if desired a single bundled * application. Currently the project does not include the Jetty * dependencies, so you'll have to get them separately and add * them to your class path. This has been tested with Jetty 7. * <p/> * In addition, to support JNDI resources for pooled database connections * you'll need the following libraries in your CLASSPATH as well * <ul> * <li>commons-dbcp-1.4.jar</li> * <li>commons-pool-1.6.jar</li> * <li>mysql-connector-java-5.1.19-bin.jar</li> * </ul> * Finally, you'll need to edit your jetty.xml file to include something * like * <code> * <New id="mysqlpds" class="org.eclipse.jetty.plus.jndi.Resource"> * <Arg>jdbc/myidentifier</Arg> * <Arg> * <New class="org.apache.commons.dbcp.BasicDataSource"> * <Set name="driverClassName">com.mysql.jdbc.Driver</Set> * <Set name="Url">jdbc:mysql://host:port/dbname?autoReconnect=true</Set> * <Set name="Username">your_username</Set> * <Set name="Password">yourpassword</Set> * </New> * </Arg> * </New> * <p/> * </code> * where <code>jdbc/myidentifier</code> is the String you use when * lookup the JNDI resource (see {@link DBUtils.getConnection()} * * @author Rajarshi Guha */ public class JettyRunner { /** * Start embedded Jetty server. * * @param args Command line arguments. Currently you just need to specify the path to jetty.xml * @throws Exception */ public static void main(String[] args) throws Exception { + if (args.length != 1) { + System.err.println("Must specify path to jetty.xml"); + System.exit(-1); + } File configFile = new File(args[0]); XmlConfiguration configuration = new XmlConfiguration(new FileInputStream(configFile)); Server server = (Server) configuration.configure(); Connector connector = new SelectChannelConnector(); connector.setPort(8080); connector.setHost("127.0.0.1"); server.addConnector(connector); WebAppContext wac = new WebAppContext(); wac.setContextPath("/"); wac.setDescriptor("web/WEB-INF/web.xml"); wac.setResourceBase("classes"); wac.setParentLoaderPriority(true); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); server.join(); } }
true
true
public static void main(String[] args) throws Exception { File configFile = new File(args[0]); XmlConfiguration configuration = new XmlConfiguration(new FileInputStream(configFile)); Server server = (Server) configuration.configure(); Connector connector = new SelectChannelConnector(); connector.setPort(8080); connector.setHost("127.0.0.1"); server.addConnector(connector); WebAppContext wac = new WebAppContext(); wac.setContextPath("/"); wac.setDescriptor("web/WEB-INF/web.xml"); wac.setResourceBase("classes"); wac.setParentLoaderPriority(true); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); server.join(); }
public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Must specify path to jetty.xml"); System.exit(-1); } File configFile = new File(args[0]); XmlConfiguration configuration = new XmlConfiguration(new FileInputStream(configFile)); Server server = (Server) configuration.configure(); Connector connector = new SelectChannelConnector(); connector.setPort(8080); connector.setHost("127.0.0.1"); server.addConnector(connector); WebAppContext wac = new WebAppContext(); wac.setContextPath("/"); wac.setDescriptor("web/WEB-INF/web.xml"); wac.setResourceBase("classes"); wac.setParentLoaderPriority(true); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); server.join(); }
diff --git a/src/nz/ac/vuw/ecs/fgpj/core/Function.java b/src/nz/ac/vuw/ecs/fgpj/core/Function.java index 72ab3d7..e165765 100644 --- a/src/nz/ac/vuw/ecs/fgpj/core/Function.java +++ b/src/nz/ac/vuw/ecs/fgpj/core/Function.java @@ -1,291 +1,292 @@ package nz.ac.vuw.ecs.fgpj.core; /* FGPJ Genetic Programming library Copyright (C) 2011 Roman Klapaukh This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.List; /** * The Function class represents a function in the GP program tree * * @author Roman Klapaukh * */ public abstract class Function extends Node { private Node args[]; private int argReturnTypes[]; /** * Make a new Function. It has a fixed number of children. A return type and * a name. The name cannot contain any whitespace. * * Another important restriction is that you cannot have two Nodes such that * the name of one is the prefix of another, e.g., Int and Integer. This is * because of the way that nodes are identified when being parsed from * files. While this problem could be avoided it would require more code on * the user end which does not seem worth while. * * @param type * return type of the function * @param numArgs * number of arguments the function takes * @param name * name of the function (with no whitespace) */ public Function(int type, int numArgs, String name) { super(type, numArgs, name); args = null; argReturnTypes = null; // If the number of arguments this function accepts is greater than zero // (which is must be as it is a function // and not a Terminal // then we need to allocate the space to store pointers to the arguments // and to store their return types. args = new Node[numArgs]; argReturnTypes = new int[numArgs]; for (int i = 0; i < numArgs; i++) { args[i] = null; argReturnTypes[i] = -1; } } /** * Set the Nth argument * * @param N * the argument to set * @param node * the node that is the argument */ public void setArgN(int N, Node node) { if (node == null) throw new IllegalArgumentException("Node is NULL"); if (node.getReturnType() != argReturnTypes[N]) throw new IllegalArgumentException( "Incorrect return type for argument " + N); args[N] = node; node.setParent(this); } /** * Get the argument at position N * * @param N * The argument to get * @return root of subtree at position N */ public Node getArgN(int N) { return args[N]; } /** * Set the return type of the Nth argument * * @param N * position for which argument to set * @param type * the type to set the argument to */ protected void setArgNReturnType(int N, int type) { if (type <= 0) throw new IllegalArgumentException("Invalid return type: " + type); argReturnTypes[N] = type; } /** * Get the return type of the Nth argument * * @param argument * to get type for * @return Type of the argument */ public int getArgNReturnType(int N) { return argReturnTypes[N]; } public int computeSize() { int size = 1; for (int i = 0; i < numArgs; i++) { size += args[i].computeSize(); } return size; } public int traceDepth(int curDepth) { int retDepth = 0; int maxDepth = 0; for (int i = 0; i < numArgs; i++) { retDepth = args[i].traceDepth(getDepth()); if (retDepth > maxDepth) { maxDepth = retDepth; } } return maxDepth + 1; } public int computeDepth(int curDepth) { setDepth(curDepth + 1); int retDepth = 0; int maxDepth = 0; for (int i = 0; i < numArgs; i++) { retDepth = args[i].computeDepth(getDepth()); if (retDepth > maxDepth) { maxDepth = retDepth; } } return maxDepth + 1; } public void addTreeToVector(List<Node> list) { list.add(this); for (int i = 0; i < numArgs; i++) { args[i].addTreeToVector(list); } } public void addTreeToVector(List<Node> list, int typeNum) { if (getReturnType() == typeNum) list.add(this); for (int i = 0; i < numArgs; i++) { args[i].addTreeToVector(list, typeNum); } } /** * Append a String representing yourself to the StringBuilder passed in. * This allows a program to be saved to a String. Functions are printed in * prefix notation Brackets are used to show which function has which * children. A function foo with n children would be printed as (foo * child<SUB>0</SUB> ... child<SUB>n</SUB>) * */ public void print(StringBuilder s) { s.append(" ( "); s.append(getName()); for (int i = 0; i < numArgs; i++) { s.append(" "); args[i].print(s); } s.append(" ) "); } /** * Set child at position i to be null * * @param i * position to set to null */ public void unhook(int i) { args[i] = null; } /** * Set all children to null * */ public void unhook() { for (int i = 0; i < numArgs; i++) { args[i] = null; } } public int computePositions(int parent) { int pos = parent + 1; this.setPosition(pos); for (int i = 0; i < args.length; i++) { pos = args[i].computePositions(pos); } return pos; } public Node getNode(int node) { if (this.getPosition() == node) { return this; } for (int i = 0; i < args.length; i++) { Node n = args[i].getNode(node); if (n != null) { return n; } } return null; } public Node getNode(int node, int type, Node best) { // if you are it return yourself if (this.getReturnType() == type && this.getPosition() == node) { return this; } // if you are the best so far, nominate yourself if (this.getReturnType() == type && (best == null || Math.abs(best.getPosition() - node) > Math .abs(this.getPosition() - node))) { best = this; } // Check to make sure your children aren't it for (int i = 0; i < args.length; i++) { best = args[i].getNode(node, type, best); + if(best == null) continue; if (best.getPosition() == node || (i < args.length - 1 && args[i + 1].getPosition() > node && Math .abs(best.getPosition() - node) < Math .abs(args[i + 1].getPosition() - node))) { // can't get any better by searching return best; } } return best; } @Override public final Function copy(GPConfig conf) { Function a = NodeFactory.newNode(this, conf); a.init(this); for (int i = 0; i < getNumArgs(); i++) { a.setArgN(i, getArgN(i).copy(conf)); } return a; } @SuppressWarnings("unchecked") public Function generate(String s, GPConfig conf) { return NodeFactory.newNode(this, conf); } @SuppressWarnings("unchecked") public Function generate(GPConfig conf) { return NodeFactory.newNode(this, conf); } }
true
true
public Node getNode(int node, int type, Node best) { // if you are it return yourself if (this.getReturnType() == type && this.getPosition() == node) { return this; } // if you are the best so far, nominate yourself if (this.getReturnType() == type && (best == null || Math.abs(best.getPosition() - node) > Math .abs(this.getPosition() - node))) { best = this; } // Check to make sure your children aren't it for (int i = 0; i < args.length; i++) { best = args[i].getNode(node, type, best); if (best.getPosition() == node || (i < args.length - 1 && args[i + 1].getPosition() > node && Math .abs(best.getPosition() - node) < Math .abs(args[i + 1].getPosition() - node))) { // can't get any better by searching return best; } } return best; }
public Node getNode(int node, int type, Node best) { // if you are it return yourself if (this.getReturnType() == type && this.getPosition() == node) { return this; } // if you are the best so far, nominate yourself if (this.getReturnType() == type && (best == null || Math.abs(best.getPosition() - node) > Math .abs(this.getPosition() - node))) { best = this; } // Check to make sure your children aren't it for (int i = 0; i < args.length; i++) { best = args[i].getNode(node, type, best); if(best == null) continue; if (best.getPosition() == node || (i < args.length - 1 && args[i + 1].getPosition() > node && Math .abs(best.getPosition() - node) < Math .abs(args[i + 1].getPosition() - node))) { // can't get any better by searching return best; } } return best; }
diff --git a/test/com/xtremelabs/droidsugar/fakes/ListViewTest.java b/test/com/xtremelabs/droidsugar/fakes/ListViewTest.java index 33642ac8..b78c3ba8 100644 --- a/test/com/xtremelabs/droidsugar/fakes/ListViewTest.java +++ b/test/com/xtremelabs/droidsugar/fakes/ListViewTest.java @@ -1,68 +1,69 @@ package com.xtremelabs.droidsugar.fakes; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.xtremelabs.droidsugar.DroidSugarAndroidTestRunner; import com.xtremelabs.droidsugar.util.TestUtil; import com.xtremelabs.droidsugar.util.Transcript; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DroidSugarAndroidTestRunner.class) public class ListViewTest { private Transcript transcript; private ListView listView; @Before public void setUp() throws Exception { TestUtil.addAllProxies(); transcript = new Transcript(); listView = new ListView(null); } @Test public void testSetSelection_ShouldFireOnItemSelectedListener() throws Exception { listView.setAdapter(new CountingAdapter(1)); FakeHandler.flush(); listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { transcript.add("item was selected: " + position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); listView.setSelection(0); + FakeHandler.flush(); transcript.assertEventsSoFar("item was selected: 0"); } @Test public void testPerformItemClick_ShouldFireOnItemClickListener() throws Exception { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { transcript.add("item was clicked: " + position); } }); listView.performItemClick(null, 0, -1); transcript.assertEventsSoFar("item was clicked: 0"); } @Test public void testSetSelection_WhenNoItemSelectedListenerIsSet_ShouldDoNothing() throws Exception { listView.setSelection(0); } @Test public void shouldHaveAdapterViewCommonBehavior() throws Exception { AdapterViewBehavior.shouldActAsAdapterView(listView); } }
true
true
public void testSetSelection_ShouldFireOnItemSelectedListener() throws Exception { listView.setAdapter(new CountingAdapter(1)); FakeHandler.flush(); listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { transcript.add("item was selected: " + position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); listView.setSelection(0); transcript.assertEventsSoFar("item was selected: 0"); }
public void testSetSelection_ShouldFireOnItemSelectedListener() throws Exception { listView.setAdapter(new CountingAdapter(1)); FakeHandler.flush(); listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { transcript.add("item was selected: " + position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); listView.setSelection(0); FakeHandler.flush(); transcript.assertEventsSoFar("item was selected: 0"); }
diff --git a/MODSRC/vazkii/tinkerer/common/item/kami/foci/ItemFocusXPDrain.java b/MODSRC/vazkii/tinkerer/common/item/kami/foci/ItemFocusXPDrain.java index e4076bc6..89d4d1b3 100644 --- a/MODSRC/vazkii/tinkerer/common/item/kami/foci/ItemFocusXPDrain.java +++ b/MODSRC/vazkii/tinkerer/common/item/kami/foci/ItemFocusXPDrain.java @@ -1,101 +1,101 @@ package vazkii.tinkerer.common.item.kami.foci; import java.awt.Color; import java.util.List; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumRarity; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumcraft.common.config.Config; import thaumcraft.common.items.wands.ItemWandCasting; import vazkii.tinkerer.client.core.proxy.TTClientProxy; import vazkii.tinkerer.common.ThaumicTinkerer; import vazkii.tinkerer.common.core.helper.ExperienceHelper; import vazkii.tinkerer.common.item.foci.ItemModFocus; public class ItemFocusXPDrain extends ItemModFocus { AspectList cost = new AspectList(); private int lastGiven = 0; public ItemFocusXPDrain(int par1) { super(par1); } @Override public boolean isVisCostPerTick() { return true; } @Override public void onUsingFocusTick(ItemStack paramItemStack, EntityPlayer paramEntityPlayer, int paramInt) { if(paramEntityPlayer.worldObj.isRemote) return; ItemWandCasting wand = (ItemWandCasting) paramItemStack.getItem(); AspectList aspects = wand.getAllVis(paramItemStack); Aspect aspectToAdd = null; int takes = 0; while(aspectToAdd == null) { lastGiven = lastGiven == 5 ? 0 : lastGiven + 1; Aspect aspect = Aspect.getPrimalAspects().get(lastGiven); if(aspects.getAmount(aspect) < wand.getMaxVis(paramItemStack)) aspectToAdd = aspect; ++takes; if(takes == 7) return; } int xpUse = getXpUse(paramItemStack); if(paramEntityPlayer.experienceTotal >= xpUse) { ExperienceHelper.drainPlayerXP(paramEntityPlayer, xpUse); - wand.storeVis(paramItemStack, aspectToAdd, wand.getVis(paramItemStack, aspectToAdd) + 500); + wand.storeVis(paramItemStack, aspectToAdd, Math.min(wand.getMaxVis(paramItemStack), wand.getVis(paramItemStack, aspectToAdd) + 500)); } } @Override public int getColorFromItemStack(ItemStack par1ItemStack, int par2) { return getFocusColor(); } @Override public int getFocusColor() { EntityPlayer player = ThaumicTinkerer.proxy.getClientPlayer(); return player == null ? 0xFFFFFF : Color.HSBtoRGB(player.ticksExisted * 2 % 360 / 360F, 1F, 1F); } int getXpUse(ItemStack stack) { return 30 - EnchantmentHelper.getEnchantmentLevel(Config.enchFrugal.effectId, stack) * 3; } @Override protected void addVisCostTooltip(AspectList cost, ItemStack stack, EntityPlayer player, List list, boolean par4) { list.add(" " + EnumChatFormatting.GREEN + StatCollector.translateToLocal("ttmisc.experience") + EnumChatFormatting.WHITE + " x " + getXpUse(stack)); } @Override public AspectList getVisCost() { return cost; } @Override public EnumRarity getRarity(ItemStack par1ItemStack) { return TTClientProxy.kamiRarity; } @Override public boolean acceptsEnchant(int paramInt) { return paramInt == Config.enchFrugal.effectId; } }
true
true
public void onUsingFocusTick(ItemStack paramItemStack, EntityPlayer paramEntityPlayer, int paramInt) { if(paramEntityPlayer.worldObj.isRemote) return; ItemWandCasting wand = (ItemWandCasting) paramItemStack.getItem(); AspectList aspects = wand.getAllVis(paramItemStack); Aspect aspectToAdd = null; int takes = 0; while(aspectToAdd == null) { lastGiven = lastGiven == 5 ? 0 : lastGiven + 1; Aspect aspect = Aspect.getPrimalAspects().get(lastGiven); if(aspects.getAmount(aspect) < wand.getMaxVis(paramItemStack)) aspectToAdd = aspect; ++takes; if(takes == 7) return; } int xpUse = getXpUse(paramItemStack); if(paramEntityPlayer.experienceTotal >= xpUse) { ExperienceHelper.drainPlayerXP(paramEntityPlayer, xpUse); wand.storeVis(paramItemStack, aspectToAdd, wand.getVis(paramItemStack, aspectToAdd) + 500); } }
public void onUsingFocusTick(ItemStack paramItemStack, EntityPlayer paramEntityPlayer, int paramInt) { if(paramEntityPlayer.worldObj.isRemote) return; ItemWandCasting wand = (ItemWandCasting) paramItemStack.getItem(); AspectList aspects = wand.getAllVis(paramItemStack); Aspect aspectToAdd = null; int takes = 0; while(aspectToAdd == null) { lastGiven = lastGiven == 5 ? 0 : lastGiven + 1; Aspect aspect = Aspect.getPrimalAspects().get(lastGiven); if(aspects.getAmount(aspect) < wand.getMaxVis(paramItemStack)) aspectToAdd = aspect; ++takes; if(takes == 7) return; } int xpUse = getXpUse(paramItemStack); if(paramEntityPlayer.experienceTotal >= xpUse) { ExperienceHelper.drainPlayerXP(paramEntityPlayer, xpUse); wand.storeVis(paramItemStack, aspectToAdd, Math.min(wand.getMaxVis(paramItemStack), wand.getVis(paramItemStack, aspectToAdd) + 500)); } }
diff --git a/src/pt/ist/fenixframework/plugins/luceneIndexing/domain/DomainIndexDirectory.java b/src/pt/ist/fenixframework/plugins/luceneIndexing/domain/DomainIndexDirectory.java index 6cb90ee0..76170c78 100644 --- a/src/pt/ist/fenixframework/plugins/luceneIndexing/domain/DomainIndexDirectory.java +++ b/src/pt/ist/fenixframework/plugins/luceneIndexing/domain/DomainIndexDirectory.java @@ -1,40 +1,40 @@ package pt.ist.fenixframework.plugins.luceneIndexing.domain; public class DomainIndexDirectory extends DomainIndexDirectory_Base { public DomainIndexDirectory(String name) { super(); setPluginRoot(LuceneSearchPluginRoot.getInstance()); setIndexForClass(name); } public DomainIndexFile getIndexFile(String name) { for (DomainIndexFile file : getIndexFiles()) { - if (file.getName().equals(name)) { + if (file.getName().equals(name) && file.getIndexContent() != null) { return file; } } return null; } public static DomainIndexDirectory getIndexDirectory(String name) { for (DomainIndexDirectory directory : LuceneSearchPluginRoot.getInstance().getDomainIndexDirectories()) { if (directory.getIndexForClass().equals(name)) { return directory; } } return null; } public static DomainIndexDirectory createNewIndexDirectory(String name) { return new DomainIndexDirectory(name); } public void delete() { for (DomainIndexFile file : getIndexFilesSet()) { file.delete(); } removePluginRoot(); deleteDomainObject(); } }
true
true
public DomainIndexFile getIndexFile(String name) { for (DomainIndexFile file : getIndexFiles()) { if (file.getName().equals(name)) { return file; } } return null; }
public DomainIndexFile getIndexFile(String name) { for (DomainIndexFile file : getIndexFiles()) { if (file.getName().equals(name) && file.getIndexContent() != null) { return file; } } return null; }
diff --git a/capture-server/capture/Url.java b/capture-server/capture/Url.java index 62254a4..e1d135a 100644 --- a/capture-server/capture/Url.java +++ b/capture-server/capture/Url.java @@ -1,299 +1,300 @@ package capture; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Observable; import java.util.regex.Matcher; enum URL_STATE { NONE, QUEUED, VISITING, VISITED, ERROR } public class Url extends Observable { private URI url; private String clientProgram; private int visitTime; private ERROR_CODES majorErrorCode = ERROR_CODES.OK; private long minorErrorCode; private Boolean malicious; private URL_STATE urlState; private Date visitStartTime; private Date visitFinishTime; private String logFileDate; private Date firstStateChange; private BufferedWriter logFile; private long groupID; private boolean initialGroup; //0.0 low //1.0 high public double getPriority() { return priority; } private double priority; public Url(String u, String cProgram, int vTime, double priority) throws URISyntaxException { url = new URI(u); this.priority = priority; malicious = null; if (cProgram == null || cProgram == "") { clientProgram = ConfigManager.getInstance().getConfigOption("client-default"); } else { clientProgram = cProgram; } visitTime = vTime; urlState = URL_STATE.NONE; } public void setVisitStartTime(String visitStartTime) { try { SimpleDateFormat sf = new SimpleDateFormat("d/M/yyyy H:m:s.S"); this.visitStartTime = sf.parse(visitStartTime); } catch (ParseException e) { e.printStackTrace(System.out); } } public void setGroupId(long groupID) { this.groupID = groupID; } public String getVisitStartTime() { SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S"); return sf.format(visitStartTime); } public void setVisitFinishTime(String visitFinishTime) { try { SimpleDateFormat sf = new SimpleDateFormat("d/M/yyyy H:m:s.S"); this.visitFinishTime = sf.parse(visitFinishTime); } catch (ParseException e) { e.printStackTrace(System.out); } } public String getVisitFinishTime() { SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S"); if (visitFinishTime != null) return sf.format(visitFinishTime); else return sf.format(new Date()); } private String getLogfileDate(long time) { SimpleDateFormat sf = new SimpleDateFormat("ddMMyyyy_HHmmss"); return sf.format(new Date(time)); } public void writeEventToLog(String event) { try { if (logFile == null) { String logFileName = filenameEscape(url.toString()) + "_" + this.getLogfileDate(visitStartTime.getTime()); logFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("log" + File.separator + logFileName + ".log"), "UTF-8")); } if (firstStateChange == null) { String[] result = event.split("\",\""); String firstStateChangeStr = result[1]; SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S"); firstStateChange = sf.parse(firstStateChangeStr); } setMalicious(true); logFile.write(event); logFile.flush(); } catch (UnsupportedEncodingException e) { e.printStackTrace(System.out); } catch (IOException e) { e.printStackTrace(System.out); } catch (ParseException e) { e.printStackTrace(System.out); } } public void closeEventLog() { try { if (logFile != null) { logFile.close(); } } catch (IOException e) { e.printStackTrace(System.out); } } public boolean isMalicious() { return malicious; } public void setMalicious(boolean malicious) { this.malicious = malicious; } public URL_STATE getUrlState() { return urlState; } public void setUrlState(URL_STATE newState) { if (urlState == newState) return; urlState = newState; System.out.println("\tUrlSetState: " + newState.toString()); if (urlState == URL_STATE.VISITING) { String date = getVisitStartTime(); Stats.visiting++; Logger.getInstance().writeToProgressLog("\"" + date + "\",\"visiting\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } else if (urlState == URL_STATE.VISITED) { String date = getVisitFinishTime(); Logger.getInstance().writeToProgressLog("\"" + date + "\",\"visited\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); Stats.visited++; Stats.addUrlVisitingTime(visitStartTime, visitFinishTime, visitTime); if (this.malicious != null && this.malicious) { Stats.malicious++; Stats.addFirstStateChangeTime(firstStateChange, visitFinishTime, visitTime); Logger.getInstance().writeToMaliciousUrlLog("\"" + date + "\",\"malicious\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } else if (this.malicious != null && !this.malicious) { Stats.safe++; Logger.getInstance().writeToSafeUrlLog("\"" + date + "\",\"benign\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } closeEventLog(); } else if (urlState == URL_STATE.ERROR) { if (this.malicious != null) { if (this.malicious) { Stats.malicious++; - String date = DateFormat.getDateTimeInstance().format(new Date()); + SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S"); + String date = sf.format(new Date()); if(firstStateChange!=null && visitFinishTime != null) {//could happen when VM is stalled. since the tim can't be calculated correctly, we skip this one for this URL Stats.addFirstStateChangeTime(firstStateChange, visitFinishTime, visitTime); } Logger.getInstance().writeToMaliciousUrlLog("\"" + date + "\",\"malicious\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } //logged in error group even if group size is larger, because these URL String finishDate = getVisitFinishTime(); Logger.getInstance().writeToProgressLog("\"" + finishDate + "\",\"error" + ":" + majorErrorCode + "-" + minorErrorCode + "\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); Stats.urlError++; } closeEventLog(); } this.setChanged(); this.notifyObservers(); } public int getVisitTime() { return visitTime; } public String getClientProgram() { return clientProgram; } public String getEscapedUrl() { try { return URLEncoder.encode(url.toString(), "UTF-8").toLowerCase(); } catch (UnsupportedEncodingException e) { e.printStackTrace(System.out); return ""; } } public String getUrl() { return url.toString().toLowerCase(); } private String filenameEscape(String text) { String escaped; escaped = text; escaped = escaped.replaceAll("\\\\", "%5C"); escaped = escaped.replaceAll("/", "%2F"); escaped = escaped.replaceAll(":", "%3A"); escaped = escaped.replaceAll("\\?", "%3F"); escaped = escaped.replaceAll("\"", "%22"); escaped = escaped.replaceAll("\\*", "%2A"); escaped = escaped.replaceAll("<", "%3C"); escaped = escaped.replaceAll(">", "%3E"); escaped = escaped.replaceAll("\\|", "%7C"); escaped = escaped.replaceAll("&", "%26"); return escaped; } public String getUrlAsFileName() { return this.filenameEscape(this.getUrl()) + "_" + this.getLogfileDate(visitStartTime.getTime()); } public ERROR_CODES getMajorErrorCode() { if (majorErrorCode == null) { return ERROR_CODES.OK; } return majorErrorCode; } public void setMajorErrorCode(long majorErrorCode) { boolean validErrorCode = false; for (ERROR_CODES e : ERROR_CODES.values()) { if (majorErrorCode == e.errorCode) { validErrorCode = true; this.majorErrorCode = e; } } if (!validErrorCode) { System.out.println("Received invalid error code from client " + majorErrorCode); this.majorErrorCode = ERROR_CODES.INVALID_ERROR_CODE_FROM_CLIENT; } } public long getMinorErrorCode() { return minorErrorCode; } public void setMinorErrorCode(long minorErrorCode) { this.minorErrorCode = minorErrorCode; } public long getGroupID() { return groupID; } public void setInitialGroup(boolean initialGroup) { this.initialGroup = initialGroup; } public boolean isInitialGroup() { return initialGroup; } }
true
true
public void setUrlState(URL_STATE newState) { if (urlState == newState) return; urlState = newState; System.out.println("\tUrlSetState: " + newState.toString()); if (urlState == URL_STATE.VISITING) { String date = getVisitStartTime(); Stats.visiting++; Logger.getInstance().writeToProgressLog("\"" + date + "\",\"visiting\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } else if (urlState == URL_STATE.VISITED) { String date = getVisitFinishTime(); Logger.getInstance().writeToProgressLog("\"" + date + "\",\"visited\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); Stats.visited++; Stats.addUrlVisitingTime(visitStartTime, visitFinishTime, visitTime); if (this.malicious != null && this.malicious) { Stats.malicious++; Stats.addFirstStateChangeTime(firstStateChange, visitFinishTime, visitTime); Logger.getInstance().writeToMaliciousUrlLog("\"" + date + "\",\"malicious\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } else if (this.malicious != null && !this.malicious) { Stats.safe++; Logger.getInstance().writeToSafeUrlLog("\"" + date + "\",\"benign\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } closeEventLog(); } else if (urlState == URL_STATE.ERROR) { if (this.malicious != null) { if (this.malicious) { Stats.malicious++; String date = DateFormat.getDateTimeInstance().format(new Date()); if(firstStateChange!=null && visitFinishTime != null) {//could happen when VM is stalled. since the tim can't be calculated correctly, we skip this one for this URL Stats.addFirstStateChangeTime(firstStateChange, visitFinishTime, visitTime); } Logger.getInstance().writeToMaliciousUrlLog("\"" + date + "\",\"malicious\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } //logged in error group even if group size is larger, because these URL String finishDate = getVisitFinishTime(); Logger.getInstance().writeToProgressLog("\"" + finishDate + "\",\"error" + ":" + majorErrorCode + "-" + minorErrorCode + "\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); Stats.urlError++; } closeEventLog(); } this.setChanged(); this.notifyObservers(); }
public void setUrlState(URL_STATE newState) { if (urlState == newState) return; urlState = newState; System.out.println("\tUrlSetState: " + newState.toString()); if (urlState == URL_STATE.VISITING) { String date = getVisitStartTime(); Stats.visiting++; Logger.getInstance().writeToProgressLog("\"" + date + "\",\"visiting\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } else if (urlState == URL_STATE.VISITED) { String date = getVisitFinishTime(); Logger.getInstance().writeToProgressLog("\"" + date + "\",\"visited\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); Stats.visited++; Stats.addUrlVisitingTime(visitStartTime, visitFinishTime, visitTime); if (this.malicious != null && this.malicious) { Stats.malicious++; Stats.addFirstStateChangeTime(firstStateChange, visitFinishTime, visitTime); Logger.getInstance().writeToMaliciousUrlLog("\"" + date + "\",\"malicious\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } else if (this.malicious != null && !this.malicious) { Stats.safe++; Logger.getInstance().writeToSafeUrlLog("\"" + date + "\",\"benign\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } closeEventLog(); } else if (urlState == URL_STATE.ERROR) { if (this.malicious != null) { if (this.malicious) { Stats.malicious++; SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S"); String date = sf.format(new Date()); if(firstStateChange!=null && visitFinishTime != null) {//could happen when VM is stalled. since the tim can't be calculated correctly, we skip this one for this URL Stats.addFirstStateChangeTime(firstStateChange, visitFinishTime, visitTime); } Logger.getInstance().writeToMaliciousUrlLog("\"" + date + "\",\"malicious\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); } //logged in error group even if group size is larger, because these URL String finishDate = getVisitFinishTime(); Logger.getInstance().writeToProgressLog("\"" + finishDate + "\",\"error" + ":" + majorErrorCode + "-" + minorErrorCode + "\",\"" + groupID + "\",\"" + url + "\",\"" + clientProgram + "\",\"" + visitTime + "\""); Stats.urlError++; } closeEventLog(); } this.setChanged(); this.notifyObservers(); }
diff --git a/src/com/podevs/android/pokemononline/pokeinfo/MoveInfo.java b/src/com/podevs/android/pokemononline/pokeinfo/MoveInfo.java index a18f71d3..9940f4c6 100644 --- a/src/com/podevs/android/pokemononline/pokeinfo/MoveInfo.java +++ b/src/com/podevs/android/pokemononline/pokeinfo/MoveInfo.java @@ -1,20 +1,20 @@ package com.podevs.android.pokemononline.pokeinfo; import android.util.SparseArray; import com.podevs.android.pokemononline.DataBaseHelper; public class MoveInfo { private static SparseArray<String> moveNames = new SparseArray<String>(); public static String name(DataBaseHelper db, int num) { - if (moveNames.indexOfKey(num) != -1) { + if (moveNames.indexOfKey(num) >= 0) { return moveNames.get(num); } - String name = db.query("SELECT name FROM [moves] WHERE _id = " + num); + String name = db.query("SELECT name FROM [Moves] WHERE _id = " + num); moveNames.put(num, name); return name; } }
false
true
public static String name(DataBaseHelper db, int num) { if (moveNames.indexOfKey(num) != -1) { return moveNames.get(num); } String name = db.query("SELECT name FROM [moves] WHERE _id = " + num); moveNames.put(num, name); return name; }
public static String name(DataBaseHelper db, int num) { if (moveNames.indexOfKey(num) >= 0) { return moveNames.get(num); } String name = db.query("SELECT name FROM [Moves] WHERE _id = " + num); moveNames.put(num, name); return name; }
diff --git a/src/main/java/com/philihp/weblabora/model/building/PrintingOffice.java b/src/main/java/com/philihp/weblabora/model/building/PrintingOffice.java index 795e11e..1efa6e4 100644 --- a/src/main/java/com/philihp/weblabora/model/building/PrintingOffice.java +++ b/src/main/java/com/philihp/weblabora/model/building/PrintingOffice.java @@ -1,45 +1,46 @@ package com.philihp.weblabora.model.building; import static com.philihp.weblabora.model.TerrainTypeEnum.COAST; import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE; import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS; import java.util.EnumSet; import com.philihp.weblabora.model.Board; import com.philihp.weblabora.model.BuildCost; import com.philihp.weblabora.model.Coordinate; import com.philihp.weblabora.model.Landscape; import com.philihp.weblabora.model.Player; import com.philihp.weblabora.model.SettlementRound; import com.philihp.weblabora.model.Terrain; import com.philihp.weblabora.model.TerrainUseEnum; import com.philihp.weblabora.model.UsageParamCoordinates; import com.philihp.weblabora.model.WeblaboraException; public class PrintingOffice extends BuildingCoordinateUsage { public PrintingOffice() { super("F38", SettlementRound.D, 1, "Printing Office", BuildCost.is().wood(1).stone(2), 5, 5, EnumSet.of(PLAINS, HILLSIDE, COAST), false); } @Override public void use(Board board, UsageParamCoordinates input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Landscape landscape = player.getLandscape(); for(Coordinate coord : input.getCoordinates()) { Terrain terrain = landscape.getTerrainAt(coord); if(terrain == null) { throw new WeblaboraException(getName()+" is trying to clear forest at "+coord+" which doesn't belong to landscape"); } else if(terrain.getTerrainUse() == TerrainUseEnum.FOREST) { player.addBooks(1); terrain.setTerrainType(PLAINS); + terrain.setTerrainUse(TerrainUseEnum.EMPTY); } else throw new WeblaboraException(getName()+" is trying to clear forest at "+coord+" but found "+terrain.getTerrainUse()); } } }
true
true
public void use(Board board, UsageParamCoordinates input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Landscape landscape = player.getLandscape(); for(Coordinate coord : input.getCoordinates()) { Terrain terrain = landscape.getTerrainAt(coord); if(terrain == null) { throw new WeblaboraException(getName()+" is trying to clear forest at "+coord+" which doesn't belong to landscape"); } else if(terrain.getTerrainUse() == TerrainUseEnum.FOREST) { player.addBooks(1); terrain.setTerrainType(PLAINS); } else throw new WeblaboraException(getName()+" is trying to clear forest at "+coord+" but found "+terrain.getTerrainUse()); } }
public void use(Board board, UsageParamCoordinates input) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); Landscape landscape = player.getLandscape(); for(Coordinate coord : input.getCoordinates()) { Terrain terrain = landscape.getTerrainAt(coord); if(terrain == null) { throw new WeblaboraException(getName()+" is trying to clear forest at "+coord+" which doesn't belong to landscape"); } else if(terrain.getTerrainUse() == TerrainUseEnum.FOREST) { player.addBooks(1); terrain.setTerrainType(PLAINS); terrain.setTerrainUse(TerrainUseEnum.EMPTY); } else throw new WeblaboraException(getName()+" is trying to clear forest at "+coord+" but found "+terrain.getTerrainUse()); } }
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java index 03bc8c008..7600dafda 100644 --- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java +++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java @@ -1,402 +1,405 @@ /******************************************************************************* * Copyright (c) 2007 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Martin Oberhuber (Wind River) - initial API and implementation *******************************************************************************/ package org.eclipse.core.tests.filesystem; import java.io.*; import org.eclipse.core.filesystem.*; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; /** * */ public class SymlinkTest extends FileSystemTest { private static String specialCharName = "���� ��� ���� �����"; //$NON-NLS-1$ protected IFileStore aDir, aFile; //actual Dir, File protected IFileInfo iDir, iFile, ilDir, ilFile, illDir, illFile; protected IFileStore lDir, lFile; //symlink to Dir, File protected IFileStore llDir, llFile; //link to link to Dir, File public static IFileSystem getFileSystem() { try { return EFS.getFileSystem(EFS.SCHEME_FILE); } catch (CoreException e) { fail("getFileSystem", e); } return null; } public static IWorkspace getWorkspace() { return ResourcesPlugin.getWorkspace(); } public static boolean isTestablePlatform() { // A Platform is testable if it supports the "ln -s" command. String os = Platform.getOS(); //currently we only support linux if (os.equals(Platform.OS_LINUX) // ||os.equals(Platform.OS_AIX) // ||os.equals(Platform.OS_HPUX) // ||os.equals(Platform.OS_SOLARIS) // ||isWindowsVista() ) { return true; } return false; } public static boolean isWindowsVista() { return Platform.getOS().equals(Platform.OS_WIN32) && "6.0".equals(System.getProperty("org.osgi.framework.os.version")); //$NON-NLS-1$ //$NON-NLS-2$ } protected void fetchFileInfos() { iDir = aDir.fetchInfo(); iFile = aFile.fetchInfo(); ilDir = lDir.fetchInfo(); ilFile = lFile.fetchInfo(); illDir = llDir.fetchInfo(); illFile = llFile.fetchInfo(); } public boolean haveSymlinks() { return (getFileSystem().attributes() & EFS.ATTRIBUTE_SYMLINK) != 0; } protected void makeLinkStructure() { aDir = baseStore.getChild("aDir"); aFile = baseStore.getChild("aFile"); lDir = baseStore.getChild("lDir"); lFile = baseStore.getChild("lFile"); llDir = baseStore.getChild("llDir"); llFile = baseStore.getChild("llFile"); ensureExists(aDir, true); ensureExists(aFile, false); mkLink(baseStore, "lDir", "aDir", true); mkLink(baseStore, "llDir", "lDir", true); mkLink(baseStore, "lFile", "aFile", false); mkLink(baseStore, "llFile", "lFile", false); fetchFileInfos(); } protected void mkLink(IFileStore dir, String src, String tgt, boolean isDir) { String[] envp = {}; try { Process p; File basedir = baseStore.toLocalFile(EFS.NONE, getMonitor()); if (isWindowsVista()) { if (isDir) { String[] cmd = {"mklink", "/d", src, tgt}; p = Runtime.getRuntime().exec(cmd, envp, basedir); } else { String[] cmd = {"mklink", src, tgt}; p = Runtime.getRuntime().exec(cmd, envp, basedir); } } else { String[] cmd = {"ln", "-s", tgt, src}; p = Runtime.getRuntime().exec(cmd, envp, basedir); } int exitcode = p.waitFor(); assertEquals(exitcode, 0); } catch (IOException e) { fail("mkLink", e); } catch (CoreException e) { fail("mkLink", e); } catch (InterruptedException e) { fail("mkLink", e); } } protected void setUp() throws Exception { baseStore = getFileSystem().getStore(getWorkspace().getRoot().getLocation().append("temp")); baseStore.mkdir(EFS.NONE, null); } protected void tearDown() throws Exception { baseStore.delete(EFS.NONE, null); } public void testBrokenSymlinkAttributes() { if (!isTestablePlatform()) { return; } makeLinkStructure(); //break links by removing actual dir and file ensureDoesNotExist(aDir); ensureDoesNotExist(aFile); fetchFileInfos(); assertFalse(ilFile.exists()); assertFalse(ilFile.isDirectory()); assertFalse(illFile.exists()); assertFalse(illFile.isDirectory()); assertFalse(ilDir.exists()); assertFalse(ilDir.isDirectory()); assertFalse(illDir.exists()); assertFalse(illDir.isDirectory()); assertEquals(ilFile.getLastModified(), 0); assertEquals(ilFile.getLength(), 0); assertEquals(ilDir.getLastModified(), 0); assertEquals(ilDir.getLength(), 0); assertEquals(illFile.getLastModified(), 0); assertEquals(illFile.getLength(), 0); assertEquals(illDir.getLastModified(), 0); assertEquals(illDir.getLength(), 0); if (haveSymlinks()) { assertTrue(ilFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(ilFile.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "aFile"); assertTrue(ilDir.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(ilDir.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "aDir"); assertTrue(illFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(illFile.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lFile"); assertTrue(illDir.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(illDir.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lDir"); } } public void testBrokenSymlinkRemove() throws Exception { //removing a broken symlink is possible if (!isTestablePlatform()) { return; } makeLinkStructure(); ensureDoesNotExist(aFile); ensureDoesNotExist(aDir); IFileInfo[] infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 4); llFile.delete(EFS.NONE, getMonitor()); llDir.delete(EFS.NONE, getMonitor()); infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 2); lFile.delete(EFS.NONE, getMonitor()); lDir.delete(EFS.NONE, getMonitor()); infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 0); } public void testRecursiveSymlink() throws Exception { if (!isTestablePlatform()) return; mkLink(baseStore, "l1", "l2", false); mkLink(baseStore, "l2", "l1", false); IFileStore l1 = baseStore.getChild("l1"); IFileInfo i1 = l1.fetchInfo(); assertFalse(i1.exists()); assertFalse(i1.isDirectory()); if (haveSymlinks()) { assertTrue(i1.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals("l2", i1.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET)); } IFileInfo[] infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 2); i1.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true); boolean exceptionThrown = false; try { l1.putInfo(i1, EFS.SET_ATTRIBUTES, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } i1 = l1.fetchInfo(); - //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links - //assertTrue(exceptionThrown); - //assertTrue(i1.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); + boolean fixMeFixed = false; + if (fixMeFixed) { + //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links + assertTrue(exceptionThrown); + assertTrue(i1.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); + } assertFalse(i1.exists()); i1.setLastModified(12345); exceptionThrown = false; try { l1.putInfo(i1, EFS.SET_LAST_MODIFIED, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } i1 = l1.fetchInfo(); //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links //assertTrue(exceptionThrown); //assertEquals(i1.getLastModified(), 12345); assertFalse(i1.exists()); l1.delete(EFS.NONE, getMonitor()); infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 1); } public void testSymlinkAttributes() { if (!isTestablePlatform()) { return; } makeLinkStructure(); assertFalse(iFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertFalse(iDir.getAttribute(EFS.ATTRIBUTE_SYMLINK)); //valid links assertTrue(ilFile.exists()); assertFalse(ilFile.isDirectory()); assertTrue(illFile.exists()); assertFalse(illFile.isDirectory()); assertTrue(ilDir.exists()); assertTrue(ilDir.isDirectory()); assertTrue(illDir.exists()); assertTrue(illDir.isDirectory()); assertEquals(iFile.getLastModified(), illFile.getLastModified()); assertEquals(iFile.getLength(), illFile.getLength()); assertEquals(iDir.getLastModified(), illDir.getLastModified()); assertEquals(iDir.getLength(), illDir.getLength()); if (haveSymlinks()) { assertTrue(ilFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(ilFile.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "aFile"); assertTrue(ilDir.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(ilDir.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "aDir"); assertTrue(illFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(illFile.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lFile"); assertTrue(illDir.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(illDir.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lDir"); } } public void testSymlinkDirRead() throws Exception { //reading from a directory pointed to by a link is possible if (!isTestablePlatform()) { return; } makeLinkStructure(); IFileStore childDir = aDir.getChild("subDir"); ensureExists(childDir, true); IFileInfo[] infos = llDir.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 1); assertTrue(infos[0].isDirectory()); assertFalse(infos[0].getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertNull(infos[0].getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET)); assertEquals(infos[0].getName(), "subDir"); ensureDoesNotExist(childDir); } public void testSymlinkDirWrite() throws Exception { //writing to symlinked dir if (!isTestablePlatform()) { return; } makeLinkStructure(); IFileStore childFile = llDir.getChild("subFile"); ensureExists(childFile, false); IFileInfo[] infos = aDir.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 1); assertFalse(infos[0].isDirectory()); assertFalse(infos[0].getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertNull(infos[0].getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET)); assertEquals(infos[0].getName(), "subFile"); //writing to broken symlink ensureDoesNotExist(aDir); childFile = llDir.getChild("subFile"); OutputStream out = null; boolean exceptionThrown = false; try { out = childFile.openOutputStream(EFS.NONE, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } if (out != null) out.close(); assertNull(out); assertTrue(exceptionThrown); } public void testSymlinkEnabled() { if (Platform.OS_LINUX.equals(Platform.getOS())) { assertTrue(haveSymlinks()); } else { assertFalse(haveSymlinks()); } } public void testSymlinkExtendedChars() throws Exception { if (!isTestablePlatform()) return; IFileStore childDir = baseStore.getChild(specialCharName); ensureExists(childDir, true); IFileStore childFile = baseStore.getChild("ff" + specialCharName); ensureExists(childFile, false); mkLink(baseStore, "l" + specialCharName, specialCharName, true); mkLink(baseStore, "lf" + specialCharName, "ff" + specialCharName, false); IFileInfo[] infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 4); for (int i = 0; i < infos.length; i++) { assertTrue(infos[i].getName().endsWith(specialCharName)); assertTrue(infos[i].exists()); if (infos[i].getName().charAt(1) == 'f') { assertFalse(infos[i].isDirectory()); } else { assertTrue(infos[i].isDirectory()); } if (haveSymlinks() && infos[i].getName().charAt(0) == 'l') { assertTrue(infos[i].getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertTrue(infos[i].getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET).endsWith(specialCharName)); } } } public void testSymlinkPutInfo() throws Exception { if (!isTestablePlatform()) { return; } //check that putInfo() "writes through" the symlink makeLinkStructure(); long oldTime = iFile.getLastModified(); long timeToSet = oldTime - 100000; illFile.setLastModified(timeToSet); illFile.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true); llFile.putInfo(illFile, EFS.SET_ATTRIBUTES | EFS.SET_LAST_MODIFIED, getMonitor()); iFile = aFile.fetchInfo(); assertEquals(iFile.getLastModified(), timeToSet); assertTrue(iFile.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); oldTime = iDir.getLastModified(); timeToSet = oldTime - 100000; illDir.setLastModified(timeToSet); illDir.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true); llDir.putInfo(illDir, EFS.SET_ATTRIBUTES | EFS.SET_LAST_MODIFIED, getMonitor()); iDir = aDir.fetchInfo(); assertTrue(iDir.getLastModified() != oldTime); assertEquals(iDir.getLastModified(), timeToSet); assertTrue(iDir.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); if (haveSymlinks()) { //check that link properties are maintained even through putInfo illFile = llFile.fetchInfo(); illDir = llDir.fetchInfo(); assertTrue(illFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertTrue(illDir.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(illFile.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lFile"); assertEquals(illDir.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lDir"); } } public void testSymlinkRemove() throws Exception { //removing a symlink keeps the link target intact. //symlinks being broken due to remove are set to non-existant. if (!isTestablePlatform()) { return; } makeLinkStructure(); lFile.delete(EFS.NONE, getMonitor()); illFile = lFile.fetchInfo(); assertFalse(illFile.exists()); iFile = aFile.fetchInfo(); assertTrue(iFile.exists()); lDir.delete(EFS.NONE, getMonitor()); illDir = lDir.fetchInfo(); assertFalse(illFile.exists()); iDir = aDir.fetchInfo(); assertTrue(iDir.exists()); } }
true
true
public void testRecursiveSymlink() throws Exception { if (!isTestablePlatform()) return; mkLink(baseStore, "l1", "l2", false); mkLink(baseStore, "l2", "l1", false); IFileStore l1 = baseStore.getChild("l1"); IFileInfo i1 = l1.fetchInfo(); assertFalse(i1.exists()); assertFalse(i1.isDirectory()); if (haveSymlinks()) { assertTrue(i1.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals("l2", i1.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET)); } IFileInfo[] infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 2); i1.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true); boolean exceptionThrown = false; try { l1.putInfo(i1, EFS.SET_ATTRIBUTES, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } i1 = l1.fetchInfo(); //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links //assertTrue(exceptionThrown); //assertTrue(i1.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); assertFalse(i1.exists()); i1.setLastModified(12345); exceptionThrown = false; try { l1.putInfo(i1, EFS.SET_LAST_MODIFIED, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } i1 = l1.fetchInfo(); //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links //assertTrue(exceptionThrown); //assertEquals(i1.getLastModified(), 12345); assertFalse(i1.exists()); l1.delete(EFS.NONE, getMonitor()); infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 1); }
public void testRecursiveSymlink() throws Exception { if (!isTestablePlatform()) return; mkLink(baseStore, "l1", "l2", false); mkLink(baseStore, "l2", "l1", false); IFileStore l1 = baseStore.getChild("l1"); IFileInfo i1 = l1.fetchInfo(); assertFalse(i1.exists()); assertFalse(i1.isDirectory()); if (haveSymlinks()) { assertTrue(i1.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals("l2", i1.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET)); } IFileInfo[] infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 2); i1.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true); boolean exceptionThrown = false; try { l1.putInfo(i1, EFS.SET_ATTRIBUTES, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } i1 = l1.fetchInfo(); boolean fixMeFixed = false; if (fixMeFixed) { //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links assertTrue(exceptionThrown); assertTrue(i1.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); } assertFalse(i1.exists()); i1.setLastModified(12345); exceptionThrown = false; try { l1.putInfo(i1, EFS.SET_LAST_MODIFIED, getMonitor()); } catch (CoreException ce) { exceptionThrown = true; } i1 = l1.fetchInfo(); //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links //assertTrue(exceptionThrown); //assertEquals(i1.getLastModified(), 12345); assertFalse(i1.exists()); l1.delete(EFS.NONE, getMonitor()); infos = baseStore.childInfos(EFS.NONE, getMonitor()); assertEquals(infos.length, 1); }
diff --git a/src/com/dmdirc/parser/ProcessNick.java b/src/com/dmdirc/parser/ProcessNick.java index d42bcca7d..9d60226e8 100644 --- a/src/com/dmdirc/parser/ProcessNick.java +++ b/src/com/dmdirc/parser/ProcessNick.java @@ -1,133 +1,132 @@ /* * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * SVN: $Id$ */ package com.dmdirc.parser; import com.dmdirc.parser.callbacks.CallbackOnChannelNickChanged; import com.dmdirc.parser.callbacks.CallbackOnNickChanged; /** * Process a Nick change. */ public class ProcessNick extends IRCProcessor { /** * Process a Nick change. * * @param sParam Type of line to process ("NICK") * @param token IRCTokenised line to process */ public void process(String sParam, String[] token) { ClientInfo iClient; ChannelClientInfo iChannelClient; String oldNickname; iClient = getClientInfo(token[0]); if (iClient != null) { oldNickname = myParser.toLowerCase(iClient.getNickname()); // Remove the client from the known clients list final boolean isSameNick = myParser.equalsIgnoreCase(oldNickname, token[token.length-1]); if (!isSameNick) { myParser.forceRemoveClient(getClientInfo(oldNickname)); } // Change the nickame iClient.setUserBits(token[token.length-1],true); // Readd the client if (!isSameNick && myParser.getClientInfo(iClient.getNickname()) != null) { - myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, - "Nick change would overwrite existing client", myParser.getLastLine())); + myParser.onPostErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine()), false); } else { if (!isSameNick) { myParser.addClient(iClient); } for (ChannelInfo iChannel : myParser.getChannels()) { // Find the user (using the old nickname) iChannelClient = iChannel.getUser(oldNickname); if (iChannelClient != null) { // Rename them. This uses the old nickname (the key in the hashtable) // and the channelClient object has access to the new nickname (by way // of the ClientInfo object we updated above) if (!isSameNick) { iChannel.renameClient(oldNickname, iChannelClient); } callChannelNickChanged(iChannel,iChannelClient,ClientInfo.parseHost(token[0])); } } callNickChanged(iClient, ClientInfo.parseHost(token[0])); } } } /** * Callback to all objects implementing the ChannelNickChanged Callback. * * @see IChannelNickChanged * @param cChannel One of the channels that the user is on * @param cChannelClient Client changing nickname * @param sOldNick Nickname before change * @return true if a method was called, false otherwise */ protected boolean callChannelNickChanged(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sOldNick) { CallbackOnChannelNickChanged cb = (CallbackOnChannelNickChanged)getCallbackManager().getCallbackType("OnChannelNickChanged"); if (cb != null) { return cb.call(cChannel, cChannelClient, sOldNick); } return false; } /** * Callback to all objects implementing the NickChanged Callback. * * @see INickChanged * @param cClient Client changing nickname * @param sOldNick Nickname before change * @return true if a method was called, false otherwise */ protected boolean callNickChanged(ClientInfo cClient, String sOldNick) { CallbackOnNickChanged cb = (CallbackOnNickChanged)getCallbackManager().getCallbackType("OnNickChanged"); if (cb != null) { return cb.call(cClient, sOldNick); } return false; } /** * What does this IRCProcessor handle. * * @return String[] with the names of the tokens we handle. */ public String[] handles() { String[] iHandle = new String[1]; iHandle[0] = "NICK"; return iHandle; } /** * Create a new instance of the IRCProcessor Object. * * @param parser IRCParser That owns this IRCProcessor * @param manager ProcessingManager that is in charge of this IRCProcessor */ protected ProcessNick (IRCParser parser, ProcessingManager manager) { super(parser, manager); } }
true
true
public void process(String sParam, String[] token) { ClientInfo iClient; ChannelClientInfo iChannelClient; String oldNickname; iClient = getClientInfo(token[0]); if (iClient != null) { oldNickname = myParser.toLowerCase(iClient.getNickname()); // Remove the client from the known clients list final boolean isSameNick = myParser.equalsIgnoreCase(oldNickname, token[token.length-1]); if (!isSameNick) { myParser.forceRemoveClient(getClientInfo(oldNickname)); } // Change the nickame iClient.setUserBits(token[token.length-1],true); // Readd the client if (!isSameNick && myParser.getClientInfo(iClient.getNickname()) != null) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine())); } else { if (!isSameNick) { myParser.addClient(iClient); } for (ChannelInfo iChannel : myParser.getChannels()) { // Find the user (using the old nickname) iChannelClient = iChannel.getUser(oldNickname); if (iChannelClient != null) { // Rename them. This uses the old nickname (the key in the hashtable) // and the channelClient object has access to the new nickname (by way // of the ClientInfo object we updated above) if (!isSameNick) { iChannel.renameClient(oldNickname, iChannelClient); } callChannelNickChanged(iChannel,iChannelClient,ClientInfo.parseHost(token[0])); } } callNickChanged(iClient, ClientInfo.parseHost(token[0])); } } }
public void process(String sParam, String[] token) { ClientInfo iClient; ChannelClientInfo iChannelClient; String oldNickname; iClient = getClientInfo(token[0]); if (iClient != null) { oldNickname = myParser.toLowerCase(iClient.getNickname()); // Remove the client from the known clients list final boolean isSameNick = myParser.equalsIgnoreCase(oldNickname, token[token.length-1]); if (!isSameNick) { myParser.forceRemoveClient(getClientInfo(oldNickname)); } // Change the nickame iClient.setUserBits(token[token.length-1],true); // Readd the client if (!isSameNick && myParser.getClientInfo(iClient.getNickname()) != null) { myParser.onPostErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine()), false); } else { if (!isSameNick) { myParser.addClient(iClient); } for (ChannelInfo iChannel : myParser.getChannels()) { // Find the user (using the old nickname) iChannelClient = iChannel.getUser(oldNickname); if (iChannelClient != null) { // Rename them. This uses the old nickname (the key in the hashtable) // and the channelClient object has access to the new nickname (by way // of the ClientInfo object we updated above) if (!isSameNick) { iChannel.renameClient(oldNickname, iChannelClient); } callChannelNickChanged(iChannel,iChannelClient,ClientInfo.parseHost(token[0])); } } callNickChanged(iClient, ClientInfo.parseHost(token[0])); } } }
diff --git a/src/MessageClasses/MessageEntry.java b/src/MessageClasses/MessageEntry.java index f7b468a..125d8fa 100644 --- a/src/MessageClasses/MessageEntry.java +++ b/src/MessageClasses/MessageEntry.java @@ -1,159 +1,159 @@ /* * This code is distributed under terms of GNU GPLv2. * *See LICENSE file. * ©UKRINFORM 2011-2012 */ package MessageClasses; /** * Message index entry class. * Contains all message fields but it's content. * @author Stanislav Nepochatov <[email protected]> */ public class MessageEntry extends Generic.CsvElder { /** * Index of the original message * @since RibbonServer a2 */ public String ORIG_INDEX; /** * Index of message. */ public String INDEX; /** * Message's directories. */ public String[] DIRS; /** * Header of message. */ public String HEADER; /** * Date of message release. */ public String DATE; /** * Name of the original author. * * <p>Once message appears in the system name of original author * cannot be changed by ordinary user.</p> * @since RibbonServer a2 */ public String ORIG_AUTHOR; /** * Author of message. */ public String AUTHOR; /** * Message's tags. */ public String[] TAGS; /** * System properties of this message. * @since RibbonServer a2 */ public java.util.ArrayList<MessageClasses.MessageProperty> PROPERTIES = new java.util.ArrayList<MessageClasses.MessageProperty>(); /** * Message language. * @since RibbonServer a2 */ public String LANG; /** * Default empty constructor. */ public MessageEntry() { this.baseCount = 8; this.groupCount = 2; this.currentFormat = csvFormatType.ComplexCsv; } /** * Default constructor from csv form. * @param givenCsv csv line */ public MessageEntry(String givenCsv) { this(); java.util.ArrayList<String[]> parsedStruct = Generic.CsvFormat.fromCsv(this, givenCsv); String[] baseArray = parsedStruct.get(0); this.INDEX = baseArray[0]; this.ORIG_INDEX = baseArray[1]; this.DIRS = parsedStruct.get(1); this.LANG = baseArray[2]; this.HEADER = baseArray[3]; this.DATE = baseArray[4]; this.ORIG_AUTHOR = baseArray[5]; this.AUTHOR = baseArray[6]; this.TAGS = parsedStruct.get(2); - String[] rawPropertiesArray = baseArray[7].split("$"); + String[] rawPropertiesArray = baseArray[7].split("\\$"); if ((rawPropertiesArray.length > 1) || (!rawPropertiesArray[0].isEmpty())) { for (String rawProperty : rawPropertiesArray) { this.PROPERTIES.add(new MessageClasses.MessageProperty(rawProperty)); } } } @Override public String toCsv() { return this.INDEX + "," + this.ORIG_INDEX + "," + Generic.CsvFormat.renderGroup(DIRS) + "," + this.LANG + ",{" + this.HEADER + "}," + this.DATE + ",{" + this.ORIG_AUTHOR + "},{" + this.AUTHOR + "}," + Generic.CsvFormat.renderGroup(TAGS) + "," + Generic.CsvFormat.renderMessageProperties(PROPERTIES); } /** * Create message template for RIBBON_POST_MESSAGE command;<br> * <br> * CSV format:<br> * ORIGINAL_INDEX,[DIR_1,DIR_2],LANG,{HEADER},[TAG_1,TAG_2] * @param PostCsv given csv line for post command; */ public void createMessageForPost(String PostCsv) { this.baseCount = 3; java.util.ArrayList<String[]> parsedStruct = Generic.CsvFormat.fromCsv(this, PostCsv); String[] baseArray = parsedStruct.get(0); this.ORIG_INDEX = baseArray[0]; this.LANG = baseArray[1]; this.HEADER = baseArray[2]; this.DIRS = parsedStruct.get(1); this.TAGS = parsedStruct.get(2); } /** * Create message template for RIBBON_MODIFY_MESSAGE command;<br> * <br> * CSV format:<br> * [DIR_1,DIR_2],LANG,{HEADER},[TAG_1,TAG_2] * @param modCsv given csv line for post command; */ public void createMessageForModify(String modCsv) { this.baseCount = 2; java.util.ArrayList<String[]> parsedStruct = Generic.CsvFormat.fromCsv(this, modCsv); String[] baseArray = parsedStruct.get(0); this.LANG = baseArray[0]; this.HEADER = baseArray[1]; this.DIRS = parsedStruct.get(1); this.TAGS = parsedStruct.get(2); } /** * Modify message's fileds; * @param givenMessage message template; */ public void modifyMessageEntry(MessageEntry givenMessage) { this.LANG = givenMessage.LANG; this.HEADER = givenMessage.HEADER; this.DIRS = givenMessage.DIRS; this.TAGS = givenMessage.TAGS; } }
true
true
public MessageEntry(String givenCsv) { this(); java.util.ArrayList<String[]> parsedStruct = Generic.CsvFormat.fromCsv(this, givenCsv); String[] baseArray = parsedStruct.get(0); this.INDEX = baseArray[0]; this.ORIG_INDEX = baseArray[1]; this.DIRS = parsedStruct.get(1); this.LANG = baseArray[2]; this.HEADER = baseArray[3]; this.DATE = baseArray[4]; this.ORIG_AUTHOR = baseArray[5]; this.AUTHOR = baseArray[6]; this.TAGS = parsedStruct.get(2); String[] rawPropertiesArray = baseArray[7].split("$"); if ((rawPropertiesArray.length > 1) || (!rawPropertiesArray[0].isEmpty())) { for (String rawProperty : rawPropertiesArray) { this.PROPERTIES.add(new MessageClasses.MessageProperty(rawProperty)); } } }
public MessageEntry(String givenCsv) { this(); java.util.ArrayList<String[]> parsedStruct = Generic.CsvFormat.fromCsv(this, givenCsv); String[] baseArray = parsedStruct.get(0); this.INDEX = baseArray[0]; this.ORIG_INDEX = baseArray[1]; this.DIRS = parsedStruct.get(1); this.LANG = baseArray[2]; this.HEADER = baseArray[3]; this.DATE = baseArray[4]; this.ORIG_AUTHOR = baseArray[5]; this.AUTHOR = baseArray[6]; this.TAGS = parsedStruct.get(2); String[] rawPropertiesArray = baseArray[7].split("\\$"); if ((rawPropertiesArray.length > 1) || (!rawPropertiesArray[0].isEmpty())) { for (String rawProperty : rawPropertiesArray) { this.PROPERTIES.add(new MessageClasses.MessageProperty(rawProperty)); } } }
diff --git a/src/main/java/com/bsg/pcms/user/UserController.java b/src/main/java/com/bsg/pcms/user/UserController.java index f499b36..c621ed8 100644 --- a/src/main/java/com/bsg/pcms/user/UserController.java +++ b/src/main/java/com/bsg/pcms/user/UserController.java @@ -1,75 +1,76 @@ package com.bsg.pcms.user; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.bsg.pcms.dashboard.DashboardController; import com.bsg.pcms.dto.UserDTO; import com.bsg.pcms.utility.BigstarConstant; import com.bsg.pcms.utility.BigstarProperties; @Controller public class UserController { private Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired BigstarConstant bigstarConstant; @Autowired private DashboardController dashboardController; @Autowired private UserService userSevice; @Autowired private BigstarProperties bigstarProperties; /** * PMC 초기화면 * * @return */ @RequestMapping(value = "index.do", method = RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value = "login", method = RequestMethod.POST) public String login(UserDTO member, HttpServletRequest request) { if (userSevice.hasNoUser(member)) { + logger.info("here"); return "redirect:/index.do"; } UserDTO resultDTO = userSevice.getUser(member); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("id", resultDTO.getId()); map.put("level_cd", resultDTO.getLevel_cd()); request.getSession().setAttribute("user", map); return "redirect:/dashboard.do"; } @RequestMapping(value = "logout", method = RequestMethod.GET) public String logout() { return "redirect:/index.do"; } }
true
true
public String login(UserDTO member, HttpServletRequest request) { if (userSevice.hasNoUser(member)) { return "redirect:/index.do"; } UserDTO resultDTO = userSevice.getUser(member); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("id", resultDTO.getId()); map.put("level_cd", resultDTO.getLevel_cd()); request.getSession().setAttribute("user", map); return "redirect:/dashboard.do"; }
public String login(UserDTO member, HttpServletRequest request) { if (userSevice.hasNoUser(member)) { logger.info("here"); return "redirect:/index.do"; } UserDTO resultDTO = userSevice.getUser(member); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("id", resultDTO.getId()); map.put("level_cd", resultDTO.getLevel_cd()); request.getSession().setAttribute("user", map); return "redirect:/dashboard.do"; }
diff --git a/test/regression/ThreadStop.java b/test/regression/ThreadStop.java index 3a3080f9a..22257bd78 100644 --- a/test/regression/ThreadStop.java +++ b/test/regression/ThreadStop.java @@ -1,248 +1,251 @@ /* * ThreadStop.java * * Test stopping various threads. * * Courtesy Pat Tullmann ([email protected]) */ class ThreadStop_BlockThread extends Thread { String blocker = "blocker"; public void run() { System.out.println("Target (BlockThread) running..."); try { synchronized(blocker) { System.out.println(" Locked ..."); try { blocker.wait(); } catch (InterruptedException ie) { System.out.println("INTERRUPTED. TRY AGAIN. " +ie); } } } catch (Error o) { System.out.println(" Handling my own: " + o); System.out.print(" Am I alive? Answer: "); System.out.println(Thread.currentThread().isAlive()); // rethrow exception throw o; } } public ThreadStop_BlockThread() { super("BlockThread"); } } class ThreadStop_RunThread extends Thread { static int ct_ = 0; public void run() { System.out.println("Target (RunThread) running..."); while(true) { ct_++; } } public ThreadStop_RunThread() { super("RunThread"); } } class ThreadStop_MonitorThread extends Thread { static Object obj_ = new Object(); public void run() { System.out.println("Target (MonitorThread) running..."); synchronized(obj_) { try { obj_.wait(); } catch (InterruptedException ie) { System.out.println("INTERRUPTED. TRY AGAIN. " +ie); } } } public ThreadStop_MonitorThread() { super("MonitorThread"); } } class ThreadStop_DoneThread extends Thread { public void run() { // just exit immediately } public ThreadStop_DoneThread() { super("DoneThread"); } } class ThreadStop_SelfStop extends Thread { public void run() { this.stop(); System.out.println("SelfStop thread returned from stop()"); } public ThreadStop_SelfStop() { super("SelfStopThread"); } } class ThreadStop { static int ct_ = 0; static Object obj_ = new Object(); static public void sleep(int time) { try { Thread.sleep(time); } catch (InterruptedException ie) { msg("Dammit! Thread.sleep() was interrupted. Results are INVALID. " +ie); } } static public void killIt(Thread target) { // Sleep for a bit to let it get going. sleep(500); // Kill the target target.stop(); // Sleep for a bit and then check if its dead sleep(500); if (target.isAlive()) msg(" Failure! Target is alive."); else msg(" Success. Target is dead."); } static public void main(String[] args) { Thread target; msg("Test 1: Stop a thread that's blocked on itself"); target = new ThreadStop_BlockThread(); target.start(); sleep(500); synchronized(((ThreadStop_BlockThread)target).blocker) { killIt(target); // sleep while holding on to target msg(" Sleeping while still holding on to target"); sleep(500); msg(" Releasing target lock"); } // give this thread time to catch its death exception sleep(500); msg("Test 2: Stop a thread that's blocked in a monitor"); target = new ThreadStop_MonitorThread(); target.start(); killIt(target); msg("Test 3: Stop a thread that's running"); target = new ThreadStop_RunThread(); // make sure we get to run again if non-preemptive Thread.currentThread().setPriority(Thread.MAX_PRIORITY); target.start(); killIt(target); msg("Test 4: Stop a thread that's done"); target = new ThreadStop_DoneThread(); target.start(); killIt(target); + // killing unstarted threads doesn't work yet + if (false) { msg("Test 5: Stop a thread that's never been run"); - Thread t2 = new Thread("NeverGoThread"); + target = new ThreadStop_RunThread(); - killIt(t2); + killIt(target); - t2.start(); + target.start(); sleep(100); - if (t2.isAlive()) - msg(" Failure! Target is still alive!"); + if (target.isAlive()) + msg(" Failure (#5)! Target is still alive!"); + } msg("Test 6: Have a thread stop itself"); target = new ThreadStop_SelfStop(); target.start(); sleep(2000); if (target.isAlive()) - msg(" Failure! Target is still alive!"); + msg(" Failure (#6)! Target is still alive!"); else msg(" Success. Target is dead."); msg("All tests completed"); } public void run() { while (true) { try { synchronized(obj_) { msg("Running; blocking (ct=" +ct_+ ")"); obj_.notify(); ct_++; obj_.wait(); msg("Woken (_ct=" +ct_+ ")"); } } catch (java.lang.InterruptedException ie) { msg("Dammit. Test is invalid, try again. " +ie); } } } public static void msg(String arg) { System.out.println(arg); } }
false
true
static public void main(String[] args) { Thread target; msg("Test 1: Stop a thread that's blocked on itself"); target = new ThreadStop_BlockThread(); target.start(); sleep(500); synchronized(((ThreadStop_BlockThread)target).blocker) { killIt(target); // sleep while holding on to target msg(" Sleeping while still holding on to target"); sleep(500); msg(" Releasing target lock"); } // give this thread time to catch its death exception sleep(500); msg("Test 2: Stop a thread that's blocked in a monitor"); target = new ThreadStop_MonitorThread(); target.start(); killIt(target); msg("Test 3: Stop a thread that's running"); target = new ThreadStop_RunThread(); // make sure we get to run again if non-preemptive Thread.currentThread().setPriority(Thread.MAX_PRIORITY); target.start(); killIt(target); msg("Test 4: Stop a thread that's done"); target = new ThreadStop_DoneThread(); target.start(); killIt(target); msg("Test 5: Stop a thread that's never been run"); Thread t2 = new Thread("NeverGoThread"); killIt(t2); t2.start(); sleep(100); if (t2.isAlive()) msg(" Failure! Target is still alive!"); msg("Test 6: Have a thread stop itself"); target = new ThreadStop_SelfStop(); target.start(); sleep(2000); if (target.isAlive()) msg(" Failure! Target is still alive!"); else msg(" Success. Target is dead."); msg("All tests completed"); }
static public void main(String[] args) { Thread target; msg("Test 1: Stop a thread that's blocked on itself"); target = new ThreadStop_BlockThread(); target.start(); sleep(500); synchronized(((ThreadStop_BlockThread)target).blocker) { killIt(target); // sleep while holding on to target msg(" Sleeping while still holding on to target"); sleep(500); msg(" Releasing target lock"); } // give this thread time to catch its death exception sleep(500); msg("Test 2: Stop a thread that's blocked in a monitor"); target = new ThreadStop_MonitorThread(); target.start(); killIt(target); msg("Test 3: Stop a thread that's running"); target = new ThreadStop_RunThread(); // make sure we get to run again if non-preemptive Thread.currentThread().setPriority(Thread.MAX_PRIORITY); target.start(); killIt(target); msg("Test 4: Stop a thread that's done"); target = new ThreadStop_DoneThread(); target.start(); killIt(target); // killing unstarted threads doesn't work yet if (false) { msg("Test 5: Stop a thread that's never been run"); target = new ThreadStop_RunThread(); killIt(target); target.start(); sleep(100); if (target.isAlive()) msg(" Failure (#5)! Target is still alive!"); } msg("Test 6: Have a thread stop itself"); target = new ThreadStop_SelfStop(); target.start(); sleep(2000); if (target.isAlive()) msg(" Failure (#6)! Target is still alive!"); else msg(" Success. Target is dead."); msg("All tests completed"); }
diff --git a/src/merkurius/ld27/system/LD27AnimationSystem.java b/src/merkurius/ld27/system/LD27AnimationSystem.java index 6d6a44d..6332747 100644 --- a/src/merkurius/ld27/system/LD27AnimationSystem.java +++ b/src/merkurius/ld27/system/LD27AnimationSystem.java @@ -1,138 +1,138 @@ package merkurius.ld27.system; import java.util.Map; import merkurius.ld27.component.Shooter; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.math.Vector2; import fr.kohen.alexandre.framework.base.C; import fr.kohen.alexandre.framework.components.Transform; import fr.kohen.alexandre.framework.components.Velocity; import fr.kohen.alexandre.framework.components.VisualComponent; import fr.kohen.alexandre.framework.model.Visual; import fr.kohen.alexandre.framework.systems.interfaces.AnimationSystem; /** * Extend this class to modify how the animations are updated * @author Alexandre * */ public class LD27AnimationSystem extends EntityProcessingSystem implements AnimationSystem { protected ComponentMapper<VisualComponent> visualMapper; protected ComponentMapper<Transform> transformMapper; protected ComponentMapper<Velocity> velocityMapper; protected ComponentMapper<Shooter> shooterMapper; protected Map<Entity,Visual> visuals; @SuppressWarnings("unchecked") public LD27AnimationSystem() { super( Aspect.getAspectForAll(VisualComponent.class, Shooter.class, Velocity.class) ); } @Override public void initialize() { visualMapper = ComponentMapper.getFor(VisualComponent.class, world); velocityMapper = ComponentMapper.getFor(Velocity.class, world); shooterMapper = ComponentMapper.getFor(Shooter.class, world); } @Override protected void process(Entity e) { visualMapper.get(e).stateTime += world.getDelta(); if( velocityMapper.getSafe(e) != null ) { setCurrentAnim( visualMapper.get(e), shooterMapper.get(e).getShootingVector(), velocityMapper.get(e).getSpeed() ); } } protected void setCurrentAnim(VisualComponent visual, Vector2 direction, Vector2 speed) { visual.currentAnimationName = getAnim(visual, direction) ; if( speed.len() < 50 ) { visual.currentAnimationName = idleAnim(visual); } } protected String getAnim(VisualComponent visual, Vector2 direction) { String currentAnim = visual.currentAnimationName; if( direction.angle() > 337.5 ) { - currentAnim = C.WALK_UP; + currentAnim = C.WALK_RIGHT; } else if( direction.angle() > 292.5 ) { - currentAnim = C.WALK_UP_LEFT; + currentAnim = C.WALK_DOWN_RIGHT; } else if( direction.angle() > 247.5 ) { - currentAnim = C.WALK_LEFT; + currentAnim = C.WALK_DOWN; } else if( direction.angle() > 202.5 ) { currentAnim = C.WALK_DOWN_LEFT; } else if( direction.angle() > 157.5 ) { - currentAnim = C.WALK_DOWN; + currentAnim = C.WALK_LEFT; } else if( direction.angle() > 112.5 ) { - currentAnim = C.WALK_DOWN_RIGHT; + currentAnim = C.WALK_UP_LEFT; } else if( direction.angle() > 67.5 ) { - currentAnim = C.WALK_RIGHT; + currentAnim = C.WALK_UP; } else if( direction.angle() > 22.5 ) { currentAnim = C.WALK_UP_RIGHT; } else{ - currentAnim = C.WALK_UP; + currentAnim = C.WALK_RIGHT; } /*if( speed.len() < 1 ) return idleAnim(visual); if( speed.x < 0.1f ) { if( speed.y < 0.1f ) currentAnim = C.WALK_DOWN_LEFT; else if( speed.y > 0.1f ) currentAnim = C.WALK_UP_LEFT; else currentAnim = C.WALK_LEFT; } else if( speed.x > 0.1f ) { if( speed.y < 0.1f ) currentAnim = C.WALK_DOWN_RIGHT; else if( speed.y > 0.1f ) currentAnim = C.WALK_UP_RIGHT; else currentAnim = C.WALK_RIGHT; } else { if( speed.y > 0.1f ) currentAnim = C.WALK_UP; else currentAnim = C.WALK_DOWN; } */ return currentAnim; } /** * Sets the current animation to the idle animation */ protected String idleAnim(VisualComponent visual) { String currentAnim = visual.currentAnimationName; if (currentAnim.equalsIgnoreCase(C.WALK_LEFT)) { currentAnim = C.STAND_LEFT; } else if (currentAnim.equalsIgnoreCase(C.WALK_RIGHT)) { currentAnim = C.STAND_RIGHT; } else if (currentAnim.equalsIgnoreCase(C.WALK_UP)) { currentAnim = C.STAND_UP; } else if (currentAnim.equalsIgnoreCase(C.WALK_DOWN)) { currentAnim = C.STAND_DOWN; } else if (currentAnim.equalsIgnoreCase(C.WALK_DOWN_LEFT)) { currentAnim = C.STAND_DOWN_LEFT; } else if (currentAnim.equalsIgnoreCase(C.WALK_DOWN_RIGHT)) { currentAnim = C.STAND_DOWN_RIGHT; } else if (currentAnim.equalsIgnoreCase(C.WALK_UP_LEFT)) { currentAnim = C.STAND_UP_LEFT; } else if (currentAnim.equalsIgnoreCase(C.WALK_UP_RIGHT)) { currentAnim = C.STAND_UP_RIGHT; } return currentAnim; } }
false
true
protected String getAnim(VisualComponent visual, Vector2 direction) { String currentAnim = visual.currentAnimationName; if( direction.angle() > 337.5 ) { currentAnim = C.WALK_UP; } else if( direction.angle() > 292.5 ) { currentAnim = C.WALK_UP_LEFT; } else if( direction.angle() > 247.5 ) { currentAnim = C.WALK_LEFT; } else if( direction.angle() > 202.5 ) { currentAnim = C.WALK_DOWN_LEFT; } else if( direction.angle() > 157.5 ) { currentAnim = C.WALK_DOWN; } else if( direction.angle() > 112.5 ) { currentAnim = C.WALK_DOWN_RIGHT; } else if( direction.angle() > 67.5 ) { currentAnim = C.WALK_RIGHT; } else if( direction.angle() > 22.5 ) { currentAnim = C.WALK_UP_RIGHT; } else{ currentAnim = C.WALK_UP; } /*if( speed.len() < 1 ) return idleAnim(visual); if( speed.x < 0.1f ) { if( speed.y < 0.1f ) currentAnim = C.WALK_DOWN_LEFT; else if( speed.y > 0.1f ) currentAnim = C.WALK_UP_LEFT; else currentAnim = C.WALK_LEFT; } else if( speed.x > 0.1f ) { if( speed.y < 0.1f ) currentAnim = C.WALK_DOWN_RIGHT; else if( speed.y > 0.1f ) currentAnim = C.WALK_UP_RIGHT; else currentAnim = C.WALK_RIGHT; } else { if( speed.y > 0.1f ) currentAnim = C.WALK_UP; else currentAnim = C.WALK_DOWN; } */ return currentAnim; }
protected String getAnim(VisualComponent visual, Vector2 direction) { String currentAnim = visual.currentAnimationName; if( direction.angle() > 337.5 ) { currentAnim = C.WALK_RIGHT; } else if( direction.angle() > 292.5 ) { currentAnim = C.WALK_DOWN_RIGHT; } else if( direction.angle() > 247.5 ) { currentAnim = C.WALK_DOWN; } else if( direction.angle() > 202.5 ) { currentAnim = C.WALK_DOWN_LEFT; } else if( direction.angle() > 157.5 ) { currentAnim = C.WALK_LEFT; } else if( direction.angle() > 112.5 ) { currentAnim = C.WALK_UP_LEFT; } else if( direction.angle() > 67.5 ) { currentAnim = C.WALK_UP; } else if( direction.angle() > 22.5 ) { currentAnim = C.WALK_UP_RIGHT; } else{ currentAnim = C.WALK_RIGHT; } /*if( speed.len() < 1 ) return idleAnim(visual); if( speed.x < 0.1f ) { if( speed.y < 0.1f ) currentAnim = C.WALK_DOWN_LEFT; else if( speed.y > 0.1f ) currentAnim = C.WALK_UP_LEFT; else currentAnim = C.WALK_LEFT; } else if( speed.x > 0.1f ) { if( speed.y < 0.1f ) currentAnim = C.WALK_DOWN_RIGHT; else if( speed.y > 0.1f ) currentAnim = C.WALK_UP_RIGHT; else currentAnim = C.WALK_RIGHT; } else { if( speed.y > 0.1f ) currentAnim = C.WALK_UP; else currentAnim = C.WALK_DOWN; } */ return currentAnim; }
diff --git a/src/org/omegat/filters2/po/PoFilter.java b/src/org/omegat/filters2/po/PoFilter.java index d0790796..4f7d7ba9 100644 --- a/src/org/omegat/filters2/po/PoFilter.java +++ b/src/org/omegat/filters2/po/PoFilter.java @@ -1,462 +1,463 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2000-2006 Keith Godfrey and Maxym Mykhalchuk 2006 Thomas Huriaux 2008 Martin Fleurke 2009 Alex Buloichik Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **************************************************************************/ package org.omegat.filters2.po; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.omegat.filters2.AbstractFilter; import org.omegat.filters2.Instance; import org.omegat.filters2.TranslationException; import org.omegat.util.OStrings; /** * Filter to support po files (in various encodings). * * Format described on * http://www.gnu.org/software/hello/manual/gettext/PO-Files.html * * Filter is not thread-safe ! * * @author Keith Godfrey * @author Maxym Mykhalchuk * @author Thomas Huriaux * @author Martin Fleurke * @author Alex Buloichik ([email protected]) */ public class PoFilter extends AbstractFilter { protected static Pattern COMMENT_FUZZY = Pattern.compile("#, fuzzy"); protected static Pattern COMMENT_FUZZY_OTHER = Pattern .compile("#,.* fuzzy.*"); protected static Pattern COMMENT_NOWRAP = Pattern.compile("#,.* no-wrap.*"); protected static Pattern MSG_ID = Pattern .compile("msgid(_plural)?\\s+\"(.*)\""); protected static Pattern MSG_STR = Pattern .compile("msgstr(\\[[0-9]+\\])?\\s+\"(.*)\""); protected static Pattern MSG_CTX = Pattern.compile("msgctxt\\s+\"(.*)\""); protected static Pattern MSG_OTHER = Pattern.compile("\"(.*)\""); enum MODE { MSGID, MSGSTR, MSGID_PLURAL, MSGSTR_PLURAL, MSGCTX }; private StringBuilder[] sources, targets; private boolean nowrap, fuzzy; private BufferedWriter out; public String getFileFormatName() { return OStrings.getString("POFILTER_FILTER_NAME"); } public Instance[] getDefaultInstances() { return new Instance[] { new Instance("*.po"), // NOI18N new Instance("*.pot") // NOI18N }; } public boolean isSourceEncodingVariable() { return true; } public boolean isTargetEncodingVariable() { return true; } public String getFuzzyMark() { return "PO-fuzzy"; } public void processFile(File inFile, String inEncoding, File outFile, String outEncoding) throws IOException, TranslationException { BufferedReader reader = createReader(inFile, inEncoding); try { BufferedWriter writer; if (outFile != null) { writer = createWriter(outFile, outEncoding); } else { writer = null; } try { processFile(reader, writer); } finally { if (writer != null) { writer.close(); } } } finally { reader.close(); } } @Override protected void alignFile(BufferedReader sourceFile, BufferedReader translatedFile) throws Exception { // BOM (byte order mark) bugfix translatedFile.mark(1); int ch = translatedFile.read(); if (ch != 0xFEFF) translatedFile.reset(); this.out = null; processPoFile(translatedFile); } public void processFile(BufferedReader in, BufferedWriter out) throws IOException { // BOM (byte order mark) bugfix in.mark(1); int ch = in.read(); if (ch != 0xFEFF) in.reset(); this.out = out; processPoFile(in); } private void processPoFile(BufferedReader in) throws IOException { fuzzy = false; nowrap = false; MODE currentMode = null; int currentPlural = 0; sources = new StringBuilder[2]; sources[0] = new StringBuilder(); sources[1] = new StringBuilder(); targets = new StringBuilder[2]; targets[0] = new StringBuilder(); targets[1] = new StringBuilder(); String s; while ((s = in.readLine()) != null) { /* * Removing the fuzzy markers, as it has no meanings after being * processed by omegat */ if (COMMENT_FUZZY.matcher(s).matches()) { fuzzy = true; flushTranslation(currentMode); continue; } else if (COMMENT_FUZZY_OTHER.matcher(s).matches()) { fuzzy = true; flushTranslation(currentMode); s = s.replaceAll("(.*), fuzzy(.*)", "$1$2"); } // FSM for po files if (COMMENT_NOWRAP.matcher(s).matches()) { flushTranslation(currentMode); /* * Read the no-wrap comment, indicating that the creator of the * po-file did not want long messages to be wrapped on multiple * lines. See 5.6.2 no-wrap of http://docs.oasis-open * .org/xliff/v1.2/xliff-profile-po/xliff * -profile-po-1.2-cd02.html for an example. */ nowrap = true; eol(s); continue; } Matcher m; if ((m = MSG_ID.matcher(s)).matches()) { String text = m.group(2); if (m.group(1) == null) { // non-plural ID currentMode = MODE.MSGID; sources[0].append(text); } else { // plural ID currentMode = MODE.MSGID_PLURAL; sources[1].append(text); } eol(s); continue; } if ((m = MSG_STR.matcher(s)).matches()) { String text = m.group(2); if (m.group(1) == null) { // non-plural lines currentMode = MODE.MSGSTR; targets[0].append(text); } else { currentMode = MODE.MSGSTR_PLURAL; // plurals, i.e. msgstr[N] lines if ("[0]".equals(m.group(1))) { targets[0].append(text); currentPlural = 0; } else if ("[1]".equals(m.group(1))) { targets[1].append(text); currentPlural = 1; } } continue; } if ((m = MSG_CTX.matcher(s)).matches()) { currentMode = MODE.MSGCTX; eol(s); continue; } if ((m = MSG_OTHER.matcher(s)).matches()) { String text = m.group(1); if (currentMode == null) { throw new IOException("Invalid file format"); } switch (currentMode) { case MSGID: sources[0].append(text); eol(s); break; case MSGID_PLURAL: sources[1].append(text); eol(s); break; case MSGSTR: targets[0].append(text); break; case MSGSTR_PLURAL: targets[currentPlural].append(text); break; case MSGCTX: + eol(s); break; } continue; } flushTranslation(currentMode); eol(s); } flushTranslation(currentMode); } protected void eol(String s) throws IOException { if (out != null) { out.write(s); out.write('\n'); } } protected void align(int pair) { String s = unescape(sources[pair].toString()); String t = unescape(targets[pair].toString()); align(s, t); } protected void align(String source, String translation) { if (translation.length() == 0) { translation = null; } if (entryParseCallback != null) { entryParseCallback.addEntry(null, source, translation, fuzzy, null, this); } else if (entryAlignCallback != null) { entryAlignCallback.addTranslation(null, source, translation, fuzzy, null, this); } } protected void alignHeader(String header) { if (entryParseCallback != null) { entryParseCallback.addEntry(null, unescape(header), null, false, null, this); } } protected void flushTranslation(MODE currentMode) throws IOException { if (sources[0].length() == 0) { if (targets[0].length() == 0) { // there is no text to translate yet return; } else { // header if (out != null) { out.write("msgstr " + getTranslation(targets[0]) + "\n"); } else { alignHeader(targets[0].toString()); } } fuzzy = false; } else { // source exist if (sources[1].length() == 0) { // non-plurals if (out != null) { out.write("msgstr " + getTranslation(sources[0]) + "\n"); } else { align(0); } } else { // plurals if (out != null) { out.write("msgstr[0] " + getTranslation(sources[0]) + "\n"); out.write("msgstr[1] " + getTranslation(sources[1]) + "\n"); } else { align(0); align(1); } } fuzzy = false; } sources[0].setLength(0); sources[1].setLength(0); targets[0].setLength(0); targets[1].setLength(0); } protected static final Pattern R1 = Pattern .compile("(?<!\\\\)((\\\\\\\\)*)\\\\\""); protected static final Pattern R2 = Pattern .compile("(?<!\\\\)((\\\\\\\\)*)\\\\n"); protected static final Pattern R3 = Pattern .compile("(?<!\\\\)((\\\\\\\\)*)\\\\t"); protected static final Pattern R4 = Pattern.compile("^\\\\n"); /** * Private processEntry to do pre- and postprocessing.<br> * The given entry is interpreted to a string (e.g. escaped quotes are * unescaped, '\n' is translated into newline character, '\t' into tab * character.) then translated and then returned as a PO-string-notation * (e.g. double quotes escaped, newline characters represented as '\n' and * surrounded by double quotes, possibly split up over multiple lines)<Br> * Long translations are not split up over multiple lines as some PO editors * do, but when there are newline characters in a translation, it is split * up at the newline markers.<Br> * If the nowrap parameter is true, a translation that exists of multiple * lines starts with an empty string-line to left-align all lines. [With * nowrap set to true, long lines are also never wrapped (except for at * newline characters), but that was already not done without nowrap.] [ * 1869069 ] Escape support for PO * * @param entry * The entire source text, without it's surrounding double * quotes, but otherwise not-interpreted * @param nowrap * gives indication if the translation should not be wrapped over * multiple lines and all lines be left-aligned. * @return The translated entry, within double quotes on each line (thus * ready to be printed to target file immediately) **/ private String getTranslation(StringBuilder en) { String entry = unescape(en.toString()); // Do real translation String translation = entryTranslateCallback .getTranslation(null, entry); if (translation != null) { return "\"" + escape(translation) + "\""; } else { return "\"\""; } } /** * Unescape text from .po format. */ private String unescape(String entry) { // Removes escapes from quotes. ( \" becomes " unless the \ // was escaped itself.) The number of preceding slashes before \" // should not be odd, else the \ is escaped and not part of \". // The regex is: no backslash before an optional even number // of backslashes before \". Replace only the \" with " and keep the // other escaped backslashes ) entry = R1.matcher(entry).replaceAll("$1\""); // Interprets newline sequence, except when preceded by \ // \n becomes Linefeed, unless the \ was escaped itself. // The number of preceding slashes before \n should not be odd, // else the \ is escaped and not part of \n. // The regex is: no backslash before an optional even number of // backslashes before \n. Replace only the \n with <newline> and // keep // the other escaped backslashes. entry = R2.matcher(entry).replaceAll("$1\n"); // same for \t, the tab character entry = R3.matcher(entry).replaceAll("$1\t"); // Interprets newline sequence at the beginning of a line entry = R4.matcher(entry).replaceAll("\\\n"); // Removes escape from backslash entry = entry.replace("\\\\", "\\"); return entry; } /** * Escape text to .po format. */ private String escape(String translation) { // Escapes backslash translation = translation.replace("\\", "\\\\"); // Adds escapes to quotes. ( " becomes \" ) translation = translation.replace("\"", "\\\""); // AB: restore \r translation = translation.replace("\\\\r", "\\r"); /* * Normally, long lines are wrapped at 'output page width', which * defaults to ?76?, and always at newlines. IF the no-wrap indicator is * present, long lines should not be wrapped, except on newline * characters, in which case the first line should be empty, so that the * different lines are aligned the same. OmegaT < 2.0 has never wrapped * any line, and it is quite useless when the po-file is not edited with * a plain-text-editor. But it is simple to wrap at least at newline * characters (which is necessary for the translation of the po-header * anyway) We can also honor the no-wrap instruction at least by letting * the first line of a multi-line translation not be on the same line as * 'msgstr'. */ // Interprets newline chars. 'blah<br>blah' becomes // 'blah\n"<br>"blah' translation = translation.replace("\n", "\\n\"\n\""); // don't make empty new line at the end (in case the last 'blah' is // empty string) if (translation.endsWith("\"\n\"")) { translation = translation.substring(0, translation.length() - 3); } if (nowrap && translation.contains("\n")) { // start with empty string, to align all lines of translation translation = "\"\n\"" + translation; } // Interprets tab chars. 'blah<tab>blah' becomes 'blah\tblah' // (<tab> representing the tab character '\u0009') translation = translation.replace("\t", "\\t"); return translation; } }
true
true
private void processPoFile(BufferedReader in) throws IOException { fuzzy = false; nowrap = false; MODE currentMode = null; int currentPlural = 0; sources = new StringBuilder[2]; sources[0] = new StringBuilder(); sources[1] = new StringBuilder(); targets = new StringBuilder[2]; targets[0] = new StringBuilder(); targets[1] = new StringBuilder(); String s; while ((s = in.readLine()) != null) { /* * Removing the fuzzy markers, as it has no meanings after being * processed by omegat */ if (COMMENT_FUZZY.matcher(s).matches()) { fuzzy = true; flushTranslation(currentMode); continue; } else if (COMMENT_FUZZY_OTHER.matcher(s).matches()) { fuzzy = true; flushTranslation(currentMode); s = s.replaceAll("(.*), fuzzy(.*)", "$1$2"); } // FSM for po files if (COMMENT_NOWRAP.matcher(s).matches()) { flushTranslation(currentMode); /* * Read the no-wrap comment, indicating that the creator of the * po-file did not want long messages to be wrapped on multiple * lines. See 5.6.2 no-wrap of http://docs.oasis-open * .org/xliff/v1.2/xliff-profile-po/xliff * -profile-po-1.2-cd02.html for an example. */ nowrap = true; eol(s); continue; } Matcher m; if ((m = MSG_ID.matcher(s)).matches()) { String text = m.group(2); if (m.group(1) == null) { // non-plural ID currentMode = MODE.MSGID; sources[0].append(text); } else { // plural ID currentMode = MODE.MSGID_PLURAL; sources[1].append(text); } eol(s); continue; } if ((m = MSG_STR.matcher(s)).matches()) { String text = m.group(2); if (m.group(1) == null) { // non-plural lines currentMode = MODE.MSGSTR; targets[0].append(text); } else { currentMode = MODE.MSGSTR_PLURAL; // plurals, i.e. msgstr[N] lines if ("[0]".equals(m.group(1))) { targets[0].append(text); currentPlural = 0; } else if ("[1]".equals(m.group(1))) { targets[1].append(text); currentPlural = 1; } } continue; } if ((m = MSG_CTX.matcher(s)).matches()) { currentMode = MODE.MSGCTX; eol(s); continue; } if ((m = MSG_OTHER.matcher(s)).matches()) { String text = m.group(1); if (currentMode == null) { throw new IOException("Invalid file format"); } switch (currentMode) { case MSGID: sources[0].append(text); eol(s); break; case MSGID_PLURAL: sources[1].append(text); eol(s); break; case MSGSTR: targets[0].append(text); break; case MSGSTR_PLURAL: targets[currentPlural].append(text); break; case MSGCTX: break; } continue; } flushTranslation(currentMode); eol(s); } flushTranslation(currentMode); }
private void processPoFile(BufferedReader in) throws IOException { fuzzy = false; nowrap = false; MODE currentMode = null; int currentPlural = 0; sources = new StringBuilder[2]; sources[0] = new StringBuilder(); sources[1] = new StringBuilder(); targets = new StringBuilder[2]; targets[0] = new StringBuilder(); targets[1] = new StringBuilder(); String s; while ((s = in.readLine()) != null) { /* * Removing the fuzzy markers, as it has no meanings after being * processed by omegat */ if (COMMENT_FUZZY.matcher(s).matches()) { fuzzy = true; flushTranslation(currentMode); continue; } else if (COMMENT_FUZZY_OTHER.matcher(s).matches()) { fuzzy = true; flushTranslation(currentMode); s = s.replaceAll("(.*), fuzzy(.*)", "$1$2"); } // FSM for po files if (COMMENT_NOWRAP.matcher(s).matches()) { flushTranslation(currentMode); /* * Read the no-wrap comment, indicating that the creator of the * po-file did not want long messages to be wrapped on multiple * lines. See 5.6.2 no-wrap of http://docs.oasis-open * .org/xliff/v1.2/xliff-profile-po/xliff * -profile-po-1.2-cd02.html for an example. */ nowrap = true; eol(s); continue; } Matcher m; if ((m = MSG_ID.matcher(s)).matches()) { String text = m.group(2); if (m.group(1) == null) { // non-plural ID currentMode = MODE.MSGID; sources[0].append(text); } else { // plural ID currentMode = MODE.MSGID_PLURAL; sources[1].append(text); } eol(s); continue; } if ((m = MSG_STR.matcher(s)).matches()) { String text = m.group(2); if (m.group(1) == null) { // non-plural lines currentMode = MODE.MSGSTR; targets[0].append(text); } else { currentMode = MODE.MSGSTR_PLURAL; // plurals, i.e. msgstr[N] lines if ("[0]".equals(m.group(1))) { targets[0].append(text); currentPlural = 0; } else if ("[1]".equals(m.group(1))) { targets[1].append(text); currentPlural = 1; } } continue; } if ((m = MSG_CTX.matcher(s)).matches()) { currentMode = MODE.MSGCTX; eol(s); continue; } if ((m = MSG_OTHER.matcher(s)).matches()) { String text = m.group(1); if (currentMode == null) { throw new IOException("Invalid file format"); } switch (currentMode) { case MSGID: sources[0].append(text); eol(s); break; case MSGID_PLURAL: sources[1].append(text); eol(s); break; case MSGSTR: targets[0].append(text); break; case MSGSTR_PLURAL: targets[currentPlural].append(text); break; case MSGCTX: eol(s); break; } continue; } flushTranslation(currentMode); eol(s); } flushTranslation(currentMode); }
diff --git a/src/minecraft/liquidmechanics/common/LiquidMechanics.java b/src/minecraft/liquidmechanics/common/LiquidMechanics.java index f73e43fd..d423a861 100644 --- a/src/minecraft/liquidmechanics/common/LiquidMechanics.java +++ b/src/minecraft/liquidmechanics/common/LiquidMechanics.java @@ -1,327 +1,327 @@ package liquidmechanics.common; import java.io.File; import java.util.logging.Logger; import liquidmechanics.api.helpers.ColorCode; import liquidmechanics.api.liquids.LiquidHandler; import liquidmechanics.common.block.BlockGenerator; import liquidmechanics.common.block.BlockPipe; import liquidmechanics.common.block.BlockPumpMachine; import liquidmechanics.common.block.BlockReleaseValve; import liquidmechanics.common.block.BlockRod; import liquidmechanics.common.block.BlockSink; import liquidmechanics.common.block.BlockTank; import liquidmechanics.common.block.BlockWasteLiquid; import liquidmechanics.common.item.ItemGuage; import liquidmechanics.common.item.ItemLiquidMachine; import liquidmechanics.common.item.ItemParts; import liquidmechanics.common.item.ItemParts.Parts; import liquidmechanics.common.item.ItemPipe; import liquidmechanics.common.item.ItemReleaseValve; import liquidmechanics.common.item.ItemTank; import liquidmechanics.common.tileentity.TileEntityGenerator; import liquidmechanics.common.tileentity.TileEntityPipe; import liquidmechanics.common.tileentity.TileEntityPump; import liquidmechanics.common.tileentity.TileEntityReleaseValve; import liquidmechanics.common.tileentity.TileEntityRod; import liquidmechanics.common.tileentity.TileEntitySink; import liquidmechanics.common.tileentity.TileEntityTank; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.liquids.LiquidDictionary; import net.minecraftforge.liquids.LiquidStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import universalelectricity.prefab.TranslationHelper; import universalelectricity.prefab.network.PacketManager; import cpw.mods.fml.common.DummyModContainer; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.PostInit; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; /** * Used in the creation of a new mod class * * @author Rseifert */ @Mod(modid = LiquidMechanics.NAME, name = LiquidMechanics.NAME, version = LiquidMechanics.VERSION, dependencies = "after:BasicComponents") @NetworkMod(channels = { LiquidMechanics.CHANNEL }, clientSideRequired = true, serverSideRequired = false, packetHandler = PacketManager.class) public class LiquidMechanics extends DummyModContainer { // TODO Change in Version Release public static final String VERSION = "0.2.7"; // Constants public static final String NAME = "LiquidMechanics"; public static final String CHANNEL = "liquidMech"; public static final String PATH = "/liquidmechanics/"; public static final String RESOURCE_PATH = PATH + "resource/"; public static final String BLOCK_TEXTURE_FILE = RESOURCE_PATH + "blocks.png"; public static final String ITEM_TEXTURE_FILE = RESOURCE_PATH + "items.png"; public static final String LANGUAGE_PATH = RESOURCE_PATH + "lang/"; private static final String[] LANGUAGES_SUPPORTED = new String[] { "en_US" }; public static final Configuration CONFIGURATION = new Configuration(new File(Loader.instance().getConfigDir() + "/UniversalElectricity/", NAME + ".cfg")); public final static int BLOCK_ID_PREFIX = 3100; public final static int ITEM_ID_PREFIX = 13200; public static Block blockPipe; public static Block blockTank; public static Block blockMachine; public static Block blockRod; public static Block blockGenerator; public static Block blockReleaseValve; public static Block blockSink; public static Block blockWasteLiquid; public static LiquidStack liquidSteam; public static Item itemParts; // public static Item itemPipes; public static Item itemGauge; @SidedProxy(clientSide = "liquidmechanics.client.ClientProxy", serverSide = "liquidmechanics.common.CommonProxy") public static CommonProxy proxy; @Instance(NAME) public static LiquidMechanics instance; public static Logger FMLog = Logger.getLogger(NAME); @PreInit public void preInit(FMLPreInitializationEvent event) { FMLog.setParent(FMLLog.getLogger()); FMLog.info("Initializing..."); MinecraftForge.EVENT_BUS.register(new LiquidHandler()); instance = this; CONFIGURATION.load(); // Blocks blockPipe = new BlockPipe(this.CONFIGURATION.getBlock("Pipes", BLOCK_ID_PREFIX).getInt()); blockMachine = new BlockPumpMachine(this.CONFIGURATION.getBlock("Machines", BLOCK_ID_PREFIX + 1).getInt()); blockRod = new BlockRod(this.CONFIGURATION.getBlock("Mechanical Rod", BLOCK_ID_PREFIX + 3).getInt()); blockGenerator = new BlockGenerator((this.CONFIGURATION.getBlock("Generator", BLOCK_ID_PREFIX + 4).getInt())); blockReleaseValve = new BlockReleaseValve((this.CONFIGURATION.getBlock("Release Valve", BLOCK_ID_PREFIX + 5).getInt())); blockTank = new BlockTank(this.CONFIGURATION.getBlock("Tank", BLOCK_ID_PREFIX + 6).getInt()); blockWasteLiquid = new BlockWasteLiquid(this.CONFIGURATION.getBlock("WasteLiquid", BLOCK_ID_PREFIX + 7).getInt()); blockSink = new BlockSink(this.CONFIGURATION.getBlock("Sink", BLOCK_ID_PREFIX + 8).getInt()); // Items itemParts = new ItemParts(this.CONFIGURATION.getItem("Parts", ITEM_ID_PREFIX).getInt()); // itemPipes = new ItemPipe(this.CONFIGURATION.getItem("PipeItem", // ITEM_ID_PREFIX + 1).getInt()); // Valve item itemGauge = new ItemGuage(this.CONFIGURATION.getItem("PipeGuage", ITEM_ID_PREFIX + 3).getInt()); CONFIGURATION.save(); proxy.preInit(); // block registry GameRegistry.registerBlock(blockPipe, ItemPipe.class, "lmPipe"); GameRegistry.registerBlock(blockReleaseValve, ItemReleaseValve.class, "eValve"); GameRegistry.registerBlock(blockRod, "mechRod"); GameRegistry.registerBlock(blockGenerator, "lmGen"); GameRegistry.registerBlock(blockMachine, ItemLiquidMachine.class, "lmMachines"); GameRegistry.registerBlock(blockTank, ItemTank.class, "lmTank"); GameRegistry.registerBlock(blockSink, "lmSink"); } @Init public void Init(FMLInitializationEvent event) { FMLog.info("Loading..."); proxy.Init(); // TileEntities GameRegistry.registerTileEntity(TileEntityPipe.class, "lmPipeTile"); GameRegistry.registerTileEntity(TileEntityPump.class, "lmPumpTile"); GameRegistry.registerTileEntity(TileEntityRod.class, "lmRodTile"); GameRegistry.registerTileEntity(TileEntityReleaseValve.class, "lmeValve"); GameRegistry.registerTileEntity(TileEntityTank.class, "lmTank"); GameRegistry.registerTileEntity(TileEntityGenerator.class, "lmGen"); GameRegistry.registerTileEntity(TileEntitySink.class, "lmSink"); FMLog.info("Fluid Mechanics Loaded: " + TranslationHelper.loadLanguages(LANGUAGE_PATH, LANGUAGES_SUPPORTED) + " Languages."); } @PostInit public void PostInit(FMLPostInitializationEvent event) { FMLog.info("Finalizing..."); proxy.postInit(); TabLiquidMechanics.setItemStack(new ItemStack(blockPipe, 1, 4)); // generator CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(this.blockGenerator, 1), new Object[] { "@T@", "OVO", "@T@", 'T', new ItemStack(LiquidMechanics.blockRod, 1), '@', "plateSteel", 'O', "basicCircuit", 'V', "motor" })); // pipe gauge GameRegistry.addRecipe(new ItemStack(this.itemGauge, 1, 0), new Object[] { "TVT", " T ", 'V', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'T', new ItemStack(itemParts, 1, Parts.Iron.ordinal()) }); // iron tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Iron.ordinal()), new Object[] { "@@@", '@', Item.ingotIron }); // bronze tube CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(itemParts, 4, Parts.Bronze.ordinal()), new Object[] { "@@@", '@', "ingotBronze" })); // obby tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Obby.ordinal()), new Object[] { "@@@", '@', Block.obsidian }); // nether tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Nether.ordinal()), new Object[] { "N@N", 'N', Block.netherrack, '@', new ItemStack(itemParts, 2, Parts.Obby.ordinal()) }); // seal GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Seal.ordinal()), new Object[] { "@@", "@@", '@', Item.leather }); // slime steal GameRegistry.addShapelessRecipe(new ItemStack(itemParts, 1, Parts.SlimeSeal.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Seal.ordinal()), new ItemStack(Item.slimeBall, 1) }); // part valve GameRegistry.addRecipe(new ItemStack(itemParts, 1, Parts.Valve.ordinal()), new Object[] { "T@T", 'T', new ItemStack(itemParts, 1, Parts.Iron.ordinal()), '@', Block.lever }); // unfinished tank GameRegistry.addRecipe(new ItemStack(itemParts, 1, Parts.Tank.ordinal()), new Object[] { " @ ", "@ @", " @ ", '@', Item.ingotIron }); // mechanical rod GameRegistry.addRecipe(new ItemStack(blockRod, 1), new Object[] { "I@I", 'I', Item.ingotIron, '@', new ItemStack(itemParts, 1, Parts.Iron.ordinal()) }); // Iron Pipe GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 1, 15), new Object[] { new ItemStack(itemParts, 1, Parts.Iron.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); for (int it = 0; it < 15; it++) { if (it != ColorCode.WHITE.ordinal() && it != ColorCode.ORANGE.ordinal()) { GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 4, it), new Object[] { new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(Item.dyePowder, 1, it) }); } } // steam pipes GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 1, ColorCode.ORANGE.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Bronze.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); // milk pipes GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 4, ColorCode.WHITE.ordinal()), new Object[] { new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), - new ItemStack(Item.dyePowder, 1, 0) }); + new ItemStack(Item.dyePowder, 1, 15) }); // steam tank GameRegistry.addShapelessRecipe(new ItemStack(blockTank, 1, ColorCode.ORANGE.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Tank.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()), new ItemStack(itemParts, 1, Parts.Bronze.ordinal()), new ItemStack(itemParts, 1, Parts.Bronze.ordinal()) }); // lava tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.RED.ordinal()), new Object[] { "N@N", "@ @", "N@N", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.obsidian, 'N', Block.netherrack }); // water tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.BLUE.ordinal()), new Object[] { "@G@", "STS", "@G@", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.planks, 'G', Block.glass, 'S', new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); // milk tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.WHITE.ordinal()), new Object[] { "W@W", "WTW", "W@W", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.stone, 'W', Block.planks }); // generic Tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.NONE.ordinal()), new Object[] { "@@@", "@T@", "@@@", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.stone }); // pump CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(blockMachine, 1, 0), new Object[] { "C@C", "BMB", "@X@", '@', "plateSteel", 'X', new ItemStack(blockPipe, 1, ColorCode.NONE.ordinal()), 'B', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'C',"basicCircuit", 'M', "motor" })); // release valve GameRegistry.addRecipe(new ItemStack(blockReleaseValve, 1), new Object[] { "RPR", "PVP", "RPR", 'P', new ItemStack(blockPipe, 1, 15), 'V', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'R', Item.redstone }); // sink GameRegistry.addRecipe(new ItemStack(blockSink, 1), new Object[] { "I I", "SIS", "SPS", 'P', new ItemStack(blockPipe, 1, 15), 'I', Item.ingotIron, 'S', Block.stone }); // reg ore directory for parts OreDictionary.registerOre("bronzeTube", new ItemStack(itemParts, 1, Parts.Bronze.ordinal())); OreDictionary.registerOre("ironTube", new ItemStack(itemParts, 1, Parts.Iron.ordinal())); OreDictionary.registerOre("netherTube", new ItemStack(itemParts, 1, Parts.Nether.ordinal())); OreDictionary.registerOre("obbyTube", new ItemStack(itemParts, 1, Parts.Obby.ordinal())); OreDictionary.registerOre("leatherSeal", new ItemStack(itemParts, 1, Parts.Seal.ordinal())); OreDictionary.registerOre("leatherSlimeSeal", new ItemStack(itemParts, 1, Parts.SlimeSeal.ordinal())); OreDictionary.registerOre("valvePart", new ItemStack(itemParts, 1, Parts.Valve.ordinal())); OreDictionary.registerOre("bronzeTube", new ItemStack(itemParts, 1, Parts.Bronze.ordinal())); OreDictionary.registerOre("unfinishedTank", new ItemStack(itemParts, 1, Parts.Tank.ordinal())); // add Default Liquids to current list, done last to let other mods use // there liquid data first if used LiquidStack waste = LiquidDictionary.getOrCreateLiquid("Waste", new LiquidStack(LiquidMechanics.blockWasteLiquid, 1)); LiquidHandler.addDefaultLiquids(); FMLog.info("Done Loading"); } }
true
true
public void PostInit(FMLPostInitializationEvent event) { FMLog.info("Finalizing..."); proxy.postInit(); TabLiquidMechanics.setItemStack(new ItemStack(blockPipe, 1, 4)); // generator CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(this.blockGenerator, 1), new Object[] { "@T@", "OVO", "@T@", 'T', new ItemStack(LiquidMechanics.blockRod, 1), '@', "plateSteel", 'O', "basicCircuit", 'V', "motor" })); // pipe gauge GameRegistry.addRecipe(new ItemStack(this.itemGauge, 1, 0), new Object[] { "TVT", " T ", 'V', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'T', new ItemStack(itemParts, 1, Parts.Iron.ordinal()) }); // iron tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Iron.ordinal()), new Object[] { "@@@", '@', Item.ingotIron }); // bronze tube CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(itemParts, 4, Parts.Bronze.ordinal()), new Object[] { "@@@", '@', "ingotBronze" })); // obby tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Obby.ordinal()), new Object[] { "@@@", '@', Block.obsidian }); // nether tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Nether.ordinal()), new Object[] { "N@N", 'N', Block.netherrack, '@', new ItemStack(itemParts, 2, Parts.Obby.ordinal()) }); // seal GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Seal.ordinal()), new Object[] { "@@", "@@", '@', Item.leather }); // slime steal GameRegistry.addShapelessRecipe(new ItemStack(itemParts, 1, Parts.SlimeSeal.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Seal.ordinal()), new ItemStack(Item.slimeBall, 1) }); // part valve GameRegistry.addRecipe(new ItemStack(itemParts, 1, Parts.Valve.ordinal()), new Object[] { "T@T", 'T', new ItemStack(itemParts, 1, Parts.Iron.ordinal()), '@', Block.lever }); // unfinished tank GameRegistry.addRecipe(new ItemStack(itemParts, 1, Parts.Tank.ordinal()), new Object[] { " @ ", "@ @", " @ ", '@', Item.ingotIron }); // mechanical rod GameRegistry.addRecipe(new ItemStack(blockRod, 1), new Object[] { "I@I", 'I', Item.ingotIron, '@', new ItemStack(itemParts, 1, Parts.Iron.ordinal()) }); // Iron Pipe GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 1, 15), new Object[] { new ItemStack(itemParts, 1, Parts.Iron.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); for (int it = 0; it < 15; it++) { if (it != ColorCode.WHITE.ordinal() && it != ColorCode.ORANGE.ordinal()) { GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 4, it), new Object[] { new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(Item.dyePowder, 1, it) }); } } // steam pipes GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 1, ColorCode.ORANGE.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Bronze.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); // milk pipes GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 4, ColorCode.WHITE.ordinal()), new Object[] { new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(Item.dyePowder, 1, 0) }); // steam tank GameRegistry.addShapelessRecipe(new ItemStack(blockTank, 1, ColorCode.ORANGE.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Tank.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()), new ItemStack(itemParts, 1, Parts.Bronze.ordinal()), new ItemStack(itemParts, 1, Parts.Bronze.ordinal()) }); // lava tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.RED.ordinal()), new Object[] { "N@N", "@ @", "N@N", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.obsidian, 'N', Block.netherrack }); // water tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.BLUE.ordinal()), new Object[] { "@G@", "STS", "@G@", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.planks, 'G', Block.glass, 'S', new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); // milk tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.WHITE.ordinal()), new Object[] { "W@W", "WTW", "W@W", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.stone, 'W', Block.planks }); // generic Tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.NONE.ordinal()), new Object[] { "@@@", "@T@", "@@@", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.stone }); // pump CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(blockMachine, 1, 0), new Object[] { "C@C", "BMB", "@X@", '@', "plateSteel", 'X', new ItemStack(blockPipe, 1, ColorCode.NONE.ordinal()), 'B', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'C',"basicCircuit", 'M', "motor" })); // release valve GameRegistry.addRecipe(new ItemStack(blockReleaseValve, 1), new Object[] { "RPR", "PVP", "RPR", 'P', new ItemStack(blockPipe, 1, 15), 'V', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'R', Item.redstone }); // sink GameRegistry.addRecipe(new ItemStack(blockSink, 1), new Object[] { "I I", "SIS", "SPS", 'P', new ItemStack(blockPipe, 1, 15), 'I', Item.ingotIron, 'S', Block.stone }); // reg ore directory for parts OreDictionary.registerOre("bronzeTube", new ItemStack(itemParts, 1, Parts.Bronze.ordinal())); OreDictionary.registerOre("ironTube", new ItemStack(itemParts, 1, Parts.Iron.ordinal())); OreDictionary.registerOre("netherTube", new ItemStack(itemParts, 1, Parts.Nether.ordinal())); OreDictionary.registerOre("obbyTube", new ItemStack(itemParts, 1, Parts.Obby.ordinal())); OreDictionary.registerOre("leatherSeal", new ItemStack(itemParts, 1, Parts.Seal.ordinal())); OreDictionary.registerOre("leatherSlimeSeal", new ItemStack(itemParts, 1, Parts.SlimeSeal.ordinal())); OreDictionary.registerOre("valvePart", new ItemStack(itemParts, 1, Parts.Valve.ordinal())); OreDictionary.registerOre("bronzeTube", new ItemStack(itemParts, 1, Parts.Bronze.ordinal())); OreDictionary.registerOre("unfinishedTank", new ItemStack(itemParts, 1, Parts.Tank.ordinal())); // add Default Liquids to current list, done last to let other mods use // there liquid data first if used LiquidStack waste = LiquidDictionary.getOrCreateLiquid("Waste", new LiquidStack(LiquidMechanics.blockWasteLiquid, 1)); LiquidHandler.addDefaultLiquids(); FMLog.info("Done Loading"); }
public void PostInit(FMLPostInitializationEvent event) { FMLog.info("Finalizing..."); proxy.postInit(); TabLiquidMechanics.setItemStack(new ItemStack(blockPipe, 1, 4)); // generator CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(this.blockGenerator, 1), new Object[] { "@T@", "OVO", "@T@", 'T', new ItemStack(LiquidMechanics.blockRod, 1), '@', "plateSteel", 'O', "basicCircuit", 'V', "motor" })); // pipe gauge GameRegistry.addRecipe(new ItemStack(this.itemGauge, 1, 0), new Object[] { "TVT", " T ", 'V', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'T', new ItemStack(itemParts, 1, Parts.Iron.ordinal()) }); // iron tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Iron.ordinal()), new Object[] { "@@@", '@', Item.ingotIron }); // bronze tube CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(itemParts, 4, Parts.Bronze.ordinal()), new Object[] { "@@@", '@', "ingotBronze" })); // obby tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Obby.ordinal()), new Object[] { "@@@", '@', Block.obsidian }); // nether tube GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Nether.ordinal()), new Object[] { "N@N", 'N', Block.netherrack, '@', new ItemStack(itemParts, 2, Parts.Obby.ordinal()) }); // seal GameRegistry.addRecipe(new ItemStack(itemParts, 4, Parts.Seal.ordinal()), new Object[] { "@@", "@@", '@', Item.leather }); // slime steal GameRegistry.addShapelessRecipe(new ItemStack(itemParts, 1, Parts.SlimeSeal.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Seal.ordinal()), new ItemStack(Item.slimeBall, 1) }); // part valve GameRegistry.addRecipe(new ItemStack(itemParts, 1, Parts.Valve.ordinal()), new Object[] { "T@T", 'T', new ItemStack(itemParts, 1, Parts.Iron.ordinal()), '@', Block.lever }); // unfinished tank GameRegistry.addRecipe(new ItemStack(itemParts, 1, Parts.Tank.ordinal()), new Object[] { " @ ", "@ @", " @ ", '@', Item.ingotIron }); // mechanical rod GameRegistry.addRecipe(new ItemStack(blockRod, 1), new Object[] { "I@I", 'I', Item.ingotIron, '@', new ItemStack(itemParts, 1, Parts.Iron.ordinal()) }); // Iron Pipe GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 1, 15), new Object[] { new ItemStack(itemParts, 1, Parts.Iron.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); for (int it = 0; it < 15; it++) { if (it != ColorCode.WHITE.ordinal() && it != ColorCode.ORANGE.ordinal()) { GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 4, it), new Object[] { new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(Item.dyePowder, 1, it) }); } } // steam pipes GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 1, ColorCode.ORANGE.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Bronze.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); // milk pipes GameRegistry.addShapelessRecipe(new ItemStack(blockPipe, 4, ColorCode.WHITE.ordinal()), new Object[] { new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(blockPipe, 1, 15), new ItemStack(Item.dyePowder, 1, 15) }); // steam tank GameRegistry.addShapelessRecipe(new ItemStack(blockTank, 1, ColorCode.ORANGE.ordinal()), new Object[] { new ItemStack(itemParts, 1, Parts.Tank.ordinal()), new ItemStack(itemParts, 1, Parts.Seal.ordinal()), new ItemStack(itemParts, 1, Parts.Bronze.ordinal()), new ItemStack(itemParts, 1, Parts.Bronze.ordinal()) }); // lava tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.RED.ordinal()), new Object[] { "N@N", "@ @", "N@N", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.obsidian, 'N', Block.netherrack }); // water tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.BLUE.ordinal()), new Object[] { "@G@", "STS", "@G@", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.planks, 'G', Block.glass, 'S', new ItemStack(itemParts, 1, Parts.Seal.ordinal()) }); // milk tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.WHITE.ordinal()), new Object[] { "W@W", "WTW", "W@W", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.stone, 'W', Block.planks }); // generic Tank GameRegistry.addRecipe(new ItemStack(blockTank, 1, ColorCode.NONE.ordinal()), new Object[] { "@@@", "@T@", "@@@", 'T', new ItemStack(itemParts, 1, Parts.Tank.ordinal()), '@', Block.stone }); // pump CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(new ItemStack(blockMachine, 1, 0), new Object[] { "C@C", "BMB", "@X@", '@', "plateSteel", 'X', new ItemStack(blockPipe, 1, ColorCode.NONE.ordinal()), 'B', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'C',"basicCircuit", 'M', "motor" })); // release valve GameRegistry.addRecipe(new ItemStack(blockReleaseValve, 1), new Object[] { "RPR", "PVP", "RPR", 'P', new ItemStack(blockPipe, 1, 15), 'V', new ItemStack(itemParts, 1, Parts.Valve.ordinal()), 'R', Item.redstone }); // sink GameRegistry.addRecipe(new ItemStack(blockSink, 1), new Object[] { "I I", "SIS", "SPS", 'P', new ItemStack(blockPipe, 1, 15), 'I', Item.ingotIron, 'S', Block.stone }); // reg ore directory for parts OreDictionary.registerOre("bronzeTube", new ItemStack(itemParts, 1, Parts.Bronze.ordinal())); OreDictionary.registerOre("ironTube", new ItemStack(itemParts, 1, Parts.Iron.ordinal())); OreDictionary.registerOre("netherTube", new ItemStack(itemParts, 1, Parts.Nether.ordinal())); OreDictionary.registerOre("obbyTube", new ItemStack(itemParts, 1, Parts.Obby.ordinal())); OreDictionary.registerOre("leatherSeal", new ItemStack(itemParts, 1, Parts.Seal.ordinal())); OreDictionary.registerOre("leatherSlimeSeal", new ItemStack(itemParts, 1, Parts.SlimeSeal.ordinal())); OreDictionary.registerOre("valvePart", new ItemStack(itemParts, 1, Parts.Valve.ordinal())); OreDictionary.registerOre("bronzeTube", new ItemStack(itemParts, 1, Parts.Bronze.ordinal())); OreDictionary.registerOre("unfinishedTank", new ItemStack(itemParts, 1, Parts.Tank.ordinal())); // add Default Liquids to current list, done last to let other mods use // there liquid data first if used LiquidStack waste = LiquidDictionary.getOrCreateLiquid("Waste", new LiquidStack(LiquidMechanics.blockWasteLiquid, 1)); LiquidHandler.addDefaultLiquids(); FMLog.info("Done Loading"); }
diff --git a/demonstration/src/java/org/apache/commons/logging/proofofconcept/runner/ClassLoaderRunner.java b/demonstration/src/java/org/apache/commons/logging/proofofconcept/runner/ClassLoaderRunner.java index 21a8f94..a486e39 100644 --- a/demonstration/src/java/org/apache/commons/logging/proofofconcept/runner/ClassLoaderRunner.java +++ b/demonstration/src/java/org/apache/commons/logging/proofofconcept/runner/ClassLoaderRunner.java @@ -1,219 +1,222 @@ /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.logging.proofofconcept.runner; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * Runs demonstrations with complex classloader hierarchies * and outputs formatted descriptions of the tests run. */ public class ClassLoaderRunner { private static final Class[] EMPTY_CLASSES = {}; private static final Object[] EMPTY_OBJECTS = {}; private static final URL[] EMPTY_URLS = {}; public static final int LOG4J_JAR = 1 << 0; public static final int STATIC_JAR = 1 << 1; public static final int JCL_JAR = 1 << 2; public static final int CALLER_JAR = 1 << 3; public static final int API_JAR = 1 << 4; private final URL log4jUrl; private final URL staticUrl; private final URL jclUrl; private final URL callerUrl; private final URL apiUrl; /** * Loads URLs. * @throws MalformedURLException when any of these URLs cannot * be resolved */ public ClassLoaderRunner() throws MalformedURLException { log4jUrl = new URL("file:log4j.jar"); staticUrl = new URL("file:static.jar"); jclUrl = new URL("file:commons-logging.jar"); callerUrl = new URL("file:caller.jar"); apiUrl = new URL("file:commons-logging-api.jar"); } /** * Runs a demonstration. * @param caseName human name for test (used for output) * @param parentJars bitwise code for jars to be definable * by the parent classloader * @param childJars bitwise code for jars to be definable * by the child classloader * @param setContextClassloader true if the context classloader * should be set to the child classloader, * false preserves the default * @param childFirst true if the child classloader * should delegate only if it cannot define a class, * false otherwise */ public void run(String caseName, int parentJars, int childJars, boolean setContextClassloader, boolean childFirst) { System.out.println(""); System.out.println("*****************************"); System.out.println(""); System.out.println("Running case " + caseName + "..."); System.out.println(""); URL[] parentUrls = urlsForJars(parentJars, "Parent Classloader: "); URL[] childUrls = urlsForJars(childJars, "Child Classloader: "); System.out.println("Child context classloader: " + setContextClassloader); System.out.println("Child first: " + childFirst); System.out.println(""); run("org.apache.commons.logging.proofofconcept.caller.JCLDemonstrator", parentUrls, childUrls, setContextClassloader, childFirst); System.out.println("*****************************"); } /** * Converts a bitwise jar code into an array of URLs * containing approapriate URLs. * @param jars bitwise jar code * @param humanLoaderName human name for classloader * @return <code>URL</code> array, not null possibly empty */ private URL[] urlsForJars(int jars, String humanLoaderName) { List urls = new ArrayList();; if ((LOG4J_JAR & jars) > 0) { urls.add(log4jUrl); } if ((STATIC_JAR & jars) > 0) { urls.add(staticUrl); } if ((JCL_JAR & jars) > 0) { urls.add(jclUrl); } if ((API_JAR & jars) > 0) { urls.add(apiUrl); } if ((CALLER_JAR & jars) > 0) { urls.add(callerUrl); } System.out.println(humanLoaderName + " " + urls); URL[] results = (URL[]) urls.toArray(EMPTY_URLS); return results; } /** * Runs a demonstration. * @param testName the human name for this test * @param parentClassloaderUrls the <code>URL</code>'s which should * be definable by the parent classloader, not null * @param childClassloaderUrls the <code>URL</code>'s which should * be definable by the child classloader, not null * @param setContextClassloader true if the context * classloader should be set to the child classloader, * false if the default context classloader should * be maintained * @param childFirst true if the child classloader * should delegate only when it cannot define the class, * false otherwise */ public void run (String testName, URL[] parentClassloaderUrls, URL[] childClassloaderUrls, boolean setContextClassloader, boolean childFirst) { URLClassLoader parent = new URLClassLoader(parentClassloaderUrls); URLClassLoader child = null; if (childFirst) { child = new ChildFirstClassLoader(childClassloaderUrls, parent); } else { child = new URLClassLoader(childClassloaderUrls, parent); } if (setContextClassloader) { Thread.currentThread().setContextClassLoader(child); + } else { + ClassLoader system = ClassLoader.getSystemClassLoader(); + Thread.currentThread().setContextClassLoader(system); } logDefiningLoaders(child, parent); try { Class callerClass = child.loadClass(testName); Method runMethod = callerClass.getDeclaredMethod("run", EMPTY_CLASSES); Object caller = callerClass.newInstance(); runMethod.invoke(caller, EMPTY_OBJECTS); } catch (Exception e) { System.out.println("Cannot execute test: " + e.getMessage()); e.printStackTrace(); } } /** * Logs the classloaders which define important classes * @param child child <code>ClassLoader</code>, not null * @param parent parent <code>ClassLoader</code>, not null */ private void logDefiningLoaders(ClassLoader child, ClassLoader parent) { System.out.println(""); logDefiningLoaders(child, parent, "org.apache.commons.logging.LogFactory", "JCL "); logDefiningLoaders(child, parent, "org.apache.log4j.Logger", "Log4j "); logDefiningLoaders(child, parent, "org.apache.commons.logging.proofofconcept.staticlogger.StaticLog4JLogger", "Static Logger"); logDefiningLoaders(child, parent, "org.apache.commons.logging.proofofconcept.caller.SomeObject", "Caller "); System.out.println(""); } /** * Logs the classloader which defines the class with the given name whose * loading is initiated by the child classloader. * @param child child <code>ClassLoader</code>, not null * @param parent parent <code>ClassLoader</code>, not null * @param className name of the class to be loaded * @param humanName the human name for the class */ private void logDefiningLoaders(ClassLoader child, ClassLoader parent, String className, String humanName) { try { Class clazz = child.loadClass(className); ClassLoader definingLoader = clazz.getClassLoader(); if (definingLoader == null) { System.out.println(humanName + " defined by SYSTEM class loader"); } else if (definingLoader.equals(child)) { System.out.println(humanName + " defined by CHILD class loader"); } else if (definingLoader.equals(parent)) { System.out.println(humanName + " defined by PARENT class loader"); } else { System.out.println(humanName + " defined by OTHER class loader"); } } catch (Exception e) { System.out.println(humanName + " NOT LOADABLE by application classloader"); } } }
true
true
public void run (String testName, URL[] parentClassloaderUrls, URL[] childClassloaderUrls, boolean setContextClassloader, boolean childFirst) { URLClassLoader parent = new URLClassLoader(parentClassloaderUrls); URLClassLoader child = null; if (childFirst) { child = new ChildFirstClassLoader(childClassloaderUrls, parent); } else { child = new URLClassLoader(childClassloaderUrls, parent); } if (setContextClassloader) { Thread.currentThread().setContextClassLoader(child); } logDefiningLoaders(child, parent); try { Class callerClass = child.loadClass(testName); Method runMethod = callerClass.getDeclaredMethod("run", EMPTY_CLASSES); Object caller = callerClass.newInstance(); runMethod.invoke(caller, EMPTY_OBJECTS); } catch (Exception e) { System.out.println("Cannot execute test: " + e.getMessage()); e.printStackTrace(); } }
public void run (String testName, URL[] parentClassloaderUrls, URL[] childClassloaderUrls, boolean setContextClassloader, boolean childFirst) { URLClassLoader parent = new URLClassLoader(parentClassloaderUrls); URLClassLoader child = null; if (childFirst) { child = new ChildFirstClassLoader(childClassloaderUrls, parent); } else { child = new URLClassLoader(childClassloaderUrls, parent); } if (setContextClassloader) { Thread.currentThread().setContextClassLoader(child); } else { ClassLoader system = ClassLoader.getSystemClassLoader(); Thread.currentThread().setContextClassLoader(system); } logDefiningLoaders(child, parent); try { Class callerClass = child.loadClass(testName); Method runMethod = callerClass.getDeclaredMethod("run", EMPTY_CLASSES); Object caller = callerClass.newInstance(); runMethod.invoke(caller, EMPTY_OBJECTS); } catch (Exception e) { System.out.println("Cannot execute test: " + e.getMessage()); e.printStackTrace(); } }
diff --git a/com/buglabs/application/ServiceTrackerHelper.java b/com/buglabs/application/ServiceTrackerHelper.java index 01eca75..33a385c 100644 --- a/com/buglabs/application/ServiceTrackerHelper.java +++ b/com/buglabs/application/ServiceTrackerHelper.java @@ -1,298 +1,299 @@ /******************************************************************************* * Copyright (c) 2008, 2009 Bug Labs, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Bug Labs, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package com.buglabs.application; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import com.buglabs.util.ServiceFilterGenerator; /** * Helper class to construct ServiceTrackers. * * @author kgilmer * */ public class ServiceTrackerHelper implements ServiceTrackerCustomizer { private final ManagedRunnable runnable; private final String[] services; private int sc; private final BundleContext bc; private Thread thread; private Map serviceMap; /** * A runnable that provides access to OSGi services passed to * ServiceTrackerHelper. * * Runnable will be started when all service are available, and interrupted * if any services become unavailable. * * @author kgilmer * */ public interface ManagedRunnable { public abstract void run(Map services); } /** * A Runnable and ServiceTrackerCustomizer that allows for fine-grained * application behavior based on OSGi service activity. An implementation of * this can be passed anywhere a ServiceTrackerRunnable is expected and * behavior will change accordingly. * * Runnable is not started automatically. It is up to the implementor to * decide when and how to create and start the thread. * * @author kgilmer * */ public interface UnmanagedRunnable extends ManagedRunnable, ServiceTrackerCustomizer { } /** * A ManagedRunnable that calls run() in-line with parent thread. This is useful if the client * does not need to create a new thread or wants to manage thread creation independently. * @author kgilmer * */ public interface ManagedInlineRunnable extends ManagedRunnable { } public ServiceTrackerHelper(BundleContext bc, ManagedRunnable t, String[] services) { this.bc = bc; this.runnable = t; this.services = services; this.serviceMap = new HashMap(); sc = 0; } public Object addingService(ServiceReference arg0) { sc++; Object svc = bc.getService(arg0); - serviceMap.put(arg0.getProperty(Constants.OBJECTCLASS), svc); + String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0]; + serviceMap.put(key, svc); if (thread == null && sc == services.length && !(runnable instanceof UnmanagedRunnable)) { if (runnable instanceof ManagedInlineRunnable) { //Client wants to run in same thread, just call method. runnable.run(serviceMap); } else { //Create new thread and pass off to client Runnable implementation. thread = new Thread(new Runnable() { public void run() { runnable.run(serviceMap); } }); thread.start(); } } if (runnable instanceof UnmanagedRunnable) { return ((UnmanagedRunnable) runnable).addingService(arg0); } return svc; } public void modifiedService(ServiceReference arg0, Object arg1) { if (runnable instanceof UnmanagedRunnable) { ((UnmanagedRunnable) runnable).modifiedService(arg0, arg1); } } public void removedService(ServiceReference arg0, Object arg1) { sc--; if (!(thread == null) && !thread.isInterrupted() && !(runnable instanceof UnmanagedRunnable)) { thread.interrupt(); return; } if (runnable instanceof UnmanagedRunnable) { ((UnmanagedRunnable) runnable).removedService(arg0, arg1); } } /** * Convenience method for creating and opening a * ServiceTrackerRunnable-based ServiceTracker. * * @param context * @param services * @param runnable * @return * @throws InvalidSyntaxException */ public static ServiceTracker openServiceTracker(BundleContext context, String[] services, ManagedRunnable runnable) throws InvalidSyntaxException { ServiceTracker st = new ServiceTracker(context, ServiceFilterGenerator.generateServiceFilter(context, services), new ServiceTrackerHelper(context, runnable, services)); st.open(); return st; } /** * Convenience method for creating and opening a * ServiceTrackerRunnable-based ServiceTracker. * * @param context * @param services * @param filter * @param runnable * @return * @throws InvalidSyntaxException */ public static ServiceTracker openServiceTracker(BundleContext context, String[] services, Filter filter, ManagedRunnable runnable) throws InvalidSyntaxException { ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerHelper(context, runnable, services)); st.open(); return st; } /** * @param context * BundleContext * @param services * Services to be tracked * @param runnable * Object handling service changes * @return * @throws InvalidSyntaxException */ public static ServiceTracker createAndOpen(BundleContext context, List services, RunnableWithServices runnable) throws InvalidSyntaxException { Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(services)); ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, services)); st.open(); return st; } /** * @param context * BundleContext * @param services * Services to be tracked * @param runnable * Object handling service changes * @return * @throws InvalidSyntaxException * */ public static ServiceTracker createAndOpen(BundleContext context, String[] services, RunnableWithServices runnable) throws InvalidSyntaxException { Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(services))); ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(services))); st.open(); return st; } /** * @param context * BundleContext * @param service * Service to be tracked * @param runnable * Object handling service changes * @return * @throws InvalidSyntaxException */ public static ServiceTracker createAndOpen(BundleContext context, String service, RunnableWithServices runnable) throws InvalidSyntaxException { Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(new String[] { service }))); ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(new String[] { service }))); st.open(); return st; } /** * @param context * BundleContext * @param services * Services to be tracked * @param runnable * Object handling service changes * @return * @throws InvalidSyntaxException */ public static ServiceTracker createAndOpen(BundleContext context, List services, ServiceChangeListener runnable) throws InvalidSyntaxException { Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(services)); ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, services)); st.open(); return st; } /** * @param context * BundleContext * @param services * Services to be tracked * @param runnable * Object handling service changes * @return * @throws InvalidSyntaxException */ public static ServiceTracker createAndOpen(BundleContext context, String[] services, ServiceChangeListener runnable) throws InvalidSyntaxException { Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(services))); ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(services))); st.open(); return st; } /** * @param context * BundleContext * @param services * Services to be tracked * @param runnable * Object handling service changes * @return * @throws InvalidSyntaxException */ public static ServiceTracker createAndOpen(BundleContext context, String service, ServiceChangeListener runnable) throws InvalidSyntaxException { Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(new String[] { service }))); ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(new String[] { service }))); st.open(); return st; } }
true
true
public Object addingService(ServiceReference arg0) { sc++; Object svc = bc.getService(arg0); serviceMap.put(arg0.getProperty(Constants.OBJECTCLASS), svc); if (thread == null && sc == services.length && !(runnable instanceof UnmanagedRunnable)) { if (runnable instanceof ManagedInlineRunnable) { //Client wants to run in same thread, just call method. runnable.run(serviceMap); } else { //Create new thread and pass off to client Runnable implementation. thread = new Thread(new Runnable() { public void run() { runnable.run(serviceMap); } }); thread.start(); } } if (runnable instanceof UnmanagedRunnable) { return ((UnmanagedRunnable) runnable).addingService(arg0); } return svc; }
public Object addingService(ServiceReference arg0) { sc++; Object svc = bc.getService(arg0); String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0]; serviceMap.put(key, svc); if (thread == null && sc == services.length && !(runnable instanceof UnmanagedRunnable)) { if (runnable instanceof ManagedInlineRunnable) { //Client wants to run in same thread, just call method. runnable.run(serviceMap); } else { //Create new thread and pass off to client Runnable implementation. thread = new Thread(new Runnable() { public void run() { runnable.run(serviceMap); } }); thread.start(); } } if (runnable instanceof UnmanagedRunnable) { return ((UnmanagedRunnable) runnable).addingService(arg0); } return svc; }
diff --git a/src/scratchpad/src/org/apache/poi/hwpf/converter/DefaultFontReplacer.java b/src/scratchpad/src/org/apache/poi/hwpf/converter/DefaultFontReplacer.java index b99816e6d..7f9f34a8c 100644 --- a/src/scratchpad/src/org/apache/poi/hwpf/converter/DefaultFontReplacer.java +++ b/src/scratchpad/src/org/apache/poi/hwpf/converter/DefaultFontReplacer.java @@ -1,71 +1,71 @@ package org.apache.poi.hwpf.converter; public class DefaultFontReplacer implements FontReplacer { public Triplet update( Triplet original ) { - if ( !AbstractWordUtils.isNotEmpty( original.fontName ) ) + if ( AbstractWordUtils.isNotEmpty( original.fontName ) ) { String fontName = original.fontName; if ( fontName.endsWith( " Regular" ) ) fontName = AbstractWordUtils.substringBeforeLast( fontName, " Regular" ); if ( fontName .endsWith( " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439" ) ) fontName = AbstractWordUtils .substringBeforeLast( fontName, " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439" ) + " Bold"; if ( fontName .endsWith( " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439 \u041A\u0443\u0440\u0441\u0438\u0432" ) ) fontName = AbstractWordUtils .substringBeforeLast( fontName, " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439 \u041A\u0443\u0440\u0441\u0438\u0432" ) + " Bold Italic"; if ( fontName.endsWith( " \u041A\u0443\u0440\u0441\u0438\u0432" ) ) fontName = AbstractWordUtils.substringBeforeLast( fontName, " \u041A\u0443\u0440\u0441\u0438\u0432" ) + " Italic"; original.fontName = fontName; } - if ( !AbstractWordUtils.isNotEmpty( original.fontName ) ) + if ( AbstractWordUtils.isNotEmpty( original.fontName ) ) { if ( "Times Regular".equals( original.fontName ) || "Times-Regular".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = false; original.italic = false; } if ( "Times Bold".equals( original.fontName ) || "Times-Bold".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = true; original.italic = false; } if ( "Times Italic".equals( original.fontName ) || "Times-Italic".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = false; original.italic = true; } if ( "Times Bold Italic".equals( original.fontName ) || "Times-BoldItalic".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = true; original.italic = true; } } return original; } }
false
true
public Triplet update( Triplet original ) { if ( !AbstractWordUtils.isNotEmpty( original.fontName ) ) { String fontName = original.fontName; if ( fontName.endsWith( " Regular" ) ) fontName = AbstractWordUtils.substringBeforeLast( fontName, " Regular" ); if ( fontName .endsWith( " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439" ) ) fontName = AbstractWordUtils .substringBeforeLast( fontName, " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439" ) + " Bold"; if ( fontName .endsWith( " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439 \u041A\u0443\u0440\u0441\u0438\u0432" ) ) fontName = AbstractWordUtils .substringBeforeLast( fontName, " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439 \u041A\u0443\u0440\u0441\u0438\u0432" ) + " Bold Italic"; if ( fontName.endsWith( " \u041A\u0443\u0440\u0441\u0438\u0432" ) ) fontName = AbstractWordUtils.substringBeforeLast( fontName, " \u041A\u0443\u0440\u0441\u0438\u0432" ) + " Italic"; original.fontName = fontName; } if ( !AbstractWordUtils.isNotEmpty( original.fontName ) ) { if ( "Times Regular".equals( original.fontName ) || "Times-Regular".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = false; original.italic = false; } if ( "Times Bold".equals( original.fontName ) || "Times-Bold".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = true; original.italic = false; } if ( "Times Italic".equals( original.fontName ) || "Times-Italic".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = false; original.italic = true; } if ( "Times Bold Italic".equals( original.fontName ) || "Times-BoldItalic".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = true; original.italic = true; } } return original; }
public Triplet update( Triplet original ) { if ( AbstractWordUtils.isNotEmpty( original.fontName ) ) { String fontName = original.fontName; if ( fontName.endsWith( " Regular" ) ) fontName = AbstractWordUtils.substringBeforeLast( fontName, " Regular" ); if ( fontName .endsWith( " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439" ) ) fontName = AbstractWordUtils .substringBeforeLast( fontName, " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439" ) + " Bold"; if ( fontName .endsWith( " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439 \u041A\u0443\u0440\u0441\u0438\u0432" ) ) fontName = AbstractWordUtils .substringBeforeLast( fontName, " \u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439 \u041A\u0443\u0440\u0441\u0438\u0432" ) + " Bold Italic"; if ( fontName.endsWith( " \u041A\u0443\u0440\u0441\u0438\u0432" ) ) fontName = AbstractWordUtils.substringBeforeLast( fontName, " \u041A\u0443\u0440\u0441\u0438\u0432" ) + " Italic"; original.fontName = fontName; } if ( AbstractWordUtils.isNotEmpty( original.fontName ) ) { if ( "Times Regular".equals( original.fontName ) || "Times-Regular".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = false; original.italic = false; } if ( "Times Bold".equals( original.fontName ) || "Times-Bold".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = true; original.italic = false; } if ( "Times Italic".equals( original.fontName ) || "Times-Italic".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = false; original.italic = true; } if ( "Times Bold Italic".equals( original.fontName ) || "Times-BoldItalic".equals( original.fontName ) ) { original.fontName = "Times"; original.bold = true; original.italic = true; } } return original; }
diff --git a/slickij-data-api/src/main/java/org/tcrun/slickij/api/data/HostStatus.java b/slickij-data-api/src/main/java/org/tcrun/slickij/api/data/HostStatus.java index 13d354c..8c13e72 100644 --- a/slickij-data-api/src/main/java/org/tcrun/slickij/api/data/HostStatus.java +++ b/slickij-data-api/src/main/java/org/tcrun/slickij/api/data/HostStatus.java @@ -1,62 +1,62 @@ package org.tcrun.slickij.api.data; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Id; import com.google.code.morphia.annotations.Property; import com.google.code.morphia.annotations.Reference; import java.io.Serializable; import java.util.Date; /** * * @author jcorbett */ @Entity("hoststatus") public class HostStatus implements Serializable { @Id private String hostname; @Property private Date lastCheckin; @Reference private Result currentWork; public Result getCurrentWork() { - if(currentWork.getRecorded() != null) + if(currentWork != null && currentWork.getRecorded() != null) { Date now = new Date(); int seconds = (int)((now.getTime() - currentWork.getRecorded().getTime())/1000); currentWork.setRunlength(seconds); } return currentWork; } public void setCurrentWork(Result currentWork) { this.currentWork = currentWork; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public Date getLastCheckin() { return lastCheckin; } public void setLastCheckin(Date lastCheckin) { this.lastCheckin = lastCheckin; } }
true
true
public Result getCurrentWork() { if(currentWork.getRecorded() != null) { Date now = new Date(); int seconds = (int)((now.getTime() - currentWork.getRecorded().getTime())/1000); currentWork.setRunlength(seconds); } return currentWork; }
public Result getCurrentWork() { if(currentWork != null && currentWork.getRecorded() != null) { Date now = new Date(); int seconds = (int)((now.getTime() - currentWork.getRecorded().getTime())/1000); currentWork.setRunlength(seconds); } return currentWork; }
diff --git a/src/main/java/tconstruct/client/ToolCoreRenderer.java b/src/main/java/tconstruct/client/ToolCoreRenderer.java index 7c22332e5..1683b7fb0 100644 --- a/src/main/java/tconstruct/client/ToolCoreRenderer.java +++ b/src/main/java/tconstruct/client/ToolCoreRenderer.java @@ -1,319 +1,318 @@ package tconstruct.client; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.*; import tconstruct.TConstruct; import tconstruct.library.tools.ToolCore; public class ToolCoreRenderer implements IItemRenderer { private final boolean isEntity; private final boolean noEntityTranslation; public ToolCoreRenderer() { this(false, false); } public ToolCoreRenderer(boolean isEntity) { this(isEntity, false); } public ToolCoreRenderer(boolean isEntity, boolean noEntityTranslation) { this.isEntity = isEntity; this.noEntityTranslation = noEntityTranslation; } @Override public boolean handleRenderType (ItemStack item, ItemRenderType type) { if (!item.hasTagCompound()) return false; switch (type) { case ENTITY: return true; case EQUIPPED: GL11.glTranslatef(0.03f, 0F, -0.09375F); case EQUIPPED_FIRST_PERSON: return !isEntity; case INVENTORY: return true; default: TConstruct.logger.warn("[TCon] Unhandled render case!"); case FIRST_PERSON_MAP: return false; } } @Override public boolean shouldUseRenderHelper (ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return handleRenderType(item, type) & helper.ordinal() < ItemRendererHelper.EQUIPPED_BLOCK.ordinal(); } private static final int toolIcons = 10; @Override public void renderItem (ItemRenderType type, ItemStack item, Object... data) { ToolCore tool = (ToolCore) item.getItem(); boolean isInventory = type == ItemRenderType.INVENTORY; Entity ent = null; if (data.length > 1) ent = (Entity) data[1]; int iconParts = toolIcons;//tool.getRenderPasses(item.getItemDamage()); // TODO: have the tools define how many render passes they have // (requires more logic rewrite than it sounds like) IIcon[] tempParts = new IIcon[iconParts]; label: { if (!isInventory && ent instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) ent; ItemStack itemInUse = player.getItemInUse(); if (itemInUse != null) { int useCount = player.getItemInUseCount(); for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i, player, itemInUse, useCount); break label; } } for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i); } int count = 0; IIcon[] parts = new IIcon[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon part = tempParts[i]; if (part == null || part == ToolCore.blankSprite || part == ToolCore.emptyIcon) ++count; else parts[i - count] = part; } iconParts -= count; if (iconParts <= 0) { iconParts = 1; // TODO: assign default sprite // parts = new Icon[]{ defaultSprite }; } Tessellator tess = Tessellator.instance; float[] xMax = new float[iconParts]; float[] yMin = new float[iconParts]; float[] xMin = new float[iconParts]; float[] yMax = new float[iconParts]; float depth = 1f / 16f; float[] width = new float[iconParts]; float[] height = new float[iconParts]; float[] xDiff = new float[iconParts]; float[] yDiff = new float[iconParts]; float[] xSub = new float[iconParts]; float[] ySub = new float[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon icon = parts[i]; xMin[i] = icon.getMinU(); xMax[i] = icon.getMaxU(); yMin[i] = icon.getMinV(); yMax[i] = icon.getMaxV(); width[i] = icon.getIconWidth(); height[i] = icon.getIconHeight(); xDiff[i] = xMin[i] - xMax[i]; yDiff[i] = yMin[i] - yMax[i]; xSub[i] = 0.5f * (xMax[i] - xMin[i]) / width[i]; ySub[i] = 0.5f * (yMax[i] - yMin[i]) / height[i]; } GL11.glPushMatrix(); // color int[] color = new int[iconParts]; for(int i = 0; i < iconParts; i++) color[i] = item.getItem().getColorFromItemStack(item, i); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (type == ItemRenderType.INVENTORY) { //TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); //texturemanager.getResourceLocation(item.getItemSpriteNumber()); //TextureUtil.func_152777_a(false, false, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glAlphaFunc(GL11.GL_GREATER, 0.5F); GL11.glDisable(GL11.GL_BLEND); tess.startDrawingQuads(); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 16, 0, xMin[i], yMax[i]); tess.addVertexWithUV(16, 16, 0, xMax[i], yMax[i]); tess.addVertexWithUV(16, 0, 0, xMax[i], yMin[i]); tess.addVertexWithUV(0, 0, 0, xMin[i], yMin[i]); } tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND); //GL11.glDisable(GL12.GL_RESCALE_NORMAL); //texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); //TextureUtil.func_147945_b(); } else { switch (type) { case EQUIPPED_FIRST_PERSON: break; case EQUIPPED: GL11.glTranslatef(0, -4 / 16f, 0); break; case ENTITY: if (!noEntityTranslation) GL11.glTranslatef(-0.5f, 0f, depth); // correction of the rotation point when items lie on the ground break; default: } // one side tess.startDrawingQuads(); tess.setNormal(0, 0, 1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 0, 0, xMax[i], yMax[i]); tess.addVertexWithUV(1, 0, 0, xMin[i], yMax[i]); tess.addVertexWithUV(1, 1, 0, xMin[i], yMin[i]); tess.addVertexWithUV(0, 1, 0, xMax[i], yMin[i]); } tess.draw(); // other side tess.startDrawingQuads(); tess.setNormal(0, 0, -1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 1, -depth, xMax[i], yMin[i]); tess.addVertexWithUV(1, 1, -depth, xMin[i], yMin[i]); tess.addVertexWithUV(1, 0, -depth, xMin[i], yMax[i]); tess.addVertexWithUV(0, 0, -depth, xMax[i], yMax[i]); } tess.draw(); // make it have "depth" tess.startDrawingQuads(); tess.setNormal(-1, 0, 0); float pos; float iconPos; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; tess.addVertexWithUV(pos, 0, -depth, iconPos, yMax[i]); tess.addVertexWithUV(pos, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(pos, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(pos, 1, -depth, iconPos, yMin[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(1, 0, 0); float posEnd; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; float d2 = 1f / w; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(posEnd, 1, -depth, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(posEnd, 0, -depth, iconPos, yMax[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, 1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; float d2 = 1f / h; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(0, posEnd, 0, xMax[i], iconPos); tess.addVertexWithUV(1, posEnd, 0, xMin[i], iconPos); tess.addVertexWithUV(1, posEnd, -depth, xMin[i], iconPos); tess.addVertexWithUV(0, posEnd, -depth, xMax[i], iconPos); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, -1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; tess.addVertexWithUV(1, pos, 0, xMin[i], iconPos); tess.addVertexWithUV(0, pos, 0, xMax[i], iconPos); tess.addVertexWithUV(0, pos, -depth, xMax[i], iconPos); tess.addVertexWithUV(1, pos, -depth, xMin[i], iconPos); } } tess.draw(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); } }
true
true
public void renderItem (ItemRenderType type, ItemStack item, Object... data) { ToolCore tool = (ToolCore) item.getItem(); boolean isInventory = type == ItemRenderType.INVENTORY; Entity ent = null; if (data.length > 1) ent = (Entity) data[1]; int iconParts = toolIcons;//tool.getRenderPasses(item.getItemDamage()); // TODO: have the tools define how many render passes they have // (requires more logic rewrite than it sounds like) IIcon[] tempParts = new IIcon[iconParts]; label: { if (!isInventory && ent instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) ent; ItemStack itemInUse = player.getItemInUse(); if (itemInUse != null) { int useCount = player.getItemInUseCount(); for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i, player, itemInUse, useCount); break label; } } for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i); } int count = 0; IIcon[] parts = new IIcon[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon part = tempParts[i]; if (part == null || part == ToolCore.blankSprite || part == ToolCore.emptyIcon) ++count; else parts[i - count] = part; } iconParts -= count; if (iconParts <= 0) { iconParts = 1; // TODO: assign default sprite // parts = new Icon[]{ defaultSprite }; } Tessellator tess = Tessellator.instance; float[] xMax = new float[iconParts]; float[] yMin = new float[iconParts]; float[] xMin = new float[iconParts]; float[] yMax = new float[iconParts]; float depth = 1f / 16f; float[] width = new float[iconParts]; float[] height = new float[iconParts]; float[] xDiff = new float[iconParts]; float[] yDiff = new float[iconParts]; float[] xSub = new float[iconParts]; float[] ySub = new float[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon icon = parts[i]; xMin[i] = icon.getMinU(); xMax[i] = icon.getMaxU(); yMin[i] = icon.getMinV(); yMax[i] = icon.getMaxV(); width[i] = icon.getIconWidth(); height[i] = icon.getIconHeight(); xDiff[i] = xMin[i] - xMax[i]; yDiff[i] = yMin[i] - yMax[i]; xSub[i] = 0.5f * (xMax[i] - xMin[i]) / width[i]; ySub[i] = 0.5f * (yMax[i] - yMin[i]) / height[i]; } GL11.glPushMatrix(); // color int[] color = new int[iconParts]; for(int i = 0; i < iconParts; i++) color[i] = item.getItem().getColorFromItemStack(item, i); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (type == ItemRenderType.INVENTORY) { //TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); //texturemanager.getResourceLocation(item.getItemSpriteNumber()); //TextureUtil.func_152777_a(false, false, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.5F); GL11.glDisable(GL11.GL_BLEND); tess.startDrawingQuads(); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 16, 0, xMin[i], yMax[i]); tess.addVertexWithUV(16, 16, 0, xMax[i], yMax[i]); tess.addVertexWithUV(16, 0, 0, xMax[i], yMin[i]); tess.addVertexWithUV(0, 0, 0, xMin[i], yMin[i]); } tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND); //GL11.glDisable(GL12.GL_RESCALE_NORMAL); //texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); //TextureUtil.func_147945_b(); } else { switch (type) { case EQUIPPED_FIRST_PERSON: break; case EQUIPPED: GL11.glTranslatef(0, -4 / 16f, 0); break; case ENTITY: if (!noEntityTranslation) GL11.glTranslatef(-0.5f, 0f, depth); // correction of the rotation point when items lie on the ground break; default: } // one side tess.startDrawingQuads(); tess.setNormal(0, 0, 1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 0, 0, xMax[i], yMax[i]); tess.addVertexWithUV(1, 0, 0, xMin[i], yMax[i]); tess.addVertexWithUV(1, 1, 0, xMin[i], yMin[i]); tess.addVertexWithUV(0, 1, 0, xMax[i], yMin[i]); } tess.draw(); // other side tess.startDrawingQuads(); tess.setNormal(0, 0, -1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 1, -depth, xMax[i], yMin[i]); tess.addVertexWithUV(1, 1, -depth, xMin[i], yMin[i]); tess.addVertexWithUV(1, 0, -depth, xMin[i], yMax[i]); tess.addVertexWithUV(0, 0, -depth, xMax[i], yMax[i]); } tess.draw(); // make it have "depth" tess.startDrawingQuads(); tess.setNormal(-1, 0, 0); float pos; float iconPos; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; tess.addVertexWithUV(pos, 0, -depth, iconPos, yMax[i]); tess.addVertexWithUV(pos, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(pos, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(pos, 1, -depth, iconPos, yMin[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(1, 0, 0); float posEnd; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; float d2 = 1f / w; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(posEnd, 1, -depth, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(posEnd, 0, -depth, iconPos, yMax[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, 1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; float d2 = 1f / h; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(0, posEnd, 0, xMax[i], iconPos); tess.addVertexWithUV(1, posEnd, 0, xMin[i], iconPos); tess.addVertexWithUV(1, posEnd, -depth, xMin[i], iconPos); tess.addVertexWithUV(0, posEnd, -depth, xMax[i], iconPos); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, -1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; tess.addVertexWithUV(1, pos, 0, xMin[i], iconPos); tess.addVertexWithUV(0, pos, 0, xMax[i], iconPos); tess.addVertexWithUV(0, pos, -depth, xMax[i], iconPos); tess.addVertexWithUV(1, pos, -depth, xMin[i], iconPos); } } tess.draw(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); }
public void renderItem (ItemRenderType type, ItemStack item, Object... data) { ToolCore tool = (ToolCore) item.getItem(); boolean isInventory = type == ItemRenderType.INVENTORY; Entity ent = null; if (data.length > 1) ent = (Entity) data[1]; int iconParts = toolIcons;//tool.getRenderPasses(item.getItemDamage()); // TODO: have the tools define how many render passes they have // (requires more logic rewrite than it sounds like) IIcon[] tempParts = new IIcon[iconParts]; label: { if (!isInventory && ent instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) ent; ItemStack itemInUse = player.getItemInUse(); if (itemInUse != null) { int useCount = player.getItemInUseCount(); for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i, player, itemInUse, useCount); break label; } } for (int i = iconParts; i-- > 0;) tempParts[i] = tool.getIcon(item, i); } int count = 0; IIcon[] parts = new IIcon[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon part = tempParts[i]; if (part == null || part == ToolCore.blankSprite || part == ToolCore.emptyIcon) ++count; else parts[i - count] = part; } iconParts -= count; if (iconParts <= 0) { iconParts = 1; // TODO: assign default sprite // parts = new Icon[]{ defaultSprite }; } Tessellator tess = Tessellator.instance; float[] xMax = new float[iconParts]; float[] yMin = new float[iconParts]; float[] xMin = new float[iconParts]; float[] yMax = new float[iconParts]; float depth = 1f / 16f; float[] width = new float[iconParts]; float[] height = new float[iconParts]; float[] xDiff = new float[iconParts]; float[] yDiff = new float[iconParts]; float[] xSub = new float[iconParts]; float[] ySub = new float[iconParts]; for (int i = 0; i < iconParts; ++i) { IIcon icon = parts[i]; xMin[i] = icon.getMinU(); xMax[i] = icon.getMaxU(); yMin[i] = icon.getMinV(); yMax[i] = icon.getMaxV(); width[i] = icon.getIconWidth(); height[i] = icon.getIconHeight(); xDiff[i] = xMin[i] - xMax[i]; yDiff[i] = yMin[i] - yMax[i]; xSub[i] = 0.5f * (xMax[i] - xMin[i]) / width[i]; ySub[i] = 0.5f * (yMax[i] - yMin[i]) / height[i]; } GL11.glPushMatrix(); // color int[] color = new int[iconParts]; for(int i = 0; i < iconParts; i++) color[i] = item.getItem().getColorFromItemStack(item, i); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (type == ItemRenderType.INVENTORY) { //TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); //texturemanager.getResourceLocation(item.getItemSpriteNumber()); //TextureUtil.func_152777_a(false, false, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_BLEND); tess.startDrawingQuads(); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 16, 0, xMin[i], yMax[i]); tess.addVertexWithUV(16, 16, 0, xMax[i], yMax[i]); tess.addVertexWithUV(16, 0, 0, xMax[i], yMin[i]); tess.addVertexWithUV(0, 0, 0, xMin[i], yMin[i]); } tess.draw(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND); //GL11.glDisable(GL12.GL_RESCALE_NORMAL); //texturemanager.bindTexture(texturemanager.getResourceLocation(item.getItemSpriteNumber())); //TextureUtil.func_147945_b(); } else { switch (type) { case EQUIPPED_FIRST_PERSON: break; case EQUIPPED: GL11.glTranslatef(0, -4 / 16f, 0); break; case ENTITY: if (!noEntityTranslation) GL11.glTranslatef(-0.5f, 0f, depth); // correction of the rotation point when items lie on the ground break; default: } // one side tess.startDrawingQuads(); tess.setNormal(0, 0, 1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 0, 0, xMax[i], yMax[i]); tess.addVertexWithUV(1, 0, 0, xMin[i], yMax[i]); tess.addVertexWithUV(1, 1, 0, xMin[i], yMin[i]); tess.addVertexWithUV(0, 1, 0, xMax[i], yMin[i]); } tess.draw(); // other side tess.startDrawingQuads(); tess.setNormal(0, 0, -1); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); tess.addVertexWithUV(0, 1, -depth, xMax[i], yMin[i]); tess.addVertexWithUV(1, 1, -depth, xMin[i], yMin[i]); tess.addVertexWithUV(1, 0, -depth, xMin[i], yMax[i]); tess.addVertexWithUV(0, 0, -depth, xMax[i], yMax[i]); } tess.draw(); // make it have "depth" tess.startDrawingQuads(); tess.setNormal(-1, 0, 0); float pos; float iconPos; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; tess.addVertexWithUV(pos, 0, -depth, iconPos, yMax[i]); tess.addVertexWithUV(pos, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(pos, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(pos, 1, -depth, iconPos, yMin[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(1, 0, 0); float posEnd; for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float w = width[i], m = xMax[i], d = xDiff[i], s = xSub[i]; float d2 = 1f / w; for (int k = 0, e = (int) w; k < e; ++k) { pos = k / w; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(posEnd, 1, -depth, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 1, 0, iconPos, yMin[i]); tess.addVertexWithUV(posEnd, 0, 0, iconPos, yMax[i]); tess.addVertexWithUV(posEnd, 0, -depth, iconPos, yMax[i]); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, 1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; float d2 = 1f / h; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; posEnd = pos + d2; tess.addVertexWithUV(0, posEnd, 0, xMax[i], iconPos); tess.addVertexWithUV(1, posEnd, 0, xMin[i], iconPos); tess.addVertexWithUV(1, posEnd, -depth, xMin[i], iconPos); tess.addVertexWithUV(0, posEnd, -depth, xMax[i], iconPos); } } tess.draw(); tess.startDrawingQuads(); tess.setNormal(0, -1, 0); for (int i = 0; i < iconParts; ++i) { tess.setColorOpaque_I(color[i]); float h = height[i], m = yMax[i], d = yDiff[i], s = ySub[i]; for (int k = 0, e = (int) h; k < e; ++k) { pos = k / h; iconPos = m + d * pos - s; tess.addVertexWithUV(1, pos, 0, xMin[i], iconPos); tess.addVertexWithUV(0, pos, 0, xMax[i], iconPos); tess.addVertexWithUV(0, pos, -depth, xMax[i], iconPos); tess.addVertexWithUV(1, pos, -depth, xMin[i], iconPos); } } tess.draw(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } GL11.glPopMatrix(); }
diff --git a/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java b/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java index be627e0a7..c0f007602 100644 --- a/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java +++ b/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java @@ -1,304 +1,304 @@ /******************************************************************************* * Copyright (c) 2010, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation *******************************************************************************/ package org.eclipse.ptp.internal.remote.rse.core.miners; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.eclipse.cdt.utils.pty.PTY; import org.eclipse.cdt.utils.spawner.ProcessFactory; import org.eclipse.dstore.core.miners.Miner; import org.eclipse.dstore.core.model.DE; import org.eclipse.dstore.core.model.DataElement; import org.eclipse.dstore.core.model.DataStoreResources; import org.eclipse.dstore.core.model.DataStoreSchema; import org.eclipse.rse.dstore.universal.miners.UniversalServerUtilities; import org.eclipse.rse.internal.dstore.universal.miners.command.patterns.Patterns; /** * @author crecoskie * */ @SuppressWarnings("restriction") public class SpawnerMiner extends Miner { public static final String SPAWN_ERROR = "spawnError"; //$NON-NLS-1$ public class CommandMinerDescriptors { public DataElement _stdout; public DataElement _stderr; public DataElement _prompt; public DataElement _grep; public DataElement _pathenvvar; public DataElement _envvar; public DataElement _libenvvar; public DataElement _error; public DataElement _warning; public DataElement _informational; public DataElement _process; public DataElement getDescriptorFor(String type) { DataElement descriptor = null; if (type.equals("stdout")) //$NON-NLS-1$ { descriptor = _stdout; } else if (type.equals("pathenvvar")) //$NON-NLS-1$ { descriptor = _pathenvvar; } else if (type.equals("envvar")) //$NON-NLS-1$ { descriptor = _envvar; } else if (type.equals("libenvvar")) //$NON-NLS-1$ { descriptor = _libenvvar; } else if (type.equals("error")) //$NON-NLS-1$ { descriptor = _error; } else if (type.equals("warning")) //$NON-NLS-1$ { descriptor = _warning; } else if (type.equals("informational")) //$NON-NLS-1$ { descriptor = _informational; } else if (type.equals("process")) //$NON-NLS-1$ { descriptor = _process; } else if (type.equals("grep")) //$NON-NLS-1$ { descriptor = _grep; } else if (type.equals("stderr")) //$NON-NLS-1$ { descriptor = _stderr; } return descriptor; } } public static final String C_SPAWN_REDIRECTED = "C_SPAWN_REDIRECTED"; //$NON-NLS-1$ public static final String C_SPAWN_NOT_REDIRECTED = "C_SPAWN_NOT_REDIRECTED"; //$NON-NLS-1$ public static final String C_SPAWN_TTY = "C_SPAWN_TTY"; //$NON-NLS-1$ public static final String T_SPAWNER_STRING_DESCRIPTOR = "Type.Spawner.String"; //$NON-NLS-1$ public static final String LOG_TAG = "SpawnerMiner"; //$NON-NLS-1$ private CommandMinerDescriptors fDescriptors = new CommandMinerDescriptors(); boolean fSupportsCharConversion; private DataElement _status; private Map<DataElement, Process> fProcessMap = new HashMap<DataElement, Process>(); public boolean _supportsCharConversion = true; private Patterns _patterns; /* (non-Javadoc) * @see org.eclipse.dstore.core.miners.Miner#getVersion() */ @Override public String getVersion() { return "0.0.2"; //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.dstore.core.miners.Miner#handleCommand(org.eclipse.dstore.core.model.DataElement) */ @Override public DataElement handleCommand(DataElement theCommand) throws Exception { try { return doHandleCommand(theCommand); } catch(RuntimeException e) { UniversalServerUtilities.logError(LOG_TAG, e.toString(), e, _dataStore); _dataStore.refresh(theCommand); _dataStore.disconnectObject(theCommand); throw e; } } private DataElement doHandleCommand(DataElement theCommand) { String name = getCommandName(theCommand); DataElement status = getCommandStatus(theCommand); _status = status; DataElement subject = getCommandArgument(theCommand, 0); if (name.equals(C_SPAWN_REDIRECTED)) { String cmd = getString(theCommand, 1); String directory = getString(theCommand, 2); File dir = new File(directory); int envSize = getInt(theCommand, 3); String[] envp = new String[envSize]; for (int i = 0; i < envSize; i++) { envp[i] = getString(theCommand, i+4); } handleSpawnRedirected(subject, cmd, dir, envp, status); - return statusDone(status); + return status; } else if(name.equals(DataStoreSchema.C_CANCEL)) { DataElement cancelStatus = getCommandStatus(subject); // get the name of the command that is to be canceled String commandName = subject.getName().trim(); if(commandName.equals(C_SPAWN_REDIRECTED) || commandName.equals(C_SPAWN_NOT_REDIRECTED) || commandName.equals(C_SPAWN_TTY)) { handleSpawnCancel(cancelStatus); } // add more cancelable commands here } else if (name.equals("C_CHAR_CONVERSION")) //$NON-NLS-1$ { fSupportsCharConversion = true; return statusDone(status); } return null; } private void handleSpawnCancel(DataElement cancelStatus) { Process processToCancel = fProcessMap.get(cancelStatus); if(processToCancel != null) { processToCancel.destroy(); synchronized(fProcessMap) { fProcessMap.put(cancelStatus, null); } } statusDone(cancelStatus); } /** * @param subject * @param cmd * @param dir * @param envp * @throws IOException */ private void handleSpawnRedirected(DataElement subject, String cmd, File dir, String[] envp, DataElement status) { try { final Process process = ProcessFactory.getFactory().exec(cmd.split(" "), envp, dir, new PTY()); //$NON-NLS-1$ synchronized(this) { fProcessMap.put(status, process); } CommandMinerThread newCommand = new CommandMinerThread(subject, process, cmd, dir.getAbsolutePath(), status, getPatterns(), fDescriptors); newCommand.start(); } catch (IOException e) { // report the error to the client so that it should show up in their console _dataStore.createObject(status, SPAWN_ERROR, cmd, ""); //$NON-NLS-1$ refreshStatus(); // tell the client that the operation is done (even though unsuccessful) statusDone(status); // log to the server log UniversalServerUtilities.logError(LOG_TAG, e.toString(), e, _dataStore); } // statusDone(status); } /** * Complete status. */ public static DataElement statusDone(DataElement status) { status.setAttribute(DE.A_NAME, DataStoreResources.model_done); status.getDataStore().refresh(status); status.getDataStore().disconnectObject(status.getParent()); return status; } private String getString(DataElement command, int index) { DataElement element = getCommandArgument(command, index); return element.getName(); } private int getInt(DataElement command, int index) { DataElement element = getCommandArgument(command, index); Integer i = new Integer(element.getName()); return i.intValue(); } /* (non-Javadoc) * @see org.eclipse.dstore.core.model.ISchemaExtender#extendSchema(org.eclipse.dstore.core.model.DataElement) */ public void extendSchema(DataElement schemaRoot) { // make sure we can load the spawner... if we can't, then bail out try { System.loadLibrary("spawner"); //$NON-NLS-1$ } catch(UnsatisfiedLinkError e) { // don't log this error, as it may just be that we are running a // generic server that doesn't have a spawner library return; } DataElement cancellable = _dataStore.findObjectDescriptor(DataStoreResources.model_Cancellable); DataElement e0_cmd = createCommandDescriptor(schemaRoot, "Spawn process without redirection", C_SPAWN_REDIRECTED, false); //$NON-NLS-1$ _dataStore.createReference(cancellable, e0_cmd, DataStoreResources.model_abstracts, DataStoreResources.model_abstracted_by); fDescriptors = new CommandMinerDescriptors(); fDescriptors._stdout = _dataStore.createObjectDescriptor(schemaRoot, "stdout"); //$NON-NLS-1$ fDescriptors._stderr = _dataStore.createObjectDescriptor(schemaRoot, "stderr"); //$NON-NLS-1$ fDescriptors._prompt = _dataStore.createObjectDescriptor(schemaRoot, "prompt"); //$NON-NLS-1$ fDescriptors._grep = _dataStore.createObjectDescriptor(schemaRoot, "grep"); //$NON-NLS-1$ fDescriptors._pathenvvar = _dataStore.createObjectDescriptor(schemaRoot, "pathenvvar"); //$NON-NLS-1$ fDescriptors._envvar = _dataStore.createObjectDescriptor(schemaRoot, "envvar"); //$NON-NLS-1$ fDescriptors._libenvvar = _dataStore.createObjectDescriptor(schemaRoot, "libenvvar"); //$NON-NLS-1$ fDescriptors._error = _dataStore.createObjectDescriptor(schemaRoot, "error"); //$NON-NLS-1$ fDescriptors._warning = _dataStore.createObjectDescriptor(schemaRoot, "warning"); //$NON-NLS-1$ fDescriptors._informational = _dataStore.createObjectDescriptor(schemaRoot, "informational"); //$NON-NLS-1$ fDescriptors._process =_dataStore.createObjectDescriptor(schemaRoot, "process"); //$NON-NLS-1$ _dataStore.refresh(schemaRoot); } public void refreshStatus() { _dataStore.refresh(_status); } private Patterns getPatterns() { if (_patterns == null) { _patterns = new Patterns(_dataStore); } return _patterns; } }
true
true
private DataElement doHandleCommand(DataElement theCommand) { String name = getCommandName(theCommand); DataElement status = getCommandStatus(theCommand); _status = status; DataElement subject = getCommandArgument(theCommand, 0); if (name.equals(C_SPAWN_REDIRECTED)) { String cmd = getString(theCommand, 1); String directory = getString(theCommand, 2); File dir = new File(directory); int envSize = getInt(theCommand, 3); String[] envp = new String[envSize]; for (int i = 0; i < envSize; i++) { envp[i] = getString(theCommand, i+4); } handleSpawnRedirected(subject, cmd, dir, envp, status); return statusDone(status); } else if(name.equals(DataStoreSchema.C_CANCEL)) { DataElement cancelStatus = getCommandStatus(subject); // get the name of the command that is to be canceled String commandName = subject.getName().trim(); if(commandName.equals(C_SPAWN_REDIRECTED) || commandName.equals(C_SPAWN_NOT_REDIRECTED) || commandName.equals(C_SPAWN_TTY)) { handleSpawnCancel(cancelStatus); } // add more cancelable commands here } else if (name.equals("C_CHAR_CONVERSION")) //$NON-NLS-1$ { fSupportsCharConversion = true; return statusDone(status); } return null; }
private DataElement doHandleCommand(DataElement theCommand) { String name = getCommandName(theCommand); DataElement status = getCommandStatus(theCommand); _status = status; DataElement subject = getCommandArgument(theCommand, 0); if (name.equals(C_SPAWN_REDIRECTED)) { String cmd = getString(theCommand, 1); String directory = getString(theCommand, 2); File dir = new File(directory); int envSize = getInt(theCommand, 3); String[] envp = new String[envSize]; for (int i = 0; i < envSize; i++) { envp[i] = getString(theCommand, i+4); } handleSpawnRedirected(subject, cmd, dir, envp, status); return status; } else if(name.equals(DataStoreSchema.C_CANCEL)) { DataElement cancelStatus = getCommandStatus(subject); // get the name of the command that is to be canceled String commandName = subject.getName().trim(); if(commandName.equals(C_SPAWN_REDIRECTED) || commandName.equals(C_SPAWN_NOT_REDIRECTED) || commandName.equals(C_SPAWN_TTY)) { handleSpawnCancel(cancelStatus); } // add more cancelable commands here } else if (name.equals("C_CHAR_CONVERSION")) //$NON-NLS-1$ { fSupportsCharConversion = true; return statusDone(status); } return null; }
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java index 4bd0402b6..b78577373 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/DefaultQueryProvider.java @@ -1,207 +1,206 @@ /******************************************************************************* * Copyright (c) 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.p2.ui; import java.net.URI; import org.eclipse.equinox.internal.p2.ui.model.*; import org.eclipse.equinox.internal.p2.ui.query.*; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.director.IUProfilePropertyQuery; import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.query.IUPropertyQuery; import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.internal.provisional.p2.query.*; import org.eclipse.equinox.internal.provisional.p2.ui.*; import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; import org.eclipse.equinox.internal.provisional.p2.ui.model.Updates; import org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil; import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.statushandlers.StatusManager; /** * Provides a default set of queries to drive the provisioning UI. * * @since 3.5 */ public class DefaultQueryProvider extends QueryProvider { private Policy policy; private Query allQuery = new Query() { public boolean isMatch(Object candidate) { return true; } }; public DefaultQueryProvider(Policy policy) { this.policy = policy; } public ElementQueryDescriptor getQueryDescriptor(final QueriedElement element) { // Initialize queryable, queryContext, and queryType from the element. // In some cases we override this. IQueryable queryable = element.getQueryable(); int queryType = element.getQueryType(); IUViewQueryContext context = element.getQueryContext(); if (context == null) { context = policy.getQueryContext(); } switch (queryType) { case QueryProvider.ARTIFACT_REPOS : queryable = new QueryableArtifactRepositoryManager(context.getArtifactRepositoryFlags()); return new ElementQueryDescriptor(queryable, null, new Collector() { public boolean accept(Object object) { if (object instanceof URI) return super.accept(new ArtifactRepositoryElement(element, (URI) object)); return true; } }); case QueryProvider.AVAILABLE_IUS : // Things get more complicated if the user wants to filter out installed items. // This involves setting up a secondary query for installed content that the various // collectors will use to reject content. We can't use a compound query because the // queryables are different (profile for installed content, repo for available content) AvailableIUCollector availableIUCollector; - ElementQueryDescriptor installedQueryDescriptor = null; boolean showLatest = context.getShowLatestVersionsOnly(); boolean hideInstalled = context.getHideAlreadyInstalled(); IProfile targetProfile = null; String profileId = context.getInstalledProfileId(); if (profileId != null) { try { targetProfile = ProvisioningUtil.getProfile(profileId); } catch (ProvisionException e) { // just bail out, we won't try to query the installed } } // Showing children of a rollback element if (element instanceof RollbackRepositoryElement) { Query profileIdQuery = new InstallableUnitQuery(((RollbackRepositoryElement) element).getProfileId()); Query rollbackIUQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_PROFILE, Boolean.toString(true)); availableIUCollector = new RollbackIUCollector(queryable, element.getParent(element)); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {profileIdQuery, rollbackIUQuery}, true), availableIUCollector); } Query topLevelQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); Query categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); // Showing child IU's of a group of repositories, or of a single repository if (element instanceof MetadataRepositories || element instanceof MetadataRepositoryElement) { if (context.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_FLAT || !context.getUseCategories()) { AvailableIUCollector collector; if (showLatest) collector = new LatestIUVersionElementCollector(queryable, element, false, context.getShowAvailableChildren()); else collector = new AvailableIUCollector(queryable, element, false, context.getShowAvailableChildren()); if (targetProfile != null) collector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, topLevelQuery, collector); } // Installed content not a concern for collecting categories return new ElementQueryDescriptor(queryable, categoryQuery, new CategoryElementCollector(queryable, element, true)); } // Showing children of categories that we've already collected // Must do this one before CategoryElement since it's a subclass if (element instanceof UncategorizedCategoryElement) { // Will have to look at all categories and groups and from there, figure out what's left Query firstPassQuery = new CompoundQuery(new Query[] {topLevelQuery, categoryQuery}, false); availableIUCollector = showLatest ? new LatestIUVersionElementCollector(queryable, element, false, context.getShowAvailableChildren()) : new AvailableIUCollector(queryable, element, false, context.getShowAvailableChildren()); if (targetProfile != null) availableIUCollector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, firstPassQuery, new UncategorizedElementCollector(queryable, element, availableIUCollector)); } // If it's a category or some other IUElement to drill down in, we get the requirements and show all requirements // that are also visible in the available list. if (element instanceof CategoryElement || (element instanceof IIUElement && ((IIUElement) element).shouldShowChildren())) { // children of a category should drill down according to the context. If we aren't in a category, we are already drilling down and // continue to do so. boolean drillDown = element instanceof CategoryElement ? context.getShowAvailableChildren() : true; Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); if (showLatest) availableIUCollector = new LatestIUVersionElementCollector(queryable, element, true, drillDown); else availableIUCollector = new AvailableIUCollector(queryable, element, true, drillDown); if (targetProfile != null) availableIUCollector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {new CompoundQuery(new Query[] {topLevelQuery, categoryQuery}, false), meetsAnyRequirementQuery}, true), availableIUCollector); } return null; case QueryProvider.AVAILABLE_UPDATES : IProfile profile; IInstallableUnit[] toUpdate = null; if (element instanceof Updates) { try { profile = ProvisioningUtil.getProfile(((Updates) element).getProfileId()); } catch (ProvisionException e) { ProvUI.handleException(e, NLS.bind(ProvUIMessages.DefaultQueryProvider_ErrorRetrievingProfile, ((Updates) element).getProfileId()), StatusManager.LOG); return null; } toUpdate = ((Updates) element).getIUs(); } else { profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); } if (profile == null) return null; Collector collector; if (toUpdate == null) { collector = profile.query(new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new Collector(), null); toUpdate = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); } QueryableUpdates updateQueryable = new QueryableUpdates(toUpdate); if (context.getShowLatestVersionsOnly()) collector = new LatestIUVersionElementCollector(updateQueryable, element, true, false); else collector = new Collector(); return new ElementQueryDescriptor(updateQueryable, allQuery, collector); case QueryProvider.INSTALLED_IUS : // Querying of IU's. We are drilling down into the requirements. if (element instanceof IIUElement && context.getShowInstallChildren()) { Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); Query visibleAsAvailableQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {visibleAsAvailableQuery, meetsAnyRequirementQuery}, true), new InstalledIUCollector(queryable, element)); } profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); if (profile == null) return null; // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=229352 // Rollback profiles are specialized/temporary instances so we must use a query that uses the profile instance, not the id. if (element instanceof RollbackProfileElement) return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new InstalledIUCollector(profile, element)); // Just a normal query of the installed IU's, query the profile and look for the visible ones return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new InstalledIUCollector(profile, element)); case QueryProvider.METADATA_REPOS : if (element instanceof MetadataRepositories) { if (queryable == null) { queryable = new QueryableMetadataRepositoryManager(policy, ((MetadataRepositories) element).getIncludeDisabledRepositories()); element.setQueryable(queryable); } return new ElementQueryDescriptor(element.getQueryable(), null, new MetadataRepositoryElementCollector(element.getQueryable(), element)); } return null; case QueryProvider.PROFILES : queryable = new QueryableProfileRegistry(); return new ElementQueryDescriptor(queryable, new Query() { public boolean isMatch(Object candidate) { return ProvUI.getAdapter(candidate, IProfile.class) != null; } }, new ProfileElementCollector(null, element)); default : return null; } } }
true
true
public ElementQueryDescriptor getQueryDescriptor(final QueriedElement element) { // Initialize queryable, queryContext, and queryType from the element. // In some cases we override this. IQueryable queryable = element.getQueryable(); int queryType = element.getQueryType(); IUViewQueryContext context = element.getQueryContext(); if (context == null) { context = policy.getQueryContext(); } switch (queryType) { case QueryProvider.ARTIFACT_REPOS : queryable = new QueryableArtifactRepositoryManager(context.getArtifactRepositoryFlags()); return new ElementQueryDescriptor(queryable, null, new Collector() { public boolean accept(Object object) { if (object instanceof URI) return super.accept(new ArtifactRepositoryElement(element, (URI) object)); return true; } }); case QueryProvider.AVAILABLE_IUS : // Things get more complicated if the user wants to filter out installed items. // This involves setting up a secondary query for installed content that the various // collectors will use to reject content. We can't use a compound query because the // queryables are different (profile for installed content, repo for available content) AvailableIUCollector availableIUCollector; ElementQueryDescriptor installedQueryDescriptor = null; boolean showLatest = context.getShowLatestVersionsOnly(); boolean hideInstalled = context.getHideAlreadyInstalled(); IProfile targetProfile = null; String profileId = context.getInstalledProfileId(); if (profileId != null) { try { targetProfile = ProvisioningUtil.getProfile(profileId); } catch (ProvisionException e) { // just bail out, we won't try to query the installed } } // Showing children of a rollback element if (element instanceof RollbackRepositoryElement) { Query profileIdQuery = new InstallableUnitQuery(((RollbackRepositoryElement) element).getProfileId()); Query rollbackIUQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_PROFILE, Boolean.toString(true)); availableIUCollector = new RollbackIUCollector(queryable, element.getParent(element)); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {profileIdQuery, rollbackIUQuery}, true), availableIUCollector); } Query topLevelQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); Query categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); // Showing child IU's of a group of repositories, or of a single repository if (element instanceof MetadataRepositories || element instanceof MetadataRepositoryElement) { if (context.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_FLAT || !context.getUseCategories()) { AvailableIUCollector collector; if (showLatest) collector = new LatestIUVersionElementCollector(queryable, element, false, context.getShowAvailableChildren()); else collector = new AvailableIUCollector(queryable, element, false, context.getShowAvailableChildren()); if (targetProfile != null) collector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, topLevelQuery, collector); } // Installed content not a concern for collecting categories return new ElementQueryDescriptor(queryable, categoryQuery, new CategoryElementCollector(queryable, element, true)); } // Showing children of categories that we've already collected // Must do this one before CategoryElement since it's a subclass if (element instanceof UncategorizedCategoryElement) { // Will have to look at all categories and groups and from there, figure out what's left Query firstPassQuery = new CompoundQuery(new Query[] {topLevelQuery, categoryQuery}, false); availableIUCollector = showLatest ? new LatestIUVersionElementCollector(queryable, element, false, context.getShowAvailableChildren()) : new AvailableIUCollector(queryable, element, false, context.getShowAvailableChildren()); if (targetProfile != null) availableIUCollector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, firstPassQuery, new UncategorizedElementCollector(queryable, element, availableIUCollector)); } // If it's a category or some other IUElement to drill down in, we get the requirements and show all requirements // that are also visible in the available list. if (element instanceof CategoryElement || (element instanceof IIUElement && ((IIUElement) element).shouldShowChildren())) { // children of a category should drill down according to the context. If we aren't in a category, we are already drilling down and // continue to do so. boolean drillDown = element instanceof CategoryElement ? context.getShowAvailableChildren() : true; Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); if (showLatest) availableIUCollector = new LatestIUVersionElementCollector(queryable, element, true, drillDown); else availableIUCollector = new AvailableIUCollector(queryable, element, true, drillDown); if (targetProfile != null) availableIUCollector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {new CompoundQuery(new Query[] {topLevelQuery, categoryQuery}, false), meetsAnyRequirementQuery}, true), availableIUCollector); } return null; case QueryProvider.AVAILABLE_UPDATES : IProfile profile; IInstallableUnit[] toUpdate = null; if (element instanceof Updates) { try { profile = ProvisioningUtil.getProfile(((Updates) element).getProfileId()); } catch (ProvisionException e) { ProvUI.handleException(e, NLS.bind(ProvUIMessages.DefaultQueryProvider_ErrorRetrievingProfile, ((Updates) element).getProfileId()), StatusManager.LOG); return null; } toUpdate = ((Updates) element).getIUs(); } else { profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); } if (profile == null) return null; Collector collector; if (toUpdate == null) { collector = profile.query(new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new Collector(), null); toUpdate = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); } QueryableUpdates updateQueryable = new QueryableUpdates(toUpdate); if (context.getShowLatestVersionsOnly()) collector = new LatestIUVersionElementCollector(updateQueryable, element, true, false); else collector = new Collector(); return new ElementQueryDescriptor(updateQueryable, allQuery, collector); case QueryProvider.INSTALLED_IUS : // Querying of IU's. We are drilling down into the requirements. if (element instanceof IIUElement && context.getShowInstallChildren()) { Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); Query visibleAsAvailableQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {visibleAsAvailableQuery, meetsAnyRequirementQuery}, true), new InstalledIUCollector(queryable, element)); } profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); if (profile == null) return null; // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=229352 // Rollback profiles are specialized/temporary instances so we must use a query that uses the profile instance, not the id. if (element instanceof RollbackProfileElement) return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new InstalledIUCollector(profile, element)); // Just a normal query of the installed IU's, query the profile and look for the visible ones return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new InstalledIUCollector(profile, element)); case QueryProvider.METADATA_REPOS : if (element instanceof MetadataRepositories) { if (queryable == null) { queryable = new QueryableMetadataRepositoryManager(policy, ((MetadataRepositories) element).getIncludeDisabledRepositories()); element.setQueryable(queryable); } return new ElementQueryDescriptor(element.getQueryable(), null, new MetadataRepositoryElementCollector(element.getQueryable(), element)); } return null; case QueryProvider.PROFILES : queryable = new QueryableProfileRegistry(); return new ElementQueryDescriptor(queryable, new Query() { public boolean isMatch(Object candidate) { return ProvUI.getAdapter(candidate, IProfile.class) != null; } }, new ProfileElementCollector(null, element)); default : return null; } }
public ElementQueryDescriptor getQueryDescriptor(final QueriedElement element) { // Initialize queryable, queryContext, and queryType from the element. // In some cases we override this. IQueryable queryable = element.getQueryable(); int queryType = element.getQueryType(); IUViewQueryContext context = element.getQueryContext(); if (context == null) { context = policy.getQueryContext(); } switch (queryType) { case QueryProvider.ARTIFACT_REPOS : queryable = new QueryableArtifactRepositoryManager(context.getArtifactRepositoryFlags()); return new ElementQueryDescriptor(queryable, null, new Collector() { public boolean accept(Object object) { if (object instanceof URI) return super.accept(new ArtifactRepositoryElement(element, (URI) object)); return true; } }); case QueryProvider.AVAILABLE_IUS : // Things get more complicated if the user wants to filter out installed items. // This involves setting up a secondary query for installed content that the various // collectors will use to reject content. We can't use a compound query because the // queryables are different (profile for installed content, repo for available content) AvailableIUCollector availableIUCollector; boolean showLatest = context.getShowLatestVersionsOnly(); boolean hideInstalled = context.getHideAlreadyInstalled(); IProfile targetProfile = null; String profileId = context.getInstalledProfileId(); if (profileId != null) { try { targetProfile = ProvisioningUtil.getProfile(profileId); } catch (ProvisionException e) { // just bail out, we won't try to query the installed } } // Showing children of a rollback element if (element instanceof RollbackRepositoryElement) { Query profileIdQuery = new InstallableUnitQuery(((RollbackRepositoryElement) element).getProfileId()); Query rollbackIUQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_PROFILE, Boolean.toString(true)); availableIUCollector = new RollbackIUCollector(queryable, element.getParent(element)); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {profileIdQuery, rollbackIUQuery}, true), availableIUCollector); } Query topLevelQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); Query categoryQuery = new IUPropertyQuery(IInstallableUnit.PROP_TYPE_CATEGORY, Boolean.toString(true)); // Showing child IU's of a group of repositories, or of a single repository if (element instanceof MetadataRepositories || element instanceof MetadataRepositoryElement) { if (context.getViewType() == IUViewQueryContext.AVAILABLE_VIEW_FLAT || !context.getUseCategories()) { AvailableIUCollector collector; if (showLatest) collector = new LatestIUVersionElementCollector(queryable, element, false, context.getShowAvailableChildren()); else collector = new AvailableIUCollector(queryable, element, false, context.getShowAvailableChildren()); if (targetProfile != null) collector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, topLevelQuery, collector); } // Installed content not a concern for collecting categories return new ElementQueryDescriptor(queryable, categoryQuery, new CategoryElementCollector(queryable, element, true)); } // Showing children of categories that we've already collected // Must do this one before CategoryElement since it's a subclass if (element instanceof UncategorizedCategoryElement) { // Will have to look at all categories and groups and from there, figure out what's left Query firstPassQuery = new CompoundQuery(new Query[] {topLevelQuery, categoryQuery}, false); availableIUCollector = showLatest ? new LatestIUVersionElementCollector(queryable, element, false, context.getShowAvailableChildren()) : new AvailableIUCollector(queryable, element, false, context.getShowAvailableChildren()); if (targetProfile != null) availableIUCollector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, firstPassQuery, new UncategorizedElementCollector(queryable, element, availableIUCollector)); } // If it's a category or some other IUElement to drill down in, we get the requirements and show all requirements // that are also visible in the available list. if (element instanceof CategoryElement || (element instanceof IIUElement && ((IIUElement) element).shouldShowChildren())) { // children of a category should drill down according to the context. If we aren't in a category, we are already drilling down and // continue to do so. boolean drillDown = element instanceof CategoryElement ? context.getShowAvailableChildren() : true; Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); if (showLatest) availableIUCollector = new LatestIUVersionElementCollector(queryable, element, true, drillDown); else availableIUCollector = new AvailableIUCollector(queryable, element, true, drillDown); if (targetProfile != null) availableIUCollector.markInstalledIUs(targetProfile, hideInstalled); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {new CompoundQuery(new Query[] {topLevelQuery, categoryQuery}, false), meetsAnyRequirementQuery}, true), availableIUCollector); } return null; case QueryProvider.AVAILABLE_UPDATES : IProfile profile; IInstallableUnit[] toUpdate = null; if (element instanceof Updates) { try { profile = ProvisioningUtil.getProfile(((Updates) element).getProfileId()); } catch (ProvisionException e) { ProvUI.handleException(e, NLS.bind(ProvUIMessages.DefaultQueryProvider_ErrorRetrievingProfile, ((Updates) element).getProfileId()), StatusManager.LOG); return null; } toUpdate = ((Updates) element).getIUs(); } else { profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); } if (profile == null) return null; Collector collector; if (toUpdate == null) { collector = profile.query(new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new Collector(), null); toUpdate = (IInstallableUnit[]) collector.toArray(IInstallableUnit.class); } QueryableUpdates updateQueryable = new QueryableUpdates(toUpdate); if (context.getShowLatestVersionsOnly()) collector = new LatestIUVersionElementCollector(updateQueryable, element, true, false); else collector = new Collector(); return new ElementQueryDescriptor(updateQueryable, allQuery, collector); case QueryProvider.INSTALLED_IUS : // Querying of IU's. We are drilling down into the requirements. if (element instanceof IIUElement && context.getShowInstallChildren()) { Query meetsAnyRequirementQuery = new AnyRequiredCapabilityQuery(((IIUElement) element).getRequirements()); Query visibleAsAvailableQuery = new IUPropertyQuery(context.getVisibleAvailableIUProperty(), Boolean.TRUE.toString()); return new ElementQueryDescriptor(queryable, new CompoundQuery(new Query[] {visibleAsAvailableQuery, meetsAnyRequirementQuery}, true), new InstalledIUCollector(queryable, element)); } profile = (IProfile) ProvUI.getAdapter(element, IProfile.class); if (profile == null) return null; // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=229352 // Rollback profiles are specialized/temporary instances so we must use a query that uses the profile instance, not the id. if (element instanceof RollbackProfileElement) return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new InstalledIUCollector(profile, element)); // Just a normal query of the installed IU's, query the profile and look for the visible ones return new ElementQueryDescriptor(profile, new IUProfilePropertyQuery(profile, context.getVisibleInstalledIUProperty(), Boolean.toString(true)), new InstalledIUCollector(profile, element)); case QueryProvider.METADATA_REPOS : if (element instanceof MetadataRepositories) { if (queryable == null) { queryable = new QueryableMetadataRepositoryManager(policy, ((MetadataRepositories) element).getIncludeDisabledRepositories()); element.setQueryable(queryable); } return new ElementQueryDescriptor(element.getQueryable(), null, new MetadataRepositoryElementCollector(element.getQueryable(), element)); } return null; case QueryProvider.PROFILES : queryable = new QueryableProfileRegistry(); return new ElementQueryDescriptor(queryable, new Query() { public boolean isMatch(Object candidate) { return ProvUI.getAdapter(candidate, IProfile.class) != null; } }, new ProfileElementCollector(null, element)); default : return null; } }
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_email.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_email.java index 228398b..22f8d89 100644 --- a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_email.java +++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_email.java @@ -1,26 +1,26 @@ package com.github.zathrus_writer.commandsex.handlers; import java.io.File; import com.github.zathrus_writer.commandsex.CommandsEX; import com.github.zathrus_writer.commandsex.helpers.ClasspathHacker; public class Handler_email { public static boolean classpathAdded = false; public Handler_email(){ - File f = new File(CommandsEX.plugin.getDataFolder() + "/mail.jar"); + File f = new File(CommandsEX.plugin.getDataFolder() + "/commons-email-1.2.jar"); if (!f.exists()){ return; } try { ClasspathHacker.addFile(f); classpathAdded = true; } catch (Exception e){ } } }
true
true
public Handler_email(){ File f = new File(CommandsEX.plugin.getDataFolder() + "/mail.jar"); if (!f.exists()){ return; } try { ClasspathHacker.addFile(f); classpathAdded = true; } catch (Exception e){ } }
public Handler_email(){ File f = new File(CommandsEX.plugin.getDataFolder() + "/commons-email-1.2.jar"); if (!f.exists()){ return; } try { ClasspathHacker.addFile(f); classpathAdded = true; } catch (Exception e){ } }
diff --git a/src/main/java/sorts/impl/DedupingPredicate.java b/src/main/java/sorts/impl/DedupingPredicate.java index 891a262..97b2f36 100644 --- a/src/main/java/sorts/impl/DedupingPredicate.java +++ b/src/main/java/sorts/impl/DedupingPredicate.java @@ -1,60 +1,60 @@ package sorts.impl; import java.nio.charset.CharacterCodingException; import java.util.Map.Entry; import java.util.Set; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Value; import org.apache.hadoop.io.Text; import sorts.options.Defaults; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Sets; /** * This is apt to be stupidly slow. Perhaps use a bloomfilter instead? * Perhaps the API itself should just allow the client to specify when it * cares about getting dupes. */ public class DedupingPredicate implements Predicate<Entry<Key,Value>> { protected final Set<String> uids; private final Text holder; public DedupingPredicate() { uids = Sets.newHashSetWithExpectedSize(64); holder = new Text(); } @Override public boolean apply(Entry<Key,Value> input) { Preconditions.checkNotNull(input); Preconditions.checkNotNull(input.getKey()); input.getKey().getColumnQualifier(holder); int index = holder.find(Defaults.NULL_BYTE_STR); Preconditions.checkArgument(-1 != index); String uid = null; try { - uid = Text.decode(holder.getBytes(), index + 1, holder.getLength()); + uid = Text.decode(holder.getBytes(), index + 1, holder.getLength() - (index + 1)); } catch (CharacterCodingException e) { throw new RuntimeException(e); } // If we haven't seen this UID yet, note such, and then keep this item if (!uids.contains(uid)) { uids.add(uid); return true; } // Otherwise, don't re-return this item return false; } }
true
true
public boolean apply(Entry<Key,Value> input) { Preconditions.checkNotNull(input); Preconditions.checkNotNull(input.getKey()); input.getKey().getColumnQualifier(holder); int index = holder.find(Defaults.NULL_BYTE_STR); Preconditions.checkArgument(-1 != index); String uid = null; try { uid = Text.decode(holder.getBytes(), index + 1, holder.getLength()); } catch (CharacterCodingException e) { throw new RuntimeException(e); } // If we haven't seen this UID yet, note such, and then keep this item if (!uids.contains(uid)) { uids.add(uid); return true; } // Otherwise, don't re-return this item return false; }
public boolean apply(Entry<Key,Value> input) { Preconditions.checkNotNull(input); Preconditions.checkNotNull(input.getKey()); input.getKey().getColumnQualifier(holder); int index = holder.find(Defaults.NULL_BYTE_STR); Preconditions.checkArgument(-1 != index); String uid = null; try { uid = Text.decode(holder.getBytes(), index + 1, holder.getLength() - (index + 1)); } catch (CharacterCodingException e) { throw new RuntimeException(e); } // If we haven't seen this UID yet, note such, and then keep this item if (!uids.contains(uid)) { uids.add(uid); return true; } // Otherwise, don't re-return this item return false; }
diff --git a/UniQuest/src/main/Game.java b/UniQuest/src/main/Game.java index 621a7e8..e14bf3e 100644 --- a/UniQuest/src/main/Game.java +++ b/UniQuest/src/main/Game.java @@ -1,639 +1,639 @@ package main; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import main.interactables.Chest; import main.interactables.Door; import main.interactables.Interactable; import main.interactables.Portal; import main.interactables.SignPost; import main.interfaces.GameMenuInterface; import main.interfaces.PlayerInterface; import main.world.Map; import main.world.Square; import main.world.World; import org.lwjgl.Sys; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import util.InvalidEscapeSequenceException; import util.geom.Point; import util.gl.Font; import util.input.Input; import util.input.KeyEvent; import util.input.MouseEvent; import util.ui.GLButton; import util.ui.GLUIException; import util.ui.GLUITheme; /** * Game class holds the running of our game. * */ public class Game { /** Instance of Player that the user will control */ public static Player player; /** Instance of Interface that displays player data */ private static PlayerInterface gameInterface; /** Instance of Map to hold the current map */ public static Map map; /** ArrayList to hold Interactables in the game */ public static ArrayList<Interactable> interactables; /** The current state the game is in */ public static int GAME_STATE; /** The initial state when the game is run */ public static final int GAME_STATE_START = 0; /** The state whilst the game is being played */ public static final int GAME_STATE_PLAYING = 1; /** The state when the player has died */ public static final int GAME_STATE_DEAD = 2; /** The state when quit has been requested */ public static final int GAME_STATE_QUIT = 3; /** The interface for the in game menu */ private GameMenuInterface gameMenu; public static ArrayList<Entity> entities; private Entity testEntity, questGiver; private RightClickMenu rightClickMenu, entityMenu, interactableMenu, walkHereMenu, closeMenu; private boolean rightMenu = false; private Object focus; private Font font; int fps; long lastFPS, lastFrame; /** Constructor for the game */ public Game() { //GAME_STATE = GAME_STATE_START; GAME_STATE = GAME_STATE_PLAYING; try { player = Player.loadPlayer("New Player.sav"); // Uncomment the following line after testing. //GAME_STATE = GAME_STATE_PLAYING; } catch (FileNotFoundException e) { player = new Player("New Player"); } catch (IOException e) { e.printStackTrace(); } } /** * This method when called runs the game and houses the * main loop that the game runs out of. Responsible for * dealing with game state changes. * */ public void begin() { Keyboard.enableRepeatEvents(true); new World(); World.setCurrentMap(player.getSceneX(), player.getSceneY()); gameInterface = new PlayerInterface(); gameMenu = new GameMenuInterface(); setupInteractables(); entities = new ArrayList<Entity>(); testEntity = new FriendlyNPC("Dave", 7, 12*Main.gridSize, 12*Main.gridSize, 0, 0); questGiver = new QuestGiver("SHAMALA", 9, 15*Main.gridSize, 17*Main.gridSize, 0, 0, "001"); entities.add(player); entities.add(testEntity); entities.add(questGiver); try { font = new GLUITheme().getFont(); createMenus(); } catch (GLUIException e) { e.printStackTrace(); } while (GAME_STATE != GAME_STATE_QUIT) { switch (GAME_STATE) { case GAME_STATE_START: try { gameStateStart(); } catch (InvalidEscapeSequenceException e1) { } break; case GAME_STATE_PLAYING: try { gameStatePlaying(); } catch (ConcurrentModificationException e) { } break; case GAME_STATE_DEAD: gameStateDead(); break; default: GAME_STATE = GAME_STATE_QUIT; break; } } } /** * TODO: Opening story goes here, tutorial section etc. * * Beginning section goes here, everything that isn't required * later on. * @throws InvalidEscapeSequenceException * */ private void gameStateStart() throws InvalidEscapeSequenceException { boolean done = false; Display.sync(60); while (!done) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); GL11.glClearColor(0, 0, 0, 1); drawBackground(); font.glDrawText("\\c#FFFFFFPress ESCAPE to skip...", Main.SCREEN_WIDTH-200, Main.SCREEN_HEIGHT-50); Display.update(); if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { done = true; } else if (Display.isCloseRequested()) { done = true; Game.GAME_STATE = Game.GAME_STATE_QUIT; } } fade(); GAME_STATE = GAME_STATE_PLAYING; } private void drawBackground() { int border = 80; GL11.glBegin(GL11.GL_QUADS); { GL11.glColor3d(255, 255, 255); GL11.glVertex2d(0, border); GL11.glVertex2d(Main.SCREEN_WIDTH, border); GL11.glVertex2d(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT-border); GL11.glVertex2d(0, Main.SCREEN_HEIGHT-border); } GL11.glEnd(); } private void fade() { float alpha = 1; while (alpha > 0) { render(); GL11.glBegin(GL11.GL_QUADS); { GL11.glColor4d(0, 0, 0, alpha); GL11.glVertex2d(0, 0); GL11.glVertex2d(Main.SCREEN_WIDTH, 0); GL11.glVertex2d(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT); GL11.glVertex2d(0, Main.SCREEN_HEIGHT); } GL11.glEnd(); alpha-=0.0005; Display.update(); if (Display.isCloseRequested()) { alpha = 0; GAME_STATE = GAME_STATE_QUIT; } } } /** * The playing state of the game corresponding to GAME_STATE_PLAYING. * */ private void gameStatePlaying() throws ConcurrentModificationException { while (GAME_STATE == GAME_STATE_PLAYING && !Display.isCloseRequested()) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); render(); Input.poll(); List<KeyEvent> keyEvents = Input.getKeyEvents(); List<MouseEvent> mouseEvents = Input.getMouseEvents(); if (rightMenu) { rightClickMenu.renderGL(); rightClickMenu.update(0); rightClickMenu.processMouseEvents(mouseEvents); } for (KeyEvent e : keyEvents) { if (e.getEvent() == KeyEvent.KEY_PRESSED) { player.input(e); } else if (e.getEvent() == KeyEvent.KEY_RELEASED && !e.isRepeatEvent()) { if (e.getKeyCode() == Main.KeyBindings.KEY_INTERACT.getUserKey()) { checkInteractables(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_INVENTORY.getUserKey()) { player.getInventory().showInventory(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_MENU.getUserKey()) { gameMenu.showInterface(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_QUESTLOG.getUserKey()) { player.getQuestLog().showInterface(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_TALK.getUserKey()) { interactEntities(); } } } for (MouseEvent e : mouseEvents) { if (e.getEvent() == MouseEvent.BUTTON_PRESSED) { if (Input.isMouseButtonDown(Input.RIGHT_MOUSE) && e.getEventX() < Main.SCREEN_PLAYABLE_WIDTH && e.getEventY() < Main.SCREEN_PLAYABLE_HEIGHT) { rightMenu = true; focus = getFocusObject(e); if (focus instanceof Entity) { rightClickMenu = entityMenu; } else if (focus instanceof Interactable){ rightClickMenu = interactableMenu; } else if (focus instanceof Square) { rightClickMenu = walkHereMenu; } else { rightClickMenu = closeMenu; } rightClickMenu.setContext(focus); rightClickMenu.setCoordinates(e); - } else if (Input.isMouseButtonDown(Input.LEFT_MOUSE)) { + } else { rightMenu = false; } } } Display.update(); if (Display.isCloseRequested()) { try { player.savePlayer(); } catch (IOException e) { System.err.println("Could not save player data"); e.printStackTrace(); } GAME_STATE = GAME_STATE_QUIT; } } } public static void render() { World.draw(); gameInterface.updateInterface(); drawInteractables(); drawEntities(); //drawGrid(); } /** * TODO: Implement death screen / game over<p> * * Death screen state of the game, once the player's health <= 0. * Corresponds to GAME_STATE_DEAD. * */ private void gameStateDead() { /* * Game Over * Write player stats to the screen * Offer to play again or maybe just take straight to the menu * */ GAME_STATE = GAME_STATE_QUIT; } /** * Draws a grid to the screen for development purposes and so * should not be included in final versions.<p> * * The grid size is specified by the global variable gridSize. * Entity movement is based on this grid size. * */ @SuppressWarnings("unused") private static void drawGrid() { GL11.glColor4f(0f, 0f, 0f, 0.1f); GL11.glBegin(GL11.GL_LINES); // Draw vertical lines for (int i = 0; i <= Main.SCREEN_PLAYABLE_WIDTH/Main.gridSize; i++) { GL11.glVertex2f(i*Main.gridSize, 0); GL11.glVertex2f(i*Main.gridSize, Main.SCREEN_PLAYABLE_HEIGHT); } // Draw horizontal lines for (int i = 0; i <= Main.SCREEN_PLAYABLE_HEIGHT/Main.gridSize; i++) { GL11.glVertex2f(0, i*Main.gridSize); GL11.glVertex2f(Main.SCREEN_PLAYABLE_WIDTH, i*Main.gridSize); } GL11.glEnd(); } private void setupInteractables() { interactables = new ArrayList<Interactable>(); Scanner s = new Scanner(ResourceManager.getResourceAsStream("../main/interactables/interactables")); while (s.hasNext()) { String[] strs = s.nextLine().split(", "); if (strs[0].equals("portal")) { Interactable i = new Portal(Integer.parseInt(strs[1]), Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]), Integer.parseInt(strs[5]), Integer.parseInt(strs[6]), Integer.parseInt(strs[7]), Integer.parseInt(strs[8])); interactables.add(i); } else if (strs[0].equals("signpost")) { Interactable i = new SignPost(strs[1], Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]), Integer.parseInt(strs[5])); interactables.add(i); } else if (strs[0].equals("chest")) { LinkedList<Item> items = new LinkedList<Item>(); if (strs.length > 5) { for (int i = 5; i < strs.length; i++) { items.add(Item.getItem(strs[i])); } } Interactable i = new Chest(Integer.parseInt(strs[1]), Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]), items); interactables.add(i); } else if (strs[0].equals("door")) { Interactable i = new Door(Integer.parseInt(strs[1]), Integer.parseInt(strs[2]), Integer.parseInt(strs[3]), Integer.parseInt(strs[4]), Boolean.parseBoolean(strs[5])); interactables.add(i); } } s.close(); } private static void drawInteractables() { for (Interactable i : interactables) { i.draw(); } } private void checkInteractables() { for (Interactable i : interactables) { if (i.checkPlayer()) { i.activate(); } } } private static void drawEntities() { for (Entity e : entities) { if (World.currentMap().getSceneX() == e.getSceneX() && World.currentMap().getSceneY() == e.getSceneY()) e.draw(); } } private void interactEntities() { for (Entity e : entities) { if (!(e instanceof Player)) { if (player.nextToEntity(e)) { e.interact(); } } } } private void createMenus() throws GLUIException { entityMenu = new RightClickMenu(); interactableMenu = new RightClickMenu(); walkHereMenu = new RightClickMenu(); closeMenu = new RightClickMenu(); GLButton talkButton = new GLButton("Talk", new GLUITheme()) { @Override protected void onClick() { ((FriendlyNPC)RightClickMenu.getContext()).interact(); } }; talkButton.setLabelAlignment(GLButton.ALIGN_LEFT); GLButton closeButton = new GLButton("Close", new GLUITheme()) { @Override protected void onClick() { rightMenu = false; } }; closeButton.setLabelAlignment(GLButton.ALIGN_LEFT); entityMenu.addButton(talkButton); entityMenu.addButton(closeButton); GLButton interactButton = new GLButton("Interact", new GLUITheme()) { @Override protected void onClick() { ((Interactable)RightClickMenu.getContext()).activate(); } }; interactButton.setLabelAlignment(GLButton.ALIGN_LEFT); interactableMenu.addButton(interactButton); interactableMenu.addButton(closeButton); GLButton walkHere = new GLButton("Walk here", new GLUITheme()) { @Override protected void onClick() { // TODO: Add walk here functionality. } }; walkHere.setLabelAlignment(GLButton.ALIGN_LEFT); walkHereMenu.addButton(walkHere); walkHereMenu.addButton(closeButton); closeMenu.addButton(closeButton); } private Object getFocusObject(MouseEvent event) { /* * We need to search through entities, interactables, * items and finally the world to see what exists * at the event point. */ Point p = event.getEventPoint(); for (Entity e : entities) { if (p.getX()-e.getX() <= e.getW() && p.getX()-e.getX() > 0 && p.getY()-e.getY() <= e.getH() && p.getY()-e.getY() > 0 && e.getSceneX() == World.currentMap().getSceneX() && e.getSceneY() == World.currentMap().getSceneY() && !(e instanceof Player)) { return e; } } for (Interactable e : interactables) { // We need to deal with special case of a portal if (e instanceof Portal) { Portal t = (Portal)e; if (p.getX()-t.getX0() <= Main.gridSize && p.getX()-t.getX0() > 0 && p.getY()-t.getY0() <= Main.gridSize && p.getY()-t.getY0()>0) { if (t.getSceneX0() == World.currentMap().getSceneX() && t.getSceneY0() == World.currentMap().getSceneY()) { return e; } } else if (p.getX()-t.getX1() <= Main.gridSize && p.getX()-t.getX1() > 0 && p.getY()-t.getY1() <= Main.gridSize && p.getY()-t.getY1()>0) { if (t.getSceneX1() == World.currentMap().getSceneX() && t.getSceneY1() == World.currentMap().getSceneY()) { return e; } } } else if (p.getX()-e.getX() <= Main.gridSize && p.getX()-e.getX() > 0 && p.getY()-e.getY() <= Main.gridSize && p.getY()-e.getY() > 0) { if (e.getSceneX() == World.currentMap().getSceneX() && e.getSceneY() == World.currentMap().getSceneY()) { return e; } } } Square s = World.currentMap().getSquare(p); if (!s.isSolid()) { return s; } return null; } public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } public int getDelta() { long time = getTime(); int delta = (int)(time-lastFrame); lastFrame = time; return delta; } }
true
true
private void gameStatePlaying() throws ConcurrentModificationException { while (GAME_STATE == GAME_STATE_PLAYING && !Display.isCloseRequested()) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); render(); Input.poll(); List<KeyEvent> keyEvents = Input.getKeyEvents(); List<MouseEvent> mouseEvents = Input.getMouseEvents(); if (rightMenu) { rightClickMenu.renderGL(); rightClickMenu.update(0); rightClickMenu.processMouseEvents(mouseEvents); } for (KeyEvent e : keyEvents) { if (e.getEvent() == KeyEvent.KEY_PRESSED) { player.input(e); } else if (e.getEvent() == KeyEvent.KEY_RELEASED && !e.isRepeatEvent()) { if (e.getKeyCode() == Main.KeyBindings.KEY_INTERACT.getUserKey()) { checkInteractables(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_INVENTORY.getUserKey()) { player.getInventory().showInventory(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_MENU.getUserKey()) { gameMenu.showInterface(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_QUESTLOG.getUserKey()) { player.getQuestLog().showInterface(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_TALK.getUserKey()) { interactEntities(); } } } for (MouseEvent e : mouseEvents) { if (e.getEvent() == MouseEvent.BUTTON_PRESSED) { if (Input.isMouseButtonDown(Input.RIGHT_MOUSE) && e.getEventX() < Main.SCREEN_PLAYABLE_WIDTH && e.getEventY() < Main.SCREEN_PLAYABLE_HEIGHT) { rightMenu = true; focus = getFocusObject(e); if (focus instanceof Entity) { rightClickMenu = entityMenu; } else if (focus instanceof Interactable){ rightClickMenu = interactableMenu; } else if (focus instanceof Square) { rightClickMenu = walkHereMenu; } else { rightClickMenu = closeMenu; } rightClickMenu.setContext(focus); rightClickMenu.setCoordinates(e); } else if (Input.isMouseButtonDown(Input.LEFT_MOUSE)) { rightMenu = false; } } } Display.update(); if (Display.isCloseRequested()) { try { player.savePlayer(); } catch (IOException e) { System.err.println("Could not save player data"); e.printStackTrace(); } GAME_STATE = GAME_STATE_QUIT; } } }
private void gameStatePlaying() throws ConcurrentModificationException { while (GAME_STATE == GAME_STATE_PLAYING && !Display.isCloseRequested()) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); render(); Input.poll(); List<KeyEvent> keyEvents = Input.getKeyEvents(); List<MouseEvent> mouseEvents = Input.getMouseEvents(); if (rightMenu) { rightClickMenu.renderGL(); rightClickMenu.update(0); rightClickMenu.processMouseEvents(mouseEvents); } for (KeyEvent e : keyEvents) { if (e.getEvent() == KeyEvent.KEY_PRESSED) { player.input(e); } else if (e.getEvent() == KeyEvent.KEY_RELEASED && !e.isRepeatEvent()) { if (e.getKeyCode() == Main.KeyBindings.KEY_INTERACT.getUserKey()) { checkInteractables(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_INVENTORY.getUserKey()) { player.getInventory().showInventory(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_MENU.getUserKey()) { gameMenu.showInterface(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_QUESTLOG.getUserKey()) { player.getQuestLog().showInterface(); } else if (e.getKeyCode() == Main.KeyBindings.KEY_TALK.getUserKey()) { interactEntities(); } } } for (MouseEvent e : mouseEvents) { if (e.getEvent() == MouseEvent.BUTTON_PRESSED) { if (Input.isMouseButtonDown(Input.RIGHT_MOUSE) && e.getEventX() < Main.SCREEN_PLAYABLE_WIDTH && e.getEventY() < Main.SCREEN_PLAYABLE_HEIGHT) { rightMenu = true; focus = getFocusObject(e); if (focus instanceof Entity) { rightClickMenu = entityMenu; } else if (focus instanceof Interactable){ rightClickMenu = interactableMenu; } else if (focus instanceof Square) { rightClickMenu = walkHereMenu; } else { rightClickMenu = closeMenu; } rightClickMenu.setContext(focus); rightClickMenu.setCoordinates(e); } else { rightMenu = false; } } } Display.update(); if (Display.isCloseRequested()) { try { player.savePlayer(); } catch (IOException e) { System.err.println("Could not save player data"); e.printStackTrace(); } GAME_STATE = GAME_STATE_QUIT; } } }
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/OAuth.java b/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/OAuth.java index 5a56e6a2f..9f8ed7b48 100644 --- a/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/OAuth.java +++ b/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/OAuth.java @@ -1,187 +1,191 @@ /** * Copyright (c) 2009 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.fedoraproject.candlepin.resteasy.interceptor; import java.io.IOException; import com.google.inject.Injector; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import javax.ws.rs.core.Response; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthException; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.OAuthValidator; import net.oauth.SimpleOAuthValidator; import net.oauth.signature.OAuthSignatureMethod; import org.apache.log4j.Logger; import org.fedoraproject.candlepin.auth.Principal; import org.fedoraproject.candlepin.config.Config; import org.fedoraproject.candlepin.exceptions.BadRequestException; import org.fedoraproject.candlepin.exceptions.CandlepinException; import org.fedoraproject.candlepin.exceptions.IseException; import org.fedoraproject.candlepin.model.OwnerCurator; import org.fedoraproject.candlepin.service.UserServiceAdapter; import org.jboss.resteasy.spi.HttpRequest; import com.google.inject.Inject; /** * Uses two legged OAuth. If it succeeds, then it pulls the username off of a * headers and creates a principal based only on the username */ public class OAuth extends UserAuth { protected static final String HEADER = "cp-user"; protected static final OAuthValidator VALIDATOR = new SimpleOAuthValidator(); protected static final String SIGNATURE_TYPE = "HMAC-SHA1"; private Logger log = Logger.getLogger(OAuth.class);; private Config config; private Map<String, OAuthAccessor> accessors = new HashMap<String, OAuthAccessor>(); @Inject OAuth(UserServiceAdapter userServiceAdapter, OwnerCurator ownerCurator, Injector injector, Config config) { super(userServiceAdapter, ownerCurator, injector); this.config = config; this.setupAccessors(); this.setupSigners(); } /** * Attempt to pull a principal off of an oauth signed message. * * @return the principal if it can be created, nil otherwise */ public Principal getPrincipal(HttpRequest request) { Principal principal = null; log.debug("Checking for oauth authentication"); try { if (getHeader(request, "Authorization").contains("oauth")) { OAuthMessage requestMessage = new RestEasyOAuthMessage(request); OAuthAccessor accessor = this.getAccessor(requestMessage); // TODO: This is known to be memory intensive. VALIDATOR.validateMessage(requestMessage, accessor); // If we got here, it is a valid oauth message String username = getHeader(request, HEADER); if ((username == null) || (username.equals(""))) { String msg = i18n .tr("No username provided for oauth request"); throw new BadRequestException(msg); } principal = createPrincipal(username); if (log.isDebugEnabled()) { log.debug("principal created for owner '" + principal.getOwner().getDisplayName() + "' with username '" + username + "'"); } } } catch (OAuthProblemException e) { - e.printStackTrace(); + log.debug("OAuth Problem", e); Response.Status returnCode = Response.Status.fromStatusCode(e .getHttpStatusCode()); - throw new CandlepinException(returnCode, e.getMessage()); + String message = i18n.tr("Oauth problem encountered. Internal message is: {0}", + e.getMessage()); + throw new CandlepinException(returnCode, message); } catch (OAuthException e) { - e.printStackTrace(); - throw new BadRequestException(e.getMessage()); + log.debug("OAuth Error", e); + String message = i18n.tr("Oauth error encountered. Internal message is: {0}", + e.getMessage()); + throw new BadRequestException(message); } catch (URISyntaxException e) { throw new IseException(e.getMessage(), e); } catch (IOException e) { throw new IseException(e.getMessage(), e); } return principal; } /** * Get an oauth accessor for a given message. An exception is thrown if no * accessor is found. * * @param msg * @return */ protected OAuthAccessor getAccessor(OAuthMessage msg) { try { OAuthAccessor accessor = accessors.get(msg.getConsumerKey()); if (accessor == null) { throw new BadRequestException( i18n.tr("No oauth consumer found for key {0}", msg.getConsumerKey())); } return accessor; } catch (IOException e) { throw new IseException(i18n.tr("Error getting oauth consumer Key", e)); } } /** * Look for settings which are in the form of * candlepin.auth.oauth.consumer.CONSUMERNAME.secret = CONSUMERSECRET and * create consumers for them. */ protected void setupAccessors() { String prefix = "candlepin.auth.oauth.consumer"; Properties props = config.getNamespaceProperties(prefix); for (Entry<Object, Object> entry : props.entrySet()) { String key = (String) entry.getKey(); key = key.replace(prefix + ".", ""); String[] parts = key.split("\\."); if ((parts.length == 2) && (parts[1].equals("secret"))) { String consumerName = parts[0]; String sekret = (String) entry.getValue(); log.debug(String.format( "Creating consumer '%s' with secret '%s'", consumerName, sekret)); OAuthConsumer consumer = new OAuthConsumer("", consumerName, sekret, null); OAuthAccessor accessor = new OAuthAccessor(consumer); accessors.put(consumerName, accessor); } } } /** * Override the built in signer for HMAC-SHA1 so that we can see better * output. */ protected void setupSigners() { log.debug("Add custom signers"); OAuthSignatureMethod.registerMethodClass(SIGNATURE_TYPE + OAuthSignatureMethod._ACCESSOR, net.oauth.signature.CustomSigner.class); OAuthSignatureMethod.registerMethodClass(SIGNATURE_TYPE, net.oauth.signature.CustomSigner.class); } }
false
true
public Principal getPrincipal(HttpRequest request) { Principal principal = null; log.debug("Checking for oauth authentication"); try { if (getHeader(request, "Authorization").contains("oauth")) { OAuthMessage requestMessage = new RestEasyOAuthMessage(request); OAuthAccessor accessor = this.getAccessor(requestMessage); // TODO: This is known to be memory intensive. VALIDATOR.validateMessage(requestMessage, accessor); // If we got here, it is a valid oauth message String username = getHeader(request, HEADER); if ((username == null) || (username.equals(""))) { String msg = i18n .tr("No username provided for oauth request"); throw new BadRequestException(msg); } principal = createPrincipal(username); if (log.isDebugEnabled()) { log.debug("principal created for owner '" + principal.getOwner().getDisplayName() + "' with username '" + username + "'"); } } } catch (OAuthProblemException e) { e.printStackTrace(); Response.Status returnCode = Response.Status.fromStatusCode(e .getHttpStatusCode()); throw new CandlepinException(returnCode, e.getMessage()); } catch (OAuthException e) { e.printStackTrace(); throw new BadRequestException(e.getMessage()); } catch (URISyntaxException e) { throw new IseException(e.getMessage(), e); } catch (IOException e) { throw new IseException(e.getMessage(), e); } return principal; }
public Principal getPrincipal(HttpRequest request) { Principal principal = null; log.debug("Checking for oauth authentication"); try { if (getHeader(request, "Authorization").contains("oauth")) { OAuthMessage requestMessage = new RestEasyOAuthMessage(request); OAuthAccessor accessor = this.getAccessor(requestMessage); // TODO: This is known to be memory intensive. VALIDATOR.validateMessage(requestMessage, accessor); // If we got here, it is a valid oauth message String username = getHeader(request, HEADER); if ((username == null) || (username.equals(""))) { String msg = i18n .tr("No username provided for oauth request"); throw new BadRequestException(msg); } principal = createPrincipal(username); if (log.isDebugEnabled()) { log.debug("principal created for owner '" + principal.getOwner().getDisplayName() + "' with username '" + username + "'"); } } } catch (OAuthProblemException e) { log.debug("OAuth Problem", e); Response.Status returnCode = Response.Status.fromStatusCode(e .getHttpStatusCode()); String message = i18n.tr("Oauth problem encountered. Internal message is: {0}", e.getMessage()); throw new CandlepinException(returnCode, message); } catch (OAuthException e) { log.debug("OAuth Error", e); String message = i18n.tr("Oauth error encountered. Internal message is: {0}", e.getMessage()); throw new BadRequestException(message); } catch (URISyntaxException e) { throw new IseException(e.getMessage(), e); } catch (IOException e) { throw new IseException(e.getMessage(), e); } return principal; }
diff --git a/support/org/intellij/grammar/generator/ExpressionGeneratorHelper.java b/support/org/intellij/grammar/generator/ExpressionGeneratorHelper.java index 23408b9..4d8ae56 100644 --- a/support/org/intellij/grammar/generator/ExpressionGeneratorHelper.java +++ b/support/org/intellij/grammar/generator/ExpressionGeneratorHelper.java @@ -1,221 +1,227 @@ /* * Copyright 2011-2012 Gregory Shrago * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.grammar.generator; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.intellij.grammar.KnownAttribute; import org.intellij.grammar.psi.BnfExpression; import org.intellij.grammar.psi.BnfRule; import java.util.*; import static org.intellij.grammar.generator.ExpressionHelper.OperatorInfo; import static org.intellij.grammar.generator.ExpressionHelper.OperatorType; import static org.intellij.grammar.generator.ParserGeneratorUtil.addWarning; import static org.intellij.grammar.generator.ParserGeneratorUtil.getNextName; import static org.intellij.grammar.generator.ParserGeneratorUtil.quote; /** * @author greg */ public class ExpressionGeneratorHelper { public static void generateExpressionRoot(ExpressionHelper.ExpressionInfo info, ParserGenerator g) { Map<String, List<OperatorInfo>> opCalls = new LinkedHashMap<String, List<OperatorInfo>>(); for (BnfRule rule : info.priorityMap.keySet()) { OperatorInfo operator = info.operatorMap.get(rule); String opCall = g.generateNodeCall(info.rootRule, operator.operator, getNextName(operator.rule.getName(), 0)); List<OperatorInfo> list = opCalls.get(opCall); if (list == null) opCalls.put(opCall, list = new ArrayList<OperatorInfo>(2)); list.add(operator); } Set<String> sortedOpCalls = opCalls.keySet(); for (String s : info.toString().split("\n")) { g.out("// " + s); } // main entry String methodName = info.rootRule.getName(); String kernelMethodName = getNextName(methodName, 0); String frameName = quote(ParserGeneratorUtil.getRuleDisplayName(info.rootRule, true)); g.out("public static boolean " + methodName + "(PsiBuilder builder_, int level_, int priority_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + methodName + "\")) return false;"); g.out("Marker marker_ = builder_.mark();"); g.out("boolean result_ = false;"); g.out("boolean pinned_ = false;"); g.out("enterErrorRecordingSection(builder_, level_, _SECTION_GENERAL_, " + frameName + ");"); boolean first = true; for (String opCall : sortedOpCalls) { OperatorInfo operator = ContainerUtil.getFirstItem(findOperators(opCalls.get(opCall), OperatorType.ATOM, OperatorType.PREFIX)); if (operator == null) continue; String nodeCall = g.generateNodeCall(operator.rule, null, operator.rule.getName()); g.out((first ? "" : "if (!result_) ") + "result_ = " + nodeCall + ";"); first = false; } g.out("pinned_ = result_;"); g.out("result_ = result_ && " + kernelMethodName + "(builder_, level_ + 1, priority_);"); g.out("if (!result_ && !pinned_) {"); g.out("marker_.rollbackTo();"); g.out("}"); g.out("else {"); g.out("marker_.drop();"); g.out("}"); g.out("result_ = exitErrorRecordingSection(builder_, level_, result_, pinned_, _SECTION_GENERAL_, null);"); g.out("return result_ || pinned_;"); g.out("}"); g.newLine(); // kernel g.out("public static boolean " + kernelMethodName + "(PsiBuilder builder_, int level_, int priority_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + kernelMethodName + "\")) return false;"); g.out("boolean result_ = true;"); g.out("while (true) {"); g.out("Marker left_marker_ = (Marker) builder_.getLatestDoneMarker();"); g.out("if (!invalid_left_marker_guard_(builder_, left_marker_, \"" + kernelMethodName + "\")) return false;"); - g.out("Marker marker_ = builder_.mark();"); first = true; for (String opCall : sortedOpCalls) { OperatorInfo operator = ContainerUtil.getFirstItem(findOperators(opCalls.get(opCall), OperatorType.BINARY, OperatorType.N_ARY, OperatorType.POSTFIX)); if (operator == null) continue; int priority = info.getPriority(operator.rule); String substCheck = ""; if (operator.substitutor != null) { substCheck = " && ((LighterASTNode)left_marker_).getTokenType() == " + ParserGeneratorUtil.getElementType(operator.substitutor); } + if (first) g.out("Marker marker_ = builder_.mark();"); g.out((first ? "" : "else ") + "if (priority_ < " + priority + substCheck + " && " + opCall + ") {"); first = false; String elementType = ParserGeneratorUtil.getElementType(operator.rule); boolean rightAssociative = ParserGeneratorUtil.getAttribute(operator.rule, KnownAttribute.RIGHT_ASSOCIATIVE); String tailCall = operator.tail == null ? null : g.generateNodeCall(operator.rule, operator.tail, getNextName(operator.rule.getName(), 1)); if (operator.type == OperatorType.BINARY) { g.out( "result_ = report_error_(builder_, " + methodName + "(builder_, level_, " + (rightAssociative ? priority - 1 : priority) + "));"); if (tailCall != null) g.out("result_ = " + tailCall + " && result_;"); } else if (operator.type == OperatorType.N_ARY) { g.out("while (true) {"); g.out("result_ = report_error_(builder_, " + methodName + "(builder_, level_, " + priority + "));"); if (tailCall != null) g.out("result_ = " + tailCall + " && result_;"); g.out("if (!" + opCall + ") break;"); g.out("}"); } else if (operator.type == OperatorType.POSTFIX) { g.out("result_ = true;"); } g.out("marker_.drop();"); g.out("left_marker_.precede().done(" + elementType + ");"); g.out("}"); } - g.out("else {"); - g.out("marker_.rollbackTo();"); - g.out("break;"); - g.out("}"); + if (first) { + g.out("// no BINARY or POSTFIX operators present"); + g.out("break;"); + } + else { + g.out("else {"); + g.out("marker_.rollbackTo();"); + g.out("break;"); + g.out("}"); + } g.out("}"); g.out("return result_;"); g.out("}"); // operators and tails THashSet<BnfExpression> visited = new THashSet<BnfExpression>(); for (String opCall : sortedOpCalls) { for (OperatorInfo operator : opCalls.get(opCall)) { if (operator.type == OperatorType.ATOM) { g.newLine(); g.generateNode(operator.rule, operator.rule.getExpression(), operator.rule.getName(), visited); continue; } else if (operator.type == OperatorType.PREFIX) { g.newLine(); String operatorFuncName = operator.rule.getName(); g.out("public static boolean " + operatorFuncName + "(PsiBuilder builder_, int level_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + operatorFuncName + "\")) return false;"); g.out("boolean result_ = false;"); g.out("boolean pinned_ = false;"); g.out("Marker marker_ = builder_.mark();"); g.out("enterErrorRecordingSection(builder_, level_, _SECTION_GENERAL_, null);"); String elementType = ParserGeneratorUtil.getElementType(operator.rule); String tailCall = operator.tail == null ? null : g.generateNodeCall(operator.rule, operator.tail, getNextName(operator.rule.getName(), 1)); g.out("result_ = "+opCall+";"); g.out("pinned_ = result_;"); Integer substitutorPriority = operator.substitutor == null ? null : info.getPriority(operator.substitutor); int rulePriority = info.getPriority(operator.rule); int priority = substitutorPriority == null ? (rulePriority == info.nextPriority - 1 ? -1 : rulePriority) : substitutorPriority; g.out("result_ = pinned_ && " + methodName + "(builder_, level_, " + priority + ") && result_;"); if (tailCall != null) { g.out("result_ = pinned_ && report_error_(builder_, " + tailCall + ") && result_;"); } g.out("if (result_ || pinned_) {"); if (StringUtil.isNotEmpty(elementType)) { g.out("marker_.done(" + elementType + ");"); } else { g.out("marker_.drop();"); } g.out("}"); g.out("else {"); g.out("marker_.rollbackTo();"); g.out("}"); g.out("result_ = exitErrorRecordingSection(builder_, level_, result_, pinned_, _SECTION_GENERAL_, null);"); g.out("return result_ || pinned_;"); g.out("}"); } g.generateNodeChild(operator.rule, operator.operator, operator.rule.getName(), 0, visited); if (operator.tail != null) { g.generateNodeChild(operator.rule, operator.tail, operator.rule.getName(), 1, visited); } } } } private static List<OperatorInfo> findOperators(Collection<OperatorInfo> list, OperatorType... types) { SmartList<OperatorInfo> result = new SmartList<OperatorInfo>(); List<OperatorType> typeList = Arrays.asList(types); for (OperatorInfo o : list) { if (ContainerUtil.find(typeList, o.type) != null) { result.add(o); } } if (result.size() > 1) { OperatorInfo info = list.iterator().next(); addWarning(info.rule.getProject(), "only first definition will be used for '" + info.operator.getText() + "': " + typeList); } return result; } public static ExpressionHelper.ExpressionInfo getInfoForExpressionParsing(ExpressionHelper expressionHelper, BnfRule rule) { ExpressionHelper.ExpressionInfo expressionInfo = expressionHelper.getExpressionInfo(rule); OperatorInfo operatorInfo = expressionInfo == null ? null : expressionInfo.operatorMap.get(rule); if (expressionInfo != null && (operatorInfo == null || operatorInfo.type != OperatorType.ATOM && operatorInfo.type != OperatorType.PREFIX)) { return expressionInfo; } return null; } }
false
true
public static void generateExpressionRoot(ExpressionHelper.ExpressionInfo info, ParserGenerator g) { Map<String, List<OperatorInfo>> opCalls = new LinkedHashMap<String, List<OperatorInfo>>(); for (BnfRule rule : info.priorityMap.keySet()) { OperatorInfo operator = info.operatorMap.get(rule); String opCall = g.generateNodeCall(info.rootRule, operator.operator, getNextName(operator.rule.getName(), 0)); List<OperatorInfo> list = opCalls.get(opCall); if (list == null) opCalls.put(opCall, list = new ArrayList<OperatorInfo>(2)); list.add(operator); } Set<String> sortedOpCalls = opCalls.keySet(); for (String s : info.toString().split("\n")) { g.out("// " + s); } // main entry String methodName = info.rootRule.getName(); String kernelMethodName = getNextName(methodName, 0); String frameName = quote(ParserGeneratorUtil.getRuleDisplayName(info.rootRule, true)); g.out("public static boolean " + methodName + "(PsiBuilder builder_, int level_, int priority_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + methodName + "\")) return false;"); g.out("Marker marker_ = builder_.mark();"); g.out("boolean result_ = false;"); g.out("boolean pinned_ = false;"); g.out("enterErrorRecordingSection(builder_, level_, _SECTION_GENERAL_, " + frameName + ");"); boolean first = true; for (String opCall : sortedOpCalls) { OperatorInfo operator = ContainerUtil.getFirstItem(findOperators(opCalls.get(opCall), OperatorType.ATOM, OperatorType.PREFIX)); if (operator == null) continue; String nodeCall = g.generateNodeCall(operator.rule, null, operator.rule.getName()); g.out((first ? "" : "if (!result_) ") + "result_ = " + nodeCall + ";"); first = false; } g.out("pinned_ = result_;"); g.out("result_ = result_ && " + kernelMethodName + "(builder_, level_ + 1, priority_);"); g.out("if (!result_ && !pinned_) {"); g.out("marker_.rollbackTo();"); g.out("}"); g.out("else {"); g.out("marker_.drop();"); g.out("}"); g.out("result_ = exitErrorRecordingSection(builder_, level_, result_, pinned_, _SECTION_GENERAL_, null);"); g.out("return result_ || pinned_;"); g.out("}"); g.newLine(); // kernel g.out("public static boolean " + kernelMethodName + "(PsiBuilder builder_, int level_, int priority_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + kernelMethodName + "\")) return false;"); g.out("boolean result_ = true;"); g.out("while (true) {"); g.out("Marker left_marker_ = (Marker) builder_.getLatestDoneMarker();"); g.out("if (!invalid_left_marker_guard_(builder_, left_marker_, \"" + kernelMethodName + "\")) return false;"); g.out("Marker marker_ = builder_.mark();"); first = true; for (String opCall : sortedOpCalls) { OperatorInfo operator = ContainerUtil.getFirstItem(findOperators(opCalls.get(opCall), OperatorType.BINARY, OperatorType.N_ARY, OperatorType.POSTFIX)); if (operator == null) continue; int priority = info.getPriority(operator.rule); String substCheck = ""; if (operator.substitutor != null) { substCheck = " && ((LighterASTNode)left_marker_).getTokenType() == " + ParserGeneratorUtil.getElementType(operator.substitutor); } g.out((first ? "" : "else ") + "if (priority_ < " + priority + substCheck + " && " + opCall + ") {"); first = false; String elementType = ParserGeneratorUtil.getElementType(operator.rule); boolean rightAssociative = ParserGeneratorUtil.getAttribute(operator.rule, KnownAttribute.RIGHT_ASSOCIATIVE); String tailCall = operator.tail == null ? null : g.generateNodeCall(operator.rule, operator.tail, getNextName(operator.rule.getName(), 1)); if (operator.type == OperatorType.BINARY) { g.out( "result_ = report_error_(builder_, " + methodName + "(builder_, level_, " + (rightAssociative ? priority - 1 : priority) + "));"); if (tailCall != null) g.out("result_ = " + tailCall + " && result_;"); } else if (operator.type == OperatorType.N_ARY) { g.out("while (true) {"); g.out("result_ = report_error_(builder_, " + methodName + "(builder_, level_, " + priority + "));"); if (tailCall != null) g.out("result_ = " + tailCall + " && result_;"); g.out("if (!" + opCall + ") break;"); g.out("}"); } else if (operator.type == OperatorType.POSTFIX) { g.out("result_ = true;"); } g.out("marker_.drop();"); g.out("left_marker_.precede().done(" + elementType + ");"); g.out("}"); } g.out("else {"); g.out("marker_.rollbackTo();"); g.out("break;"); g.out("}"); g.out("}"); g.out("return result_;"); g.out("}"); // operators and tails THashSet<BnfExpression> visited = new THashSet<BnfExpression>(); for (String opCall : sortedOpCalls) { for (OperatorInfo operator : opCalls.get(opCall)) { if (operator.type == OperatorType.ATOM) { g.newLine(); g.generateNode(operator.rule, operator.rule.getExpression(), operator.rule.getName(), visited); continue; } else if (operator.type == OperatorType.PREFIX) { g.newLine(); String operatorFuncName = operator.rule.getName(); g.out("public static boolean " + operatorFuncName + "(PsiBuilder builder_, int level_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + operatorFuncName + "\")) return false;"); g.out("boolean result_ = false;"); g.out("boolean pinned_ = false;"); g.out("Marker marker_ = builder_.mark();"); g.out("enterErrorRecordingSection(builder_, level_, _SECTION_GENERAL_, null);"); String elementType = ParserGeneratorUtil.getElementType(operator.rule); String tailCall = operator.tail == null ? null : g.generateNodeCall(operator.rule, operator.tail, getNextName(operator.rule.getName(), 1)); g.out("result_ = "+opCall+";"); g.out("pinned_ = result_;"); Integer substitutorPriority = operator.substitutor == null ? null : info.getPriority(operator.substitutor); int rulePriority = info.getPriority(operator.rule); int priority = substitutorPriority == null ? (rulePriority == info.nextPriority - 1 ? -1 : rulePriority) : substitutorPriority; g.out("result_ = pinned_ && " + methodName + "(builder_, level_, " + priority + ") && result_;"); if (tailCall != null) { g.out("result_ = pinned_ && report_error_(builder_, " + tailCall + ") && result_;"); } g.out("if (result_ || pinned_) {"); if (StringUtil.isNotEmpty(elementType)) { g.out("marker_.done(" + elementType + ");"); } else { g.out("marker_.drop();"); } g.out("}"); g.out("else {"); g.out("marker_.rollbackTo();"); g.out("}"); g.out("result_ = exitErrorRecordingSection(builder_, level_, result_, pinned_, _SECTION_GENERAL_, null);"); g.out("return result_ || pinned_;"); g.out("}"); } g.generateNodeChild(operator.rule, operator.operator, operator.rule.getName(), 0, visited); if (operator.tail != null) { g.generateNodeChild(operator.rule, operator.tail, operator.rule.getName(), 1, visited); } } } }
public static void generateExpressionRoot(ExpressionHelper.ExpressionInfo info, ParserGenerator g) { Map<String, List<OperatorInfo>> opCalls = new LinkedHashMap<String, List<OperatorInfo>>(); for (BnfRule rule : info.priorityMap.keySet()) { OperatorInfo operator = info.operatorMap.get(rule); String opCall = g.generateNodeCall(info.rootRule, operator.operator, getNextName(operator.rule.getName(), 0)); List<OperatorInfo> list = opCalls.get(opCall); if (list == null) opCalls.put(opCall, list = new ArrayList<OperatorInfo>(2)); list.add(operator); } Set<String> sortedOpCalls = opCalls.keySet(); for (String s : info.toString().split("\n")) { g.out("// " + s); } // main entry String methodName = info.rootRule.getName(); String kernelMethodName = getNextName(methodName, 0); String frameName = quote(ParserGeneratorUtil.getRuleDisplayName(info.rootRule, true)); g.out("public static boolean " + methodName + "(PsiBuilder builder_, int level_, int priority_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + methodName + "\")) return false;"); g.out("Marker marker_ = builder_.mark();"); g.out("boolean result_ = false;"); g.out("boolean pinned_ = false;"); g.out("enterErrorRecordingSection(builder_, level_, _SECTION_GENERAL_, " + frameName + ");"); boolean first = true; for (String opCall : sortedOpCalls) { OperatorInfo operator = ContainerUtil.getFirstItem(findOperators(opCalls.get(opCall), OperatorType.ATOM, OperatorType.PREFIX)); if (operator == null) continue; String nodeCall = g.generateNodeCall(operator.rule, null, operator.rule.getName()); g.out((first ? "" : "if (!result_) ") + "result_ = " + nodeCall + ";"); first = false; } g.out("pinned_ = result_;"); g.out("result_ = result_ && " + kernelMethodName + "(builder_, level_ + 1, priority_);"); g.out("if (!result_ && !pinned_) {"); g.out("marker_.rollbackTo();"); g.out("}"); g.out("else {"); g.out("marker_.drop();"); g.out("}"); g.out("result_ = exitErrorRecordingSection(builder_, level_, result_, pinned_, _SECTION_GENERAL_, null);"); g.out("return result_ || pinned_;"); g.out("}"); g.newLine(); // kernel g.out("public static boolean " + kernelMethodName + "(PsiBuilder builder_, int level_, int priority_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + kernelMethodName + "\")) return false;"); g.out("boolean result_ = true;"); g.out("while (true) {"); g.out("Marker left_marker_ = (Marker) builder_.getLatestDoneMarker();"); g.out("if (!invalid_left_marker_guard_(builder_, left_marker_, \"" + kernelMethodName + "\")) return false;"); first = true; for (String opCall : sortedOpCalls) { OperatorInfo operator = ContainerUtil.getFirstItem(findOperators(opCalls.get(opCall), OperatorType.BINARY, OperatorType.N_ARY, OperatorType.POSTFIX)); if (operator == null) continue; int priority = info.getPriority(operator.rule); String substCheck = ""; if (operator.substitutor != null) { substCheck = " && ((LighterASTNode)left_marker_).getTokenType() == " + ParserGeneratorUtil.getElementType(operator.substitutor); } if (first) g.out("Marker marker_ = builder_.mark();"); g.out((first ? "" : "else ") + "if (priority_ < " + priority + substCheck + " && " + opCall + ") {"); first = false; String elementType = ParserGeneratorUtil.getElementType(operator.rule); boolean rightAssociative = ParserGeneratorUtil.getAttribute(operator.rule, KnownAttribute.RIGHT_ASSOCIATIVE); String tailCall = operator.tail == null ? null : g.generateNodeCall(operator.rule, operator.tail, getNextName(operator.rule.getName(), 1)); if (operator.type == OperatorType.BINARY) { g.out( "result_ = report_error_(builder_, " + methodName + "(builder_, level_, " + (rightAssociative ? priority - 1 : priority) + "));"); if (tailCall != null) g.out("result_ = " + tailCall + " && result_;"); } else if (operator.type == OperatorType.N_ARY) { g.out("while (true) {"); g.out("result_ = report_error_(builder_, " + methodName + "(builder_, level_, " + priority + "));"); if (tailCall != null) g.out("result_ = " + tailCall + " && result_;"); g.out("if (!" + opCall + ") break;"); g.out("}"); } else if (operator.type == OperatorType.POSTFIX) { g.out("result_ = true;"); } g.out("marker_.drop();"); g.out("left_marker_.precede().done(" + elementType + ");"); g.out("}"); } if (first) { g.out("// no BINARY or POSTFIX operators present"); g.out("break;"); } else { g.out("else {"); g.out("marker_.rollbackTo();"); g.out("break;"); g.out("}"); } g.out("}"); g.out("return result_;"); g.out("}"); // operators and tails THashSet<BnfExpression> visited = new THashSet<BnfExpression>(); for (String opCall : sortedOpCalls) { for (OperatorInfo operator : opCalls.get(opCall)) { if (operator.type == OperatorType.ATOM) { g.newLine(); g.generateNode(operator.rule, operator.rule.getExpression(), operator.rule.getName(), visited); continue; } else if (operator.type == OperatorType.PREFIX) { g.newLine(); String operatorFuncName = operator.rule.getName(); g.out("public static boolean " + operatorFuncName + "(PsiBuilder builder_, int level_) {"); g.out("if (!recursion_guard_(builder_, level_, \"" + operatorFuncName + "\")) return false;"); g.out("boolean result_ = false;"); g.out("boolean pinned_ = false;"); g.out("Marker marker_ = builder_.mark();"); g.out("enterErrorRecordingSection(builder_, level_, _SECTION_GENERAL_, null);"); String elementType = ParserGeneratorUtil.getElementType(operator.rule); String tailCall = operator.tail == null ? null : g.generateNodeCall(operator.rule, operator.tail, getNextName(operator.rule.getName(), 1)); g.out("result_ = "+opCall+";"); g.out("pinned_ = result_;"); Integer substitutorPriority = operator.substitutor == null ? null : info.getPriority(operator.substitutor); int rulePriority = info.getPriority(operator.rule); int priority = substitutorPriority == null ? (rulePriority == info.nextPriority - 1 ? -1 : rulePriority) : substitutorPriority; g.out("result_ = pinned_ && " + methodName + "(builder_, level_, " + priority + ") && result_;"); if (tailCall != null) { g.out("result_ = pinned_ && report_error_(builder_, " + tailCall + ") && result_;"); } g.out("if (result_ || pinned_) {"); if (StringUtil.isNotEmpty(elementType)) { g.out("marker_.done(" + elementType + ");"); } else { g.out("marker_.drop();"); } g.out("}"); g.out("else {"); g.out("marker_.rollbackTo();"); g.out("}"); g.out("result_ = exitErrorRecordingSection(builder_, level_, result_, pinned_, _SECTION_GENERAL_, null);"); g.out("return result_ || pinned_;"); g.out("}"); } g.generateNodeChild(operator.rule, operator.operator, operator.rule.getName(), 0, visited); if (operator.tail != null) { g.generateNodeChild(operator.rule, operator.tail, operator.rule.getName(), 1, visited); } } } }
diff --git a/src/CardAssociation/Card.java b/src/CardAssociation/Card.java index 7425180..abbbfe5 100644 --- a/src/CardAssociation/Card.java +++ b/src/CardAssociation/Card.java @@ -1,1070 +1,1070 @@ /** * @file Cardv2.java * @author Jia Chen * @date May 04, 2012 * @description * Cardv2.java is the test instance of Card.java. */ package CardAssociation; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.UUID; import javax.imageio.ImageIO; import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.TransferHandler; public class Card implements Serializable, MouseListener, MouseMotionListener, Comparable<Object>, Transferable { /* * * * * * * * * * * * * serialized versions * */ // private static final long serialVersionUID = 5876059325645604130L; // private static final long serialVersionUID = 5876059325645604131L; private static final long serialVersionUID = 5876059325645604132L; // card properties private String[] sameID; private String id; private String pID; private String cardName; private String cardName_e; private int dupCount = 0; private ArrayList<String> effects; private ArrayList<String> effects_e; private int power; private Trigger trigger; private int level; private int cost; private int soul; private Type t; private CCode c; private String trait1; private String trait2; private String trait1_e; private String trait2_e; private String flavorText; private String flavorText_e; private String realCardName; private ArrayList<Attribute> attributes; private ArrayList<Card> associatedCards; private boolean isAlternateArt; private boolean isEPSign; // game play properties private State currentState; private Zone currentZone; // other properties private String imageResource; private String backResource; private DataFlavor[] flavors; private int MINILEN = 3; private UUID uniqueID; @Override public Object getTransferData(DataFlavor flavor) { if (isDataFlavorSupported(flavor)) { return this; } return null; } @Override public DataFlavor[] getTransferDataFlavors() { return flavors; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return flavors[0].equals(flavor); } public boolean equals(Object o) { Card card = (Card) o; if (card != null) return card.getID().equals(id); else return false; } @Override public int compareTo(Object arg0) { return id.compareTo(((Card) arg0).id); } @Override public void mouseDragged(MouseEvent e) { // customCanvas.repaint(); // customCanvas.setLocation(e.getX(), e.getY()); // System.out.println(cardName + " dragged " + customCanvas.getX() + // ", " // + customCanvas.getY()); } @Override public void mouseMoved(MouseEvent arg0) { } @Override public void mouseClicked(MouseEvent arg0) { System.out.println("Cardv2.java:clicked " + cardName); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { System.out.println("Cardv2.java:pressed cardName = " + cardName); System.out.println("Cardv2.java:pressed name = " + getCardName()); JComponent comp = (JComponent) arg0.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.exportAsDrag(comp, arg0, TransferHandler.COPY); } @Override public void mouseReleased(MouseEvent arg0) { } /* * * * * * * * * * * * * * * * * * * * * Standard Card Information and Image * */ public Card(String id, String name) { sameID = new String[MINILEN]; for (int i = 0; i < sameID.length; i++) { sameID[i] = ""; } setID(id); // setName(id); setCardName(name); realCardName = name; effects = new ArrayList<String>(); effects_e = new ArrayList<String>(); flavorText = ""; flavorText_e = ""; setCurrentState(State.NONE); // imageFile = new File("FieldImages/cardBack-s.jpg"); imageResource = "/resources/FieldImages/cardBack-s.jpg"; backResource = "/resources/FieldImages/cardBack-s.jpg"; setAssociatedCards(new ArrayList<Card>()); setAttributes(new ArrayList<Attribute>()); // addMouseListener(this); } // create a card public Card() { effects = new ArrayList<String>(); effects_e = new ArrayList<String>(); flavorText = ""; flavorText_e = ""; setCurrentState(State.NONE); sameID = new String[MINILEN]; for (int i = 0; i < sameID.length; i++) { sameID[i] = ""; } } public boolean setID(String id) { String newId = id.replace(" ", ""); pID = newId.charAt(0) + ""; for (int i = 1; i < newId.length(); i++) { if ((Character.isLetter(newId.charAt(i)) && Character.isDigit(newId .charAt(i - 1))) || (Character.isSpaceChar(newId.charAt(i)) && Character .isDigit(newId.charAt(i - 1)))) { break; } else { pID += newId.charAt(i); } } boolean isDupCard = false; for (int i = 0; i < sameID.length; i++) { if (sameID[i] == null || sameID[i].isEmpty() || sameID[i].equals(pID)) { if (sameID[i].equals(pID)) { isDupCard = false; } else { isDupCard = true; } sameID[i] = pID; break; } } // this.id = sameID[0]; this.id = pID; this.id = id; return isDupCard; } public JLabel initiateImage() { JLabel imageLabel = new JLabel(); try { Image image = ImageIO.read(getClass().getResourceAsStream( getImageResource())); // Image image = ImageIO.read(new // File("src/FieldImages/cardBack-s.jpg").toURI().toURL()); // Image image = ImageIO.read((imageFile.toURI()).toURL()); // ImageIcon img = new ImageIcon(image); ImageIcon img = new ImageIcon(image.getScaledInstance( (int) (image.getWidth(null) * 0.44), (int) (image.getHeight(null) * 0.44), Image.SCALE_SMOOTH)); imageLabel.setIcon(img); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imageLabel; } // set the card image public void setImageResource(String resPath) { imageResource = resPath; if (resPath.contains("_holo") || resPath.contains("_alt")) { setAlternateArt(true); } if (resPath.contains("_sign")) { setEPSign(true); } // setName(id); } // get the card image public String getImageResource() { // if (isWindows) // return "/" + new File(imageResource).getPath(); // else return imageResource; } public JPanel getInfoPane(int w, int h) { // Font font = new Font("Courier New", Font.BOLD, 12); JPanel infoPanel = new JPanel(); infoPanel.setPreferredSize(new Dimension(w, h)); GroupLayout layout = new GroupLayout(infoPanel); infoPanel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); JTextArea description = new JTextArea(10, 10); if (c == CCode.RED) description.setBackground(Color.PINK); else if (c == CCode.BLUE) description.setBackground(Color.CYAN); else if (c == CCode.YELLOW) description.setBackground(Color.YELLOW); else if (c == CCode.GREEN) description.setBackground(Color.GREEN); // description.setFont(font); description.setLineWrap(true); description.setWrapStyleWord(true); description.setEditable(false); String cardText = ""; if (t == Type.CHARACTER) { if (!getTrait1_j().equals("")) cardText += getTrait1(); if (!getTrait2_j().equals("")) cardText += (!cardText.equals("") ? " | " : "") + getTrait2(); cardText += "\n\n"; } cardText += getEffects() + "\n"; if (!getFlavorText().equals("")) { cardText += "Flavor Text: \n" + getFlavorText(); } description.setText(cardText); description.setCaretPosition(0); JScrollPane descContainer = new JScrollPane(description); JTextField nameLabel = new JTextField(cardName); nameLabel.setEditable(false); // nameLabel.setFont(font); JTextField idLabel = new JTextField(id.replace("_alt", "").replace("_sign", "")); idLabel.setEditable(false); // idLabel.setFont(font); JTextField typeLabel = new JTextField(t.toString()); typeLabel.setEditable(false); // typeLabel.setFont(font); JTextField levelLabel = new JTextField("Level: " + (level >= 0 ? level : " -")); levelLabel.setEditable(false); // levelLabel.setFont(font); JTextField costLabel = new JTextField("Cost: " + (cost >= 0 ? cost : " -")); costLabel.setEditable(false); // costLabel.setFont(font); JTextField soulLabel = new JTextField("Trigger: " + trigger.toString()); soulLabel.setEditable(false); // soulLabel.setFont(font); JTextField powerLabel = new JTextField("Power: " + (power > 0 ? power : " -")); powerLabel.setEditable(false); // powerLabel.setFont(font); JTextField damageLabel = new JTextField("Soul: " + (soul > 0 ? soul : " -")); damageLabel.setEditable(false); // damageLabel.setFont(font); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setHorizontalGroup(layout .createParallelGroup() .addComponent(nameLabel, GroupLayout.PREFERRED_SIZE, 350, GroupLayout.PREFERRED_SIZE) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( idLabel, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( levelLabel, GroupLayout.PREFERRED_SIZE, 60, GroupLayout.PREFERRED_SIZE) .addComponent( costLabel))) .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( typeLabel)) .addGroup( layout.createSequentialGroup() .addComponent( powerLabel, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE))) .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( soulLabel, GroupLayout.PREFERRED_SIZE, - 130, + 125, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( damageLabel)))) .addComponent(descContainer, GroupLayout.PREFERRED_SIZE, 350, GroupLayout.PREFERRED_SIZE)); layout.setVerticalGroup(layout .createSequentialGroup() .addGroup(layout.createParallelGroup().addComponent(nameLabel)) .addGroup( layout.createParallelGroup().addComponent(idLabel) .addComponent(typeLabel) .addComponent(soulLabel)) .addGroup( layout.createParallelGroup().addComponent(levelLabel) .addComponent(costLabel) .addComponent(powerLabel) .addComponent(damageLabel)) .addGroup( layout.createParallelGroup() .addComponent(descContainer))); // System.out.println("getInfoPane"); return infoPanel; } public JPanel displayImage(int w, int h) { JPanel imagePane = new JPanel(); imagePane.setPreferredSize(new Dimension(w, h)); try { // Image image = ImageIO.read((imageFile.toURI()).toURL()); // System.out.println(getImageResource()); Image image = ImageIO.read(getClass().getResourceAsStream( getImageResource())); ImageIcon img = new ImageIcon(image); imagePane.add(new JLabel(img)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imagePane; } // used in Deck.java to check how many copies of the card is there public int getCardCount() { return dupCount; } public String getID() { return id; } // used in Deck.java to increment the number of copies of the card public void addCount() { dupCount++; } public void setCount(int dupCount) { this.dupCount = dupCount; } // set the card name of the card public void setCardName(String name) { this.cardName = name; setUniqueID(UUID.randomUUID()); } // get the card name of the card public String getCardName() { return cardName; } public void setCardName_e(String cardName_e) { this.cardName_e = cardName_e; } public String getCardName_e() { return cardName_e; } // get the card effects public String getEffects() { String result = getEffects_j(); String effectsStr_e = getEffects_e(); if (!effectsStr_e.isEmpty()) { result += "\n" + effectsStr_e; } return result; } public String getEffects_j() { String result = ""; for (int i = 0; i < effects.size(); i++) { result += effects.get(i) + "\n"; } return result; } public String getEffects_e() { String result = ""; for (int i = 0; i < effects_e.size(); i++) { result += effects_e.get(i) + "\n"; } return result; } // set the card effects public void addEffect(String e) { if (!e.isEmpty()) effects.add(e); // TODO: process effects to make attributes } public void addEffect_e(String e) { if (!e.isEmpty()) effects_e.add(e); // TODO: process effects to make attributes } // set the power value of the card public void setPower(int power) { this.power = power; } // get the power value of the card public int getPower() { return power; } // set the soul count of the card public void setSoul(int soul) { this.soul = soul; } // get the soul count of the card public int getSoul() { return soul; } // set the color of the card public void setC(CCode c) { this.c = c; } // get the color of the card public CCode getC() { return c; } // set the first trait of the card public void setTrait1(String trait1) { this.trait1 = trait1; } public String getTrait1() { return getTrait1_j() + " " + getTrait1_e(); } // get the first trait of the card public String getTrait1_j() { return trait1; } // set the second trait of the card public void setTrait2(String trait2) { this.trait2 = trait2; } public String getTrait2() { return getTrait2_j() + " " + getTrait2_e(); } // get the second trait of the card public String getTrait2_j() { return trait2; } public void setTrait1_e(String trait1_e) { this.trait1_e = trait1_e; } public String getTrait1_e() { return trait1_e; } public void setTrait2_e(String trait2_e) { this.trait2_e = trait2_e; } public String getTrait2_e() { return trait2_e; } // set the level of the card public void setLevel(int level) { this.level = level; } // get the level of the card public int getLevel() { return level; } // set the cost of the card public void setCost(int cost) { this.cost = cost; } // get the cost of the card public int getCost() { return cost; } // set the trigger information of the card public void setTrigger(Trigger trigger) { this.trigger = trigger; if (this.trigger == null) this.trigger = Trigger.NONE; } // get the trigger information of the card public Trigger getTrigger() { return trigger; } // get the card type public void setT(Type t) { this.t = t; } // set the card type public Type getT() { return t; } public void resetCount() { dupCount = 0; } // used in Deck.java to decrement the number of copies of the card public void removeCount() { dupCount--; } /** * Check to see if the card meets the requirements given * * @param sId * @param sName * @param sColor * @param sType * @param sLevel * @param sCost * @param sTrigger * @param sPower * @param sSoul * @param sTrait * @param sAbility * @return */ public boolean meetsRequirement(String sId, String sName, CCode sColor, Type sType, int sLevel, int sCost, Trigger sTrigger, int sPower, int sSoul, String sTrait, String sAbility) { boolean isMet = true; if (!id.isEmpty()) { String[] parts = sId.split(" "); for (int i = 0; i < sameID.length; i++) { isMet = true; for (int j = 0; j < parts.length; j++) { isMet = isMet && sameID[i].toLowerCase().contains( parts[j].toLowerCase()); /* * if (sameID[i].toLowerCase() * .contains(parts[j].toLowerCase())) * System.out.println(sameID[i] + "???" + parts[j]); */ } if (isMet) { break; } } isMet = true; for (int j = 0; j < parts.length; j++) { isMet = isMet && id.toLowerCase().contains(parts[j].toLowerCase()); /* * if (id.toLowerCase().contains(parts[j].toLowerCase())) * System.out.println(id + "::CONTAINS::" + parts[j]); */ } /* * if (isMet) { for (int i = 0; i < sameID.length; i++) { * System.out.print("[(" + i + ")" + sameID[i] + "]"); } * System.out.println(); } */ } if (!sName.isEmpty()) { isMet = isMet && (cardName.toLowerCase().contains(sName.toLowerCase()) || cardName_e .toLowerCase().contains(sName.toLowerCase())); } if (sColor != null && sColor != CCode.ALL) { isMet = isMet && (sColor == c); } if (sType != null && sType != CardAssociation.Type.ALL) { isMet = isMet && (sType == t); } if (sLevel > -1) { isMet = isMet && (sLevel == level); } if (sCost > -1) { isMet = isMet && (sCost == cost); } if (sTrigger != null && sTrigger != Trigger.ALL) { isMet = isMet && (sTrigger == trigger); } if (sPower > -1) { isMet = isMet && (sPower == power); } if (sSoul > -1) { isMet = isMet && (sSoul == soul); } if (!sTrait.isEmpty()) { isMet = isMet && (trait1.toLowerCase().contains(sTrait) || trait2.toLowerCase().contains(sTrait) || trait1_e.toLowerCase().contains(sTrait) || trait2_e .toLowerCase().contains(sTrait)); } if (!sAbility.isEmpty()) { String[] parts = sAbility.split(" "); for (int i = 0; i < parts.length; i++) { isMet = isMet && (getEffects().toLowerCase().contains( parts[i].toLowerCase()) || getEffects_e() .toLowerCase().contains(parts[i].toLowerCase())); } } return isMet; } public void setFlavorText(String flavorText) { this.flavorText = flavorText; } public String getFlavorText() { return getFlavorText_j() + " " + getFlavorText_e(); } public String getFlavorText_j() { return flavorText; } public void setFlavorText_e(String flavorText_e) { this.flavorText_e = flavorText_e; } public String getFlavorText_e() { return flavorText_e; } public void setRealName(String name) { realCardName = name; } public String getRealName() { return realCardName; } public Card clone() { Card cloned = new Card(id, cardName); cloned.setCount(dupCount); cloned.setEffects(effects); cloned.setEffects_e(effects_e); cloned.setPower(power); cloned.setTrigger(trigger); cloned.setLevel(level); cloned.setCost(cost); cloned.setSoul(soul); cloned.setT(t); cloned.setC(c); cloned.setTrait1(trait1); cloned.setTrait1_e(trait1_e); cloned.setTrait2(trait2); cloned.setTrait2_e(trait2_e); cloned.setFlavorText(flavorText); cloned.setFlavorText_e(flavorText_e); cloned.setImageResource(imageResource); return cloned; } private void setEffects(ArrayList<String> effects) { this.effects = effects; } private void setEffects_e(ArrayList<String> effects_e) { this.effects_e = effects_e; } /* * * * * * * * * * * * * * * * * * * * * * * Game Play Property Setting and Creation * */ // private Rectangle cardBound; Canvas customCanvas = null; public Zone getCurrentZone() { return currentZone; } public void setCurrentZone(Zone currentZone) { this.currentZone = currentZone; } // used in Game.java to set the current state of the card public void setCurrentState(State currentState) { this.currentState = currentState; } // used in Game.java to get the current state of the card public State getCurrentState() { return currentState; } public Rectangle getCardBound() { Rectangle boundBox = new Rectangle(); boundBox.setBounds((int) customCanvas.getLocation().x, (int) (customCanvas.getLocation().y + Game.Game.translatedY), customCanvas.getWidth(), customCanvas.getHeight()); return boundBox; } public Image getCardImage() throws MalformedURLException, IOException { return ImageIO.read(getClass().getResourceAsStream(getImageResource())); } public Canvas toCanvas() { if (customCanvas == null) { customCanvas = new Canvas() { private static final long serialVersionUID = 932367309486409810L; public void paint(Graphics g) { Image after; try { // img = ImageIO.read((imageFile.toURI()).toURL()); BufferedImage before = ImageIO.read(getClass() .getResourceAsStream(getImageResource())); if (currentState == State.FD_REST || currentState == State.FD_STAND) { before = ImageIO.read(getClass() .getResourceAsStream(backResource)); } /* * BufferedImage before = * ImageIO.read((imageFile.toURI()) .toURL()); */ int wid = before.getWidth(); int hit = before.getHeight(); after = new BufferedImage(wid, hit, BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(Game.Game.gameScale, Game.Game.gameScale); if (currentState == State.REST || currentState == State.FD_REST) { at.translate((after.getHeight(null) - before .getWidth(null)) / 2, (after.getWidth(null) - before .getHeight(null)) / 2); if (getT() == Type.CLIMAX && currentState == State.REST) { at.rotate(Math.toRadians(-90), before.getWidth(null) / 2, before.getHeight(null) / 2); } else { at.rotate(Math.toRadians(90), before.getWidth(null) / 2, before.getHeight(null) / 2); } } else if (currentState == State.REVERSE) { at.rotate(Math.toRadians(180), before.getWidth(null) / 2, before.getHeight(null) / 2); } AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); after = scaleOp.filter(before, null); // prepareImage(img, null); g.drawImage(after, getLocation().x, getLocation().y, null); customCanvas.setBounds(getLocation().x, getLocation().y, (int) (after.getWidth(null)), (int) (after.getHeight(null))); boolean debug = false; String outputString = (int) getCardBound().getX() + " + " + getCardBound().width + "," + (int) getCardBound().getY() + " + " + getCardBound().height; if (debug) { g.setColor(Color.BLUE); g.fillRect((int) getCardBound().getX(), (int) getCardBound().getY(), getCardBound().width, getCardBound().height); g.setColor(Color.RED); g.drawRect((int) getCardBound().getX(), (int) getCardBound().getY(), getCardBound().width, getCardBound().height); g.setColor(Color.BLACK); g.drawString(outputString, (int) getCardBound() .getX(), (int) getCardBound().getY()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void update(Graphics g) { paint(g); } }; } return customCanvas; } public void setDisplay(boolean isFaceUp, boolean isTapped) { // if(isFaceUp && isTapped) // currentState = State.REST; // else if(isFaceUp && !isTapped) // currentState = State.STAND; // else if(!isFaceUp && isTapped) // currentState = State.FD_REST; // else // currentState = State.FD_STAND; } // Hard code special cases where you may put >4 cards in the deck // FZ/SE13-24 C // FZ/SE13-26 C // MF/S13-034 U // MF/S13-040 C // ID/W10-014 C // SG/W19-038 C // FT/SE10-29 public static int getMaxInDeck(Card c) { if (c.getID().equals("FZ/SE13-24 C") || c.getID().equals("FZ/SE13-26 C") || c.getID().equals("MF/S13-034 U") || c.getID().equals("MF/S13-040 C") || c.getID().equals("ID/W10-014 C") || c.getID().equals("SG/W19-038 C")) return 50; else if (c.getID().contains("FT/SE10-29")) return 6; else return 4; } public String toString() { return cardName; } public void setAlternateArt(boolean isAlternateArt) { this.isAlternateArt = isAlternateArt; } public boolean isAlternateArt() { return isAlternateArt; } public boolean isEPSign() { return isEPSign; } public void setEPSign(boolean isEPSign) { this.isEPSign = isEPSign; } public ArrayList<Attribute> getAttributes() { return attributes; } public void setAttributes(ArrayList<Attribute> attributes) { this.attributes = attributes; } public ArrayList<Card> getAssociatedCards() { return associatedCards; } public void setAssociatedCards(ArrayList<Card> associatedCards) { this.associatedCards = associatedCards; } public UUID getUniqueID() { return uniqueID; } public void setUniqueID(UUID uniqueID) { this.uniqueID = uniqueID; } }
true
true
public JPanel getInfoPane(int w, int h) { // Font font = new Font("Courier New", Font.BOLD, 12); JPanel infoPanel = new JPanel(); infoPanel.setPreferredSize(new Dimension(w, h)); GroupLayout layout = new GroupLayout(infoPanel); infoPanel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); JTextArea description = new JTextArea(10, 10); if (c == CCode.RED) description.setBackground(Color.PINK); else if (c == CCode.BLUE) description.setBackground(Color.CYAN); else if (c == CCode.YELLOW) description.setBackground(Color.YELLOW); else if (c == CCode.GREEN) description.setBackground(Color.GREEN); // description.setFont(font); description.setLineWrap(true); description.setWrapStyleWord(true); description.setEditable(false); String cardText = ""; if (t == Type.CHARACTER) { if (!getTrait1_j().equals("")) cardText += getTrait1(); if (!getTrait2_j().equals("")) cardText += (!cardText.equals("") ? " | " : "") + getTrait2(); cardText += "\n\n"; } cardText += getEffects() + "\n"; if (!getFlavorText().equals("")) { cardText += "Flavor Text: \n" + getFlavorText(); } description.setText(cardText); description.setCaretPosition(0); JScrollPane descContainer = new JScrollPane(description); JTextField nameLabel = new JTextField(cardName); nameLabel.setEditable(false); // nameLabel.setFont(font); JTextField idLabel = new JTextField(id.replace("_alt", "").replace("_sign", "")); idLabel.setEditable(false); // idLabel.setFont(font); JTextField typeLabel = new JTextField(t.toString()); typeLabel.setEditable(false); // typeLabel.setFont(font); JTextField levelLabel = new JTextField("Level: " + (level >= 0 ? level : " -")); levelLabel.setEditable(false); // levelLabel.setFont(font); JTextField costLabel = new JTextField("Cost: " + (cost >= 0 ? cost : " -")); costLabel.setEditable(false); // costLabel.setFont(font); JTextField soulLabel = new JTextField("Trigger: " + trigger.toString()); soulLabel.setEditable(false); // soulLabel.setFont(font); JTextField powerLabel = new JTextField("Power: " + (power > 0 ? power : " -")); powerLabel.setEditable(false); // powerLabel.setFont(font); JTextField damageLabel = new JTextField("Soul: " + (soul > 0 ? soul : " -")); damageLabel.setEditable(false); // damageLabel.setFont(font); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setHorizontalGroup(layout .createParallelGroup() .addComponent(nameLabel, GroupLayout.PREFERRED_SIZE, 350, GroupLayout.PREFERRED_SIZE) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( idLabel, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( levelLabel, GroupLayout.PREFERRED_SIZE, 60, GroupLayout.PREFERRED_SIZE) .addComponent( costLabel))) .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( typeLabel)) .addGroup( layout.createSequentialGroup() .addComponent( powerLabel, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE))) .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( soulLabel, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( damageLabel)))) .addComponent(descContainer, GroupLayout.PREFERRED_SIZE, 350, GroupLayout.PREFERRED_SIZE)); layout.setVerticalGroup(layout .createSequentialGroup() .addGroup(layout.createParallelGroup().addComponent(nameLabel)) .addGroup( layout.createParallelGroup().addComponent(idLabel) .addComponent(typeLabel) .addComponent(soulLabel)) .addGroup( layout.createParallelGroup().addComponent(levelLabel) .addComponent(costLabel) .addComponent(powerLabel) .addComponent(damageLabel)) .addGroup( layout.createParallelGroup() .addComponent(descContainer))); // System.out.println("getInfoPane"); return infoPanel; }
public JPanel getInfoPane(int w, int h) { // Font font = new Font("Courier New", Font.BOLD, 12); JPanel infoPanel = new JPanel(); infoPanel.setPreferredSize(new Dimension(w, h)); GroupLayout layout = new GroupLayout(infoPanel); infoPanel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); JTextArea description = new JTextArea(10, 10); if (c == CCode.RED) description.setBackground(Color.PINK); else if (c == CCode.BLUE) description.setBackground(Color.CYAN); else if (c == CCode.YELLOW) description.setBackground(Color.YELLOW); else if (c == CCode.GREEN) description.setBackground(Color.GREEN); // description.setFont(font); description.setLineWrap(true); description.setWrapStyleWord(true); description.setEditable(false); String cardText = ""; if (t == Type.CHARACTER) { if (!getTrait1_j().equals("")) cardText += getTrait1(); if (!getTrait2_j().equals("")) cardText += (!cardText.equals("") ? " | " : "") + getTrait2(); cardText += "\n\n"; } cardText += getEffects() + "\n"; if (!getFlavorText().equals("")) { cardText += "Flavor Text: \n" + getFlavorText(); } description.setText(cardText); description.setCaretPosition(0); JScrollPane descContainer = new JScrollPane(description); JTextField nameLabel = new JTextField(cardName); nameLabel.setEditable(false); // nameLabel.setFont(font); JTextField idLabel = new JTextField(id.replace("_alt", "").replace("_sign", "")); idLabel.setEditable(false); // idLabel.setFont(font); JTextField typeLabel = new JTextField(t.toString()); typeLabel.setEditable(false); // typeLabel.setFont(font); JTextField levelLabel = new JTextField("Level: " + (level >= 0 ? level : " -")); levelLabel.setEditable(false); // levelLabel.setFont(font); JTextField costLabel = new JTextField("Cost: " + (cost >= 0 ? cost : " -")); costLabel.setEditable(false); // costLabel.setFont(font); JTextField soulLabel = new JTextField("Trigger: " + trigger.toString()); soulLabel.setEditable(false); // soulLabel.setFont(font); JTextField powerLabel = new JTextField("Power: " + (power > 0 ? power : " -")); powerLabel.setEditable(false); // powerLabel.setFont(font); JTextField damageLabel = new JTextField("Soul: " + (soul > 0 ? soul : " -")); damageLabel.setEditable(false); // damageLabel.setFont(font); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setHorizontalGroup(layout .createParallelGroup() .addComponent(nameLabel, GroupLayout.PREFERRED_SIZE, 350, GroupLayout.PREFERRED_SIZE) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( idLabel, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( levelLabel, GroupLayout.PREFERRED_SIZE, 60, GroupLayout.PREFERRED_SIZE) .addComponent( costLabel))) .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( typeLabel)) .addGroup( layout.createSequentialGroup() .addComponent( powerLabel, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE))) .addGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent( soulLabel, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)) .addGroup( layout.createSequentialGroup() .addComponent( damageLabel)))) .addComponent(descContainer, GroupLayout.PREFERRED_SIZE, 350, GroupLayout.PREFERRED_SIZE)); layout.setVerticalGroup(layout .createSequentialGroup() .addGroup(layout.createParallelGroup().addComponent(nameLabel)) .addGroup( layout.createParallelGroup().addComponent(idLabel) .addComponent(typeLabel) .addComponent(soulLabel)) .addGroup( layout.createParallelGroup().addComponent(levelLabel) .addComponent(costLabel) .addComponent(powerLabel) .addComponent(damageLabel)) .addGroup( layout.createParallelGroup() .addComponent(descContainer))); // System.out.println("getInfoPane"); return infoPanel; }
diff --git a/src/main/java/water/api/Jobs.java b/src/main/java/water/api/Jobs.java index eea903311..67f58e46a 100644 --- a/src/main/java/water/api/Jobs.java +++ b/src/main/java/water/api/Jobs.java @@ -1,181 +1,181 @@ package water.api; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import water.DKV; import water.Job; import water.Job.JobState; import water.Key; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.ParseException; import java.util.Date; public class Jobs extends Request { Jobs() { } public static Response redirect(JsonObject resp, Key dest) { JsonObject redir = new JsonObject(); redir.addProperty(KEY, dest.toString()); return Response.redirect(resp, Jobs.class, redir); } @Override protected Response serve() { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); Job[] jobs = Job.all(); for( int i = jobs.length - 1; i >= 0; i-- ) { JsonObject json = new JsonObject(); json.addProperty(KEY, jobs[i].self().toString()); json.addProperty(DESCRIPTION, jobs[i].description); json.addProperty(DEST_KEY, jobs[i].dest() != null ? jobs[i].dest().toString() : ""); json.addProperty(START_TIME, RequestBuilders.ISO8601.get().format(new Date(jobs[i].start_time))); long end = jobs[i].end_time; JsonObject jobResult = new JsonObject(); Job job = jobs[i]; boolean cancelled; if (cancelled = (job.state==JobState.CANCELLED || job.state==JobState.CRASHED)) { if(job.exception != null){ jobResult.addProperty("exception", "1"); jobResult.addProperty("val", jobs[i].exception); } else { jobResult.addProperty("val", "CANCELLED"); } } else if (job.state==JobState.DONE) jobResult.addProperty("val", "OK"); json.addProperty(END_TIME, end == 0 ? "" : RequestBuilders.ISO8601.get().format(new Date(end))); json.addProperty(PROGRESS, job.state==JobState.RUNNING || job.state==JobState.DONE ? jobs[i].progress() : -1); json.addProperty(PROGRESS, end == 0 ? (cancelled ? -2 : jobs[i].progress()) : (cancelled ? -2 : -1)); json.addProperty(CANCELLED, cancelled); json.add("result",jobResult); array.add(json); } result.add(JOBS, array); Response r = Response.done(result); r.setBuilder(JOBS, new ArrayBuilder() { @Override public String caption(JsonArray array, String name) { return ""; } }); r.setBuilder(JOBS + "." + KEY, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String html; if( !Job.isRunning(Key.make(elm.getAsString())) ) html = "<button disabled class='btn btn-mini'>X</button>"; else { String keyParam = KEY + "=" + elm.getAsString(); - html = "<a href='Cancel.html?" + keyParam + "'><button class='btn btn-danger btn-mini'>X</button></a>"; + html = "<a href='/Cancel.html?" + keyParam + "'><button class='btn btn-danger btn-mini'>X</button></a>"; } return html; } }); r.setBuilder(JOBS + "." + DEST_KEY, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String str = elm.getAsString(); String key = null; try { key = URLEncoder.encode(str,"UTF-8"); } catch( UnsupportedEncodingException e ) { key = str; } - return ("".equals(key) || DKV.get(Key.make(str)) == null) ? key : "<a href='Inspect.html?"+KEY+"="+key+"'>"+str+"</a>"; + return ("".equals(key) || DKV.get(Key.make(str)) == null) ? key : "<a href='/Inspect.html?"+KEY+"="+key+"'>"+str+"</a>"; } }); r.setBuilder(JOBS + "." + START_TIME, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return date(elm.toString()); } }); r.setBuilder(JOBS + "." + END_TIME, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return date(elm.toString()); } }); r.setBuilder(JOBS + "." + PROGRESS, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return progress(Float.parseFloat(elm.getAsString())); } }); r.setBuilder(JOBS + "." + "result", new ElementBuilder() { @Override public String objectToString(JsonObject obj, String contextName) { if(obj.has("exception")){ String rid = Key.make().toString(); String ex = obj.get("val").getAsString().replace("'", ""); String [] lines = ex.split("\n"); StringBuilder sb = new StringBuilder(lines[0]); for(int i = 1; i < lines.length; ++i){ sb.append("\\n" + lines[i]); } // ex = ex.substring(0,ex.indexOf('\n')); ex = sb.toString(); String res = "\n<a onClick=\"" + "var showhide=document.getElementById('" + rid + "');" + "if(showhide.innerHTML == '') showhide.innerHTML = '<pre>" + ex + "</pre>';" + "else showhide.innerHTML = '';" + "\">FAILED</a>\n<div id='"+ rid +"'></div>\n"; return res; } else if(obj.has("val")){ return obj.get("val").getAsString(); } return ""; } @Override public String build(String elementContents, String elementName) { return "<td>" + elementContents + "</td>"; } }); return r; } private static String date(String utc) { if( utc == null || utc.length() == 0 ) return ""; utc = utc.replaceAll("^\"|\"$",""); if( utc.length() == 0 ) return ""; long ms; try { ms = RequestBuilders.ISO8601.get().parse(utc).getTime(); } catch( ParseException e ) { throw new RuntimeException(e); } return "<script>document.write(new Date(" + ms + ").toLocaleTimeString())</script>"; } private static String progress(float value) { int pct = (int) (value * 100); String type = "progress-stripped active"; if (pct==-100) { // task is done pct = 100; type = "progress-success"; } else if (pct==-200) { pct = 100; type = "progress-warning"; } // @formatter:off return "" + "<div style='margin-bottom:0px;padding-bottom:0xp;margin-top:8px;height:5px;width:180px' class='progress "+type+"'>" // + "<div class='bar' style='width:" + pct + "%;'>" // + "</div>" // + "</div>"; // @formatter:on } @Override public RequestServer.API_VERSION[] supportedVersions() { return SUPPORTS_V1_V2; } }
false
true
protected Response serve() { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); Job[] jobs = Job.all(); for( int i = jobs.length - 1; i >= 0; i-- ) { JsonObject json = new JsonObject(); json.addProperty(KEY, jobs[i].self().toString()); json.addProperty(DESCRIPTION, jobs[i].description); json.addProperty(DEST_KEY, jobs[i].dest() != null ? jobs[i].dest().toString() : ""); json.addProperty(START_TIME, RequestBuilders.ISO8601.get().format(new Date(jobs[i].start_time))); long end = jobs[i].end_time; JsonObject jobResult = new JsonObject(); Job job = jobs[i]; boolean cancelled; if (cancelled = (job.state==JobState.CANCELLED || job.state==JobState.CRASHED)) { if(job.exception != null){ jobResult.addProperty("exception", "1"); jobResult.addProperty("val", jobs[i].exception); } else { jobResult.addProperty("val", "CANCELLED"); } } else if (job.state==JobState.DONE) jobResult.addProperty("val", "OK"); json.addProperty(END_TIME, end == 0 ? "" : RequestBuilders.ISO8601.get().format(new Date(end))); json.addProperty(PROGRESS, job.state==JobState.RUNNING || job.state==JobState.DONE ? jobs[i].progress() : -1); json.addProperty(PROGRESS, end == 0 ? (cancelled ? -2 : jobs[i].progress()) : (cancelled ? -2 : -1)); json.addProperty(CANCELLED, cancelled); json.add("result",jobResult); array.add(json); } result.add(JOBS, array); Response r = Response.done(result); r.setBuilder(JOBS, new ArrayBuilder() { @Override public String caption(JsonArray array, String name) { return ""; } }); r.setBuilder(JOBS + "." + KEY, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String html; if( !Job.isRunning(Key.make(elm.getAsString())) ) html = "<button disabled class='btn btn-mini'>X</button>"; else { String keyParam = KEY + "=" + elm.getAsString(); html = "<a href='Cancel.html?" + keyParam + "'><button class='btn btn-danger btn-mini'>X</button></a>"; } return html; } }); r.setBuilder(JOBS + "." + DEST_KEY, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String str = elm.getAsString(); String key = null; try { key = URLEncoder.encode(str,"UTF-8"); } catch( UnsupportedEncodingException e ) { key = str; } return ("".equals(key) || DKV.get(Key.make(str)) == null) ? key : "<a href='Inspect.html?"+KEY+"="+key+"'>"+str+"</a>"; } }); r.setBuilder(JOBS + "." + START_TIME, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return date(elm.toString()); } }); r.setBuilder(JOBS + "." + END_TIME, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return date(elm.toString()); } }); r.setBuilder(JOBS + "." + PROGRESS, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return progress(Float.parseFloat(elm.getAsString())); } }); r.setBuilder(JOBS + "." + "result", new ElementBuilder() { @Override public String objectToString(JsonObject obj, String contextName) { if(obj.has("exception")){ String rid = Key.make().toString(); String ex = obj.get("val").getAsString().replace("'", ""); String [] lines = ex.split("\n"); StringBuilder sb = new StringBuilder(lines[0]); for(int i = 1; i < lines.length; ++i){ sb.append("\\n" + lines[i]); } // ex = ex.substring(0,ex.indexOf('\n')); ex = sb.toString(); String res = "\n<a onClick=\"" + "var showhide=document.getElementById('" + rid + "');" + "if(showhide.innerHTML == '') showhide.innerHTML = '<pre>" + ex + "</pre>';" + "else showhide.innerHTML = '';" + "\">FAILED</a>\n<div id='"+ rid +"'></div>\n"; return res; } else if(obj.has("val")){ return obj.get("val").getAsString(); } return ""; } @Override public String build(String elementContents, String elementName) { return "<td>" + elementContents + "</td>"; } }); return r; }
protected Response serve() { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); Job[] jobs = Job.all(); for( int i = jobs.length - 1; i >= 0; i-- ) { JsonObject json = new JsonObject(); json.addProperty(KEY, jobs[i].self().toString()); json.addProperty(DESCRIPTION, jobs[i].description); json.addProperty(DEST_KEY, jobs[i].dest() != null ? jobs[i].dest().toString() : ""); json.addProperty(START_TIME, RequestBuilders.ISO8601.get().format(new Date(jobs[i].start_time))); long end = jobs[i].end_time; JsonObject jobResult = new JsonObject(); Job job = jobs[i]; boolean cancelled; if (cancelled = (job.state==JobState.CANCELLED || job.state==JobState.CRASHED)) { if(job.exception != null){ jobResult.addProperty("exception", "1"); jobResult.addProperty("val", jobs[i].exception); } else { jobResult.addProperty("val", "CANCELLED"); } } else if (job.state==JobState.DONE) jobResult.addProperty("val", "OK"); json.addProperty(END_TIME, end == 0 ? "" : RequestBuilders.ISO8601.get().format(new Date(end))); json.addProperty(PROGRESS, job.state==JobState.RUNNING || job.state==JobState.DONE ? jobs[i].progress() : -1); json.addProperty(PROGRESS, end == 0 ? (cancelled ? -2 : jobs[i].progress()) : (cancelled ? -2 : -1)); json.addProperty(CANCELLED, cancelled); json.add("result",jobResult); array.add(json); } result.add(JOBS, array); Response r = Response.done(result); r.setBuilder(JOBS, new ArrayBuilder() { @Override public String caption(JsonArray array, String name) { return ""; } }); r.setBuilder(JOBS + "." + KEY, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String html; if( !Job.isRunning(Key.make(elm.getAsString())) ) html = "<button disabled class='btn btn-mini'>X</button>"; else { String keyParam = KEY + "=" + elm.getAsString(); html = "<a href='/Cancel.html?" + keyParam + "'><button class='btn btn-danger btn-mini'>X</button></a>"; } return html; } }); r.setBuilder(JOBS + "." + DEST_KEY, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String str = elm.getAsString(); String key = null; try { key = URLEncoder.encode(str,"UTF-8"); } catch( UnsupportedEncodingException e ) { key = str; } return ("".equals(key) || DKV.get(Key.make(str)) == null) ? key : "<a href='/Inspect.html?"+KEY+"="+key+"'>"+str+"</a>"; } }); r.setBuilder(JOBS + "." + START_TIME, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return date(elm.toString()); } }); r.setBuilder(JOBS + "." + END_TIME, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return date(elm.toString()); } }); r.setBuilder(JOBS + "." + PROGRESS, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { return progress(Float.parseFloat(elm.getAsString())); } }); r.setBuilder(JOBS + "." + "result", new ElementBuilder() { @Override public String objectToString(JsonObject obj, String contextName) { if(obj.has("exception")){ String rid = Key.make().toString(); String ex = obj.get("val").getAsString().replace("'", ""); String [] lines = ex.split("\n"); StringBuilder sb = new StringBuilder(lines[0]); for(int i = 1; i < lines.length; ++i){ sb.append("\\n" + lines[i]); } // ex = ex.substring(0,ex.indexOf('\n')); ex = sb.toString(); String res = "\n<a onClick=\"" + "var showhide=document.getElementById('" + rid + "');" + "if(showhide.innerHTML == '') showhide.innerHTML = '<pre>" + ex + "</pre>';" + "else showhide.innerHTML = '';" + "\">FAILED</a>\n<div id='"+ rid +"'></div>\n"; return res; } else if(obj.has("val")){ return obj.get("val").getAsString(); } return ""; } @Override public String build(String elementContents, String elementName) { return "<td>" + elementContents + "</td>"; } }); return r; }
diff --git a/src/com/ferg/awful/thread/AwfulPost.java b/src/com/ferg/awful/thread/AwfulPost.java index e8ecb075..7d3a5661 100644 --- a/src/com/ferg/awful/thread/AwfulPost.java +++ b/src/com/ferg/awful/thread/AwfulPost.java @@ -1,338 +1,338 @@ /******************************************************************************** * Copyright (c) 2011, Scott Ferguson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the software nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY SCOTT FERGUSON ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SCOTT FERGUSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package com.ferg.awful.thread; import java.util.ArrayList; import java.util.regex.Pattern; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.SimpleHtmlSerializer; import org.htmlcleaner.TagNode; import org.htmlcleaner.XPatherException; import android.util.Log; import com.ferg.awful.constants.Constants; import com.ferg.awful.network.NetworkUtils; public class AwfulPost { private static final String TAG = "AwfulPost"; /*private static final String USERNAME_SEARCH = "//dt[@class='author']|//dt[@class='author op']|//dt[@class='author role-mod']|//dt[@class='author role-admin']|//dt[@class='author role-mod op']|//dt[@class='author role-admin op']"; private static final String MOD_SEARCH = "//dt[@class='author role-mod']|//dt[@class='author role-mod op']"; private static final String ADMIN_SEARCH = "//dt[@class='author role-admin']|//dt[@class='author role-admin op']"; private static final String USERNAME = "//dt[@class='author']"; private static final String OP = "//dt[@class='author op']"; private static final String MOD = "//dt[@class='author role-mod']"; private static final String ADMIN = "//dt[@class='author role-admin']"; private static final String POST = "//table[@class='post']"; private static final String POST_ID = "//table[@class='post']"; private static final String POST_DATE = "//td[@class='postdate']"; private static final String SEEN_LINK = "//td[@class='postdate']//a"; private static final String AVATAR = "//dd[@class='title']//img"; private static final String EDITED = "//p[@class='editedby']/span"; private static final String POSTBODY = "//td[@class='postbody']"; private static final String SEEN1 = "//tr[@class='seen1']"; private static final String SEEN2 = "//tr[@class='seen2']"; private static final String SEEN = SEEN1+"|"+SEEN2; private static final String USERINFO = "//tr[position()=1]/td[position()=1]"; //this would be nicer if HtmlCleaner supported starts-with private static final String PROFILE_LINKS = "//ul[@class='profilelinks']//a"; private static final String EDITABLE = "//img[@alt='Edit']"; */ private static final Pattern fixNewline = Pattern.compile("[\\n\\r\\f\\a\\e]"); private static final String USERINFO_PREFIX = "userinfo userid-"; private static final String ELEMENT_POSTBODY = "<td class=\"postbody\">"; private static final String ELEMENT_END_TD = "</td>"; private static final String REPLACEMENT_POSTBODY = "<div class=\"postbody\">"; private static final String REPLACEMENT_END_TD = "</div>"; private static final String LINK_PROFILE = "Profile"; private static final String LINK_MESSAGE = "Message"; private static final String LINK_POST_HISTORY = "Post History"; private static final String LINK_RAP_SHEET = "Rap Sheet"; private String mId; private String mDate; private String mUserId; private String mUsername; private String mAvatar; private String mContent; private String mEdited; private boolean mLastRead = false; private boolean mPreviouslyRead = false; private boolean mEven = false; private boolean mHasProfileLink = false; private boolean mHasMessageLink = false; private boolean mHasPostHistoryLink = false; private boolean mHasRapSheetLink = false; private String mLastReadUrl; private boolean mEditable; public String getId() { return mId; } public void setId(String aId) { mId = aId; } public String getDate() { return mDate; } public void setDate(String aDate) { mDate = aDate; } public String getUserId() { return mUserId; } public void setUserId(String aUserId) { mUserId = aUserId; } public String getUsername() { return mUsername; } public void setUsername(String aUsername) { mUsername = aUsername; } public String getAvatar() { return mAvatar; } public void setAvatar(String aAvatar) { mAvatar = aAvatar; } public String getContent() { return mContent; } public void setContent(String aContent) { mContent = aContent; } public String getEdited() { return mEdited; } public void setEdited(String aEdited) { mEdited = aEdited; } public String getLastReadUrl() { return mLastReadUrl; } public void setLastReadUrl(String aLastReadUrl) { mLastReadUrl = aLastReadUrl; } public boolean isLastRead() { return mLastRead; } public void setLastRead(boolean aLastRead) { mLastRead = aLastRead; } public boolean isPreviouslyRead() { return mPreviouslyRead; } public void setPreviouslyRead(boolean aPreviouslyRead) { mPreviouslyRead = aPreviouslyRead; } public void setEven(boolean mEven) { this.mEven = mEven; } public boolean isEven() { return mEven; } public void setHasProfileLink(boolean aHasProfileLink) { mHasProfileLink = aHasProfileLink; } public boolean hasProfileLink() { return mHasProfileLink; } public void setHasMessageLink(boolean aHasMessageLink) { mHasMessageLink = aHasMessageLink; } public boolean hasMessageLink() { return mHasMessageLink; } public void setHasPostHistoryLink(boolean aHasPostHistoryLink) { mHasPostHistoryLink = aHasPostHistoryLink; } public boolean hasPostHistoryLink() { return mHasPostHistoryLink; } public void setHasRapSheetLink(boolean aHasRapSheetLink) { mHasRapSheetLink = aHasRapSheetLink; } public boolean isEditable() { return mEditable; } public void setEditable(boolean aEditable) { mEditable = aEditable; } public boolean hasRapSheetLink() { return mHasRapSheetLink; } public ArrayList<AwfulPost> markLastRead() { ArrayList<AwfulPost> result = new ArrayList<AwfulPost>(); try { TagNode response = NetworkUtils.get(Constants.BASE_URL + mLastReadUrl); result = parsePosts(response); } catch (Exception e) { e.printStackTrace(); } return result; } public static ArrayList<AwfulPost> parsePosts(TagNode aThread) { ArrayList<AwfulPost> result = new ArrayList<AwfulPost>(); HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties properties = cleaner.getProperties(); properties.setOmitComments(true); SimpleHtmlSerializer serializer = new SimpleHtmlSerializer(cleaner.getProperties()); boolean lastReadFound = false; boolean even = false; try { TagNode[] postNodes = aThread.getElementsByAttValue("class", "post", true, true); for (TagNode node : postNodes) { AwfulPost post = new AwfulPost(); // We'll just reuse the array of objects rather than create // a ton of them String id = node.getAttributeByName("id"); post.setId(id.replaceAll("post", "")); TagNode[] postContent = node.getElementsHavingAttribute("class", true); for(TagNode pc : postContent){ if(pc.getAttributeByName("class").contains("author")){ post.setUsername(pc.getText().toString().trim()); } - if(pc.getAttributeByName("class").equalsIgnoreCase("title") && pc.getChildTags().length >0){ - post.setAvatar(pc.getChildTags()[0].getAttributeByName("src")); + if(pc.getAttributeByName("class").equalsIgnoreCase("img")){ + post.setAvatar(pc.getAttributeByName("src")); } if(pc.getAttributeByName("class").equalsIgnoreCase("postbody")){ post.setContent(fixNewline.matcher(serializer.getAsString(pc)).replaceAll("")); } if(pc.getAttributeByName("class").equalsIgnoreCase("postdate")){//done if(pc.getChildTags().length>0){ post.setLastReadUrl(pc.getChildTags()[0].getAttributeByName("href").replaceAll("&amp;", "&")); } post.setDate(pc.getText().toString().replaceAll("[^\\w\\s:,]", "").trim()); } if(pc.getAttributeByName("class").equalsIgnoreCase("profilelinks")){ TagNode[] links = pc.getElementsHavingAttribute("href", true); if(links.length >0){ String href = links[0].getAttributeByName("href").trim(); post.setUserId(href.substring(href.lastIndexOf("rid=")+4)); for (TagNode linkNode : links) { String link = linkNode.getText().toString(); if (link.equals(LINK_PROFILE)) post.setHasProfileLink(true); else if(link.equals(LINK_MESSAGE)) post.setHasMessageLink(true); else if(link.equals(LINK_POST_HISTORY)) post.setHasPostHistoryLink(true); // Rap sheet is actually filled in by javascript for some stupid reason } } } if(pc.getAttributeByName("class").contains("seen") && !lastReadFound){ post.setPreviouslyRead(true); } if (!post.isPreviouslyRead()) { post.setLastRead(true); lastReadFound = true; } if(pc.getAttributeByName("class").equalsIgnoreCase("editedby") && pc.getChildTags().length >0){ post.setEdited("<i>" + pc.getChildTags()[0].getText().toString() + "</i>"); } } post.setEven(even); // even/uneven post for alternating colors even = !even; TagNode[] editImgs = node.getElementsByAttValue("alt", "Edit", true, true); if (editImgs.length > 0) { Log.i(TAG, "Editable!"); post.setEditable(true); } else { post.setEditable(false); } //it's always there though, so we can set it true without an explicit check post.setHasRapSheetLink(true); result.add(post); } Log.i(TAG, Integer.toString(postNodes.length)); } catch (Exception e) { e.printStackTrace(); } return result; } private static String createPostHtml(String aHtml) { aHtml = aHtml.replaceAll(ELEMENT_POSTBODY, REPLACEMENT_POSTBODY); aHtml = aHtml.replaceAll(ELEMENT_END_TD, REPLACEMENT_END_TD); return aHtml; } }
true
true
public static ArrayList<AwfulPost> parsePosts(TagNode aThread) { ArrayList<AwfulPost> result = new ArrayList<AwfulPost>(); HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties properties = cleaner.getProperties(); properties.setOmitComments(true); SimpleHtmlSerializer serializer = new SimpleHtmlSerializer(cleaner.getProperties()); boolean lastReadFound = false; boolean even = false; try { TagNode[] postNodes = aThread.getElementsByAttValue("class", "post", true, true); for (TagNode node : postNodes) { AwfulPost post = new AwfulPost(); // We'll just reuse the array of objects rather than create // a ton of them String id = node.getAttributeByName("id"); post.setId(id.replaceAll("post", "")); TagNode[] postContent = node.getElementsHavingAttribute("class", true); for(TagNode pc : postContent){ if(pc.getAttributeByName("class").contains("author")){ post.setUsername(pc.getText().toString().trim()); } if(pc.getAttributeByName("class").equalsIgnoreCase("title") && pc.getChildTags().length >0){ post.setAvatar(pc.getChildTags()[0].getAttributeByName("src")); } if(pc.getAttributeByName("class").equalsIgnoreCase("postbody")){ post.setContent(fixNewline.matcher(serializer.getAsString(pc)).replaceAll("")); } if(pc.getAttributeByName("class").equalsIgnoreCase("postdate")){//done if(pc.getChildTags().length>0){ post.setLastReadUrl(pc.getChildTags()[0].getAttributeByName("href").replaceAll("&amp;", "&")); } post.setDate(pc.getText().toString().replaceAll("[^\\w\\s:,]", "").trim()); } if(pc.getAttributeByName("class").equalsIgnoreCase("profilelinks")){ TagNode[] links = pc.getElementsHavingAttribute("href", true); if(links.length >0){ String href = links[0].getAttributeByName("href").trim(); post.setUserId(href.substring(href.lastIndexOf("rid=")+4)); for (TagNode linkNode : links) { String link = linkNode.getText().toString(); if (link.equals(LINK_PROFILE)) post.setHasProfileLink(true); else if(link.equals(LINK_MESSAGE)) post.setHasMessageLink(true); else if(link.equals(LINK_POST_HISTORY)) post.setHasPostHistoryLink(true); // Rap sheet is actually filled in by javascript for some stupid reason } } } if(pc.getAttributeByName("class").contains("seen") && !lastReadFound){ post.setPreviouslyRead(true); } if (!post.isPreviouslyRead()) { post.setLastRead(true); lastReadFound = true; } if(pc.getAttributeByName("class").equalsIgnoreCase("editedby") && pc.getChildTags().length >0){ post.setEdited("<i>" + pc.getChildTags()[0].getText().toString() + "</i>"); } } post.setEven(even); // even/uneven post for alternating colors even = !even; TagNode[] editImgs = node.getElementsByAttValue("alt", "Edit", true, true); if (editImgs.length > 0) { Log.i(TAG, "Editable!"); post.setEditable(true); } else { post.setEditable(false); } //it's always there though, so we can set it true without an explicit check post.setHasRapSheetLink(true); result.add(post); } Log.i(TAG, Integer.toString(postNodes.length)); } catch (Exception e) { e.printStackTrace(); } return result; }
public static ArrayList<AwfulPost> parsePosts(TagNode aThread) { ArrayList<AwfulPost> result = new ArrayList<AwfulPost>(); HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties properties = cleaner.getProperties(); properties.setOmitComments(true); SimpleHtmlSerializer serializer = new SimpleHtmlSerializer(cleaner.getProperties()); boolean lastReadFound = false; boolean even = false; try { TagNode[] postNodes = aThread.getElementsByAttValue("class", "post", true, true); for (TagNode node : postNodes) { AwfulPost post = new AwfulPost(); // We'll just reuse the array of objects rather than create // a ton of them String id = node.getAttributeByName("id"); post.setId(id.replaceAll("post", "")); TagNode[] postContent = node.getElementsHavingAttribute("class", true); for(TagNode pc : postContent){ if(pc.getAttributeByName("class").contains("author")){ post.setUsername(pc.getText().toString().trim()); } if(pc.getAttributeByName("class").equalsIgnoreCase("img")){ post.setAvatar(pc.getAttributeByName("src")); } if(pc.getAttributeByName("class").equalsIgnoreCase("postbody")){ post.setContent(fixNewline.matcher(serializer.getAsString(pc)).replaceAll("")); } if(pc.getAttributeByName("class").equalsIgnoreCase("postdate")){//done if(pc.getChildTags().length>0){ post.setLastReadUrl(pc.getChildTags()[0].getAttributeByName("href").replaceAll("&amp;", "&")); } post.setDate(pc.getText().toString().replaceAll("[^\\w\\s:,]", "").trim()); } if(pc.getAttributeByName("class").equalsIgnoreCase("profilelinks")){ TagNode[] links = pc.getElementsHavingAttribute("href", true); if(links.length >0){ String href = links[0].getAttributeByName("href").trim(); post.setUserId(href.substring(href.lastIndexOf("rid=")+4)); for (TagNode linkNode : links) { String link = linkNode.getText().toString(); if (link.equals(LINK_PROFILE)) post.setHasProfileLink(true); else if(link.equals(LINK_MESSAGE)) post.setHasMessageLink(true); else if(link.equals(LINK_POST_HISTORY)) post.setHasPostHistoryLink(true); // Rap sheet is actually filled in by javascript for some stupid reason } } } if(pc.getAttributeByName("class").contains("seen") && !lastReadFound){ post.setPreviouslyRead(true); } if (!post.isPreviouslyRead()) { post.setLastRead(true); lastReadFound = true; } if(pc.getAttributeByName("class").equalsIgnoreCase("editedby") && pc.getChildTags().length >0){ post.setEdited("<i>" + pc.getChildTags()[0].getText().toString() + "</i>"); } } post.setEven(even); // even/uneven post for alternating colors even = !even; TagNode[] editImgs = node.getElementsByAttValue("alt", "Edit", true, true); if (editImgs.length > 0) { Log.i(TAG, "Editable!"); post.setEditable(true); } else { post.setEditable(false); } //it's always there though, so we can set it true without an explicit check post.setHasRapSheetLink(true); result.add(post); } Log.i(TAG, Integer.toString(postNodes.length)); } catch (Exception e) { e.printStackTrace(); } return result; }
diff --git a/trunk/java/com/tigervnc/rfb/RawDecoder.java b/trunk/java/com/tigervnc/rfb/RawDecoder.java index f7e5d46a..6be535b2 100644 --- a/trunk/java/com/tigervnc/rfb/RawDecoder.java +++ b/trunk/java/com/tigervnc/rfb/RawDecoder.java @@ -1,44 +1,45 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ package com.tigervnc.rfb; public class RawDecoder extends Decoder { public RawDecoder(CMsgReader reader_) { reader = reader_; } public void readRect(Rect r, CMsgHandler handler) { int x = r.tl.x; int y = r.tl.y; int w = r.width(); int h = r.height(); - int[] imageBuf = reader.getImageBuf(w * h); - int nPixels = imageBuf.length / (reader.bpp() / 8); + int[] imageBuf = new int[w*h]; + int nPixels = imageBuf.length; + int bytesPerRow = w * (reader.bpp() / 8); while (h > 0) { int nRows = nPixels / w; if (nRows > h) nRows = h; - reader.is.readPixels(imageBuf, w * h, (reader.bpp() / 8), handler.cp.pf().bigEndian); + reader.getInStream().readPixels(imageBuf, nPixels, (reader.bpp() / 8), handler.cp.pf().bigEndian); handler.imageRect(new Rect(x, y, x+w, y+nRows), imageBuf); h -= nRows; y += nRows; } } CMsgReader reader; static LogWriter vlog = new LogWriter("RawDecoder"); }
false
true
public void readRect(Rect r, CMsgHandler handler) { int x = r.tl.x; int y = r.tl.y; int w = r.width(); int h = r.height(); int[] imageBuf = reader.getImageBuf(w * h); int nPixels = imageBuf.length / (reader.bpp() / 8); while (h > 0) { int nRows = nPixels / w; if (nRows > h) nRows = h; reader.is.readPixels(imageBuf, w * h, (reader.bpp() / 8), handler.cp.pf().bigEndian); handler.imageRect(new Rect(x, y, x+w, y+nRows), imageBuf); h -= nRows; y += nRows; } }
public void readRect(Rect r, CMsgHandler handler) { int x = r.tl.x; int y = r.tl.y; int w = r.width(); int h = r.height(); int[] imageBuf = new int[w*h]; int nPixels = imageBuf.length; int bytesPerRow = w * (reader.bpp() / 8); while (h > 0) { int nRows = nPixels / w; if (nRows > h) nRows = h; reader.getInStream().readPixels(imageBuf, nPixels, (reader.bpp() / 8), handler.cp.pf().bigEndian); handler.imageRect(new Rect(x, y, x+w, y+nRows), imageBuf); h -= nRows; y += nRows; } }
diff --git a/src/org/tomahawk/libtomahawk/audio/PlaybackSeekBar.java b/src/org/tomahawk/libtomahawk/audio/PlaybackSeekBar.java index 005d6f17..ef99e9b8 100644 --- a/src/org/tomahawk/libtomahawk/audio/PlaybackSeekBar.java +++ b/src/org/tomahawk/libtomahawk/audio/PlaybackSeekBar.java @@ -1,195 +1,196 @@ /* == This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2012, Enno Gottschalk <[email protected]> * Copyright 2012, Hugo Lindström <[email protected]> * * Tomahawk is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tomahawk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ package org.tomahawk.libtomahawk.audio; import org.tomahawk.tomahawk_android.R; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.widget.SeekBar; import android.widget.TextView; public class PlaybackSeekBar extends SeekBar implements Handler.Callback { private boolean mIsSeeking; private PlaybackService mPlaybackService; private OnSeekBarChangeListener mOnSeekBarChangeListener; private Handler mUiHandler; private TextView mTextViewCurrentTime; private TextView mTextViewCompletionTime; private int mUpdateInterval; private static final int MSG_UPDATE_PROGRESS = 0x1; /** @param context * @param attrs */ public PlaybackSeekBar(Context context, AttributeSet attrs) { super(context, attrs); mUiHandler = new Handler(this); mOnSeekBarChangeListener = new OnSeekBarChangeListener() { /* * (non-Javadoc) * @see android .widget .SeekBar. OnSeekBarChangeListener # onProgressChanged (android .widget .SeekBar, * int, boolean) */ @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { - updateTextViewCurrentTime(mPlaybackService.getPosition()); + if (isIsSeeking()) + updateTextViewCurrentTime(mPlaybackService.getPosition()); } /* * (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onStartTrackingTouch (android .widget.SeekBar) */ @Override public void onStartTrackingTouch(SeekBar arg0) { setIsSeeking(true); } /* * (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onStopTrackingTouch (android .widget.SeekBar) */ @Override public void onStopTrackingTouch(SeekBar arg0) { setIsSeeking(false); mPlaybackService.seekTo(getProgress()); updateSeekBarPosition(); } }; setOnSeekBarChangeListener(mOnSeekBarChangeListener); setIsSeeking(false); } /* * (non-Javadoc) * @see android.os.Handler.Callback#handleMessage(android.os.Message) */ @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_PROGRESS: updateSeekBarPosition(); break; } return true; } public void setMax() { setMax((int) mPlaybackService.getCurrentTrack().getDuration()); } public void setUpdateInterval() { mUpdateInterval = (int) (mPlaybackService.getCurrentTrack().getDuration() / 300); mUpdateInterval = Math.min(mUpdateInterval, 250); mUpdateInterval = Math.max(mUpdateInterval, 20); } /** Updates the position on seekbar and the related textviews */ public void updateSeekBarPosition() { if (!isIsSeeking()) { if (mPlaybackService.isPreparing() || mPlaybackService.getCurrentTrack().getDuration() == 0) { setEnabled(false); } else { setEnabled(true); } if (!mPlaybackService.isPreparing()) { setProgress(mPlaybackService.getPosition()); updateTextViewCurrentTime(mPlaybackService.getPosition()); } else { setProgress(0); updateTextViewCurrentTime(0); } } mUiHandler.removeMessages(MSG_UPDATE_PROGRESS); mUiHandler.sendEmptyMessageDelayed(MSG_UPDATE_PROGRESS, mUpdateInterval); } /** Updates the textview that shows the current time the track is at */ protected void updateTextViewCurrentTime(int position) { if (mTextViewCurrentTime != null) if (!isIsSeeking()) mTextViewCurrentTime.setText(String.format("%02d", position / 60000) + ":" + String.format("%02.0f", (double) ((position / 1000) % 60))); else mTextViewCurrentTime.setText(String.format("%02d", getProgress() / 60000) + ":" + String.format("%02.0f", (double) ((getProgress() / 1000) % 60))); } /** Updates the textview that shows the duration of the current track */ protected void updateTextViewCompleteTime() { if (mTextViewCompletionTime != null) { if (mPlaybackService.getCurrentTrack() != null && mPlaybackService.getCurrentTrack().getDuration() > 0) mTextViewCompletionTime.setText(String.format("%02d", mPlaybackService.getCurrentTrack().getDuration() / 60000) + ":" + String.format("%02.0f", (double) ((mPlaybackService.getCurrentTrack().getDuration() / 1000) % 60))); else mTextViewCompletionTime.setText(getResources().getString( R.string.playbackactivity_seekbar_completion_time_string)); } } /** @return mIsSeeking showing whether or not the user is currently seeking */ public boolean isIsSeeking() { return mIsSeeking; } /** @param mIsSeeking showing whether or not the user is currently seeking */ public void setIsSeeking(boolean mIsSeeking) { this.mIsSeeking = mIsSeeking; } /** @return mUiHandler to handle the updating process of the PlaybackSeekBar */ public Handler getUiHandler() { return mUiHandler; } /** @param mUiHandler to handle the updating process of the PlaybackSeekBar */ public void setUiHandler(Handler mUiHandler) { this.mUiHandler = mUiHandler; } /** @return MSG_UPDATE_PROGRESS */ public static int getMsgUpdateProgress() { return MSG_UPDATE_PROGRESS; } /** @param mPlaybackService */ public void setPlaybackService(PlaybackService mPlaybackService) { this.mPlaybackService = mPlaybackService; } /** @param mTextViewCurrentTime displaying the current time */ public void setTextViewCurrentTime(TextView mTextViewCurrentTime) { this.mTextViewCurrentTime = mTextViewCurrentTime; } /** * @param mTextViewCompletionTime * displaying the completion time */ public void setTextViewCompletionTime(TextView mTextViewCompletionTime) { this.mTextViewCompletionTime = mTextViewCompletionTime; } }
true
true
public PlaybackSeekBar(Context context, AttributeSet attrs) { super(context, attrs); mUiHandler = new Handler(this); mOnSeekBarChangeListener = new OnSeekBarChangeListener() { /* * (non-Javadoc) * @see android .widget .SeekBar. OnSeekBarChangeListener # onProgressChanged (android .widget .SeekBar, * int, boolean) */ @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { updateTextViewCurrentTime(mPlaybackService.getPosition()); } /* * (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onStartTrackingTouch (android .widget.SeekBar) */ @Override public void onStartTrackingTouch(SeekBar arg0) { setIsSeeking(true); } /* * (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onStopTrackingTouch (android .widget.SeekBar) */ @Override public void onStopTrackingTouch(SeekBar arg0) { setIsSeeking(false); mPlaybackService.seekTo(getProgress()); updateSeekBarPosition(); } }; setOnSeekBarChangeListener(mOnSeekBarChangeListener); setIsSeeking(false); }
public PlaybackSeekBar(Context context, AttributeSet attrs) { super(context, attrs); mUiHandler = new Handler(this); mOnSeekBarChangeListener = new OnSeekBarChangeListener() { /* * (non-Javadoc) * @see android .widget .SeekBar. OnSeekBarChangeListener # onProgressChanged (android .widget .SeekBar, * int, boolean) */ @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { if (isIsSeeking()) updateTextViewCurrentTime(mPlaybackService.getPosition()); } /* * (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onStartTrackingTouch (android .widget.SeekBar) */ @Override public void onStartTrackingTouch(SeekBar arg0) { setIsSeeking(true); } /* * (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onStopTrackingTouch (android .widget.SeekBar) */ @Override public void onStopTrackingTouch(SeekBar arg0) { setIsSeeking(false); mPlaybackService.seekTo(getProgress()); updateSeekBarPosition(); } }; setOnSeekBarChangeListener(mOnSeekBarChangeListener); setIsSeeking(false); }
diff --git a/src/nl/nikhef/jgridstart/util/FileUtils.java b/src/nl/nikhef/jgridstart/util/FileUtils.java index 725c61a..ddd15b4 100644 --- a/src/nl/nikhef/jgridstart/util/FileUtils.java +++ b/src/nl/nikhef/jgridstart/util/FileUtils.java @@ -1,376 +1,376 @@ package nl.nikhef.jgridstart.util; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** Some file-related utilities */ public class FileUtils { static protected Logger logger = Logger.getLogger("nl.nikhef.jgridstart.util"); /** Copy a file from one place to another. This calls an external copy * program on the operating system to make sure it is properly copied and * permissions are retained. * @throws IOException */ public static boolean CopyFile(File in, File out) throws IOException { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { boolean hasRobocopy = false; // windows: use special copy program to retain permissions. // on Vista, "xcopy /O" requires administrative rights, so we // have to resort to using robocopy there. try { int ret = Exec(new String[]{"robocopy.exe"}); - if (ret==0 && ret==16) hasRobocopy = true; + if (ret==0 || ret==16) hasRobocopy = true; } catch (Exception e) { } if (hasRobocopy) { // we have robocopy. But ... its destination filename // needs to be equal to the source filename :( // So we rename any existing file out of the way, copy // the new file, rename it to the new name, and restore // the optional original file. All this is required to // copy a file retaining its permissions. // TODO proper return value handling (!) // move old file out of the way File origFile = new File(out.getParentFile(), in.getName()); File origFileRenamed = null; if (origFile.exists()) { origFileRenamed = new File(origFile.getParentFile(), origFile.getName()+".xxx_tmp"); origFile.renameTo(origFileRenamed); } else { origFile = null; } // copy file to new place cmd = new String[]{"robocopy.exe", in.getParent(), out.getParent(), in.getName(), "/SEC", "/NP", "/NS", "/NC", "/NFL", "/NDL"}; int ret = Exec(cmd); boolean success = ret < 4 && ret >= 0; // rename new file if (success) { new File(out.getParentFile(), in.getName()).renameTo(out); } // move old file to original place again if (origFile!=null) origFileRenamed.renameTo(origFile); return success; } else { // use xcopy instead cmd = new String[]{"xcopy.exe", in.getAbsolutePath(), out.getAbsolutePath(), "/O", "/Q", "/Y"}; // If the file/ doesn't exist on copying, xcopy will ask whether you want // to create it as a directory or just copy a file, so we always // just put "F" in xcopy's stdin. return Exec(cmd, "F", null) == 1; } } else { // other, assume unix-like cmd = new String[]{"cp", "-f", "-p", in.getAbsolutePath(), out.getAbsolutePath()}; return Exec(cmd) == 0; } } /** List ordinary files in a directory. * <p> * * @see File#listFiles * @param path Directory to list files in */ public static File[] listFilesOnly(File path) { return path.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile(); } }); } /** Copies a list of files to a directory. * <p> * When an error occurs, files already copied are removed again and * an {@linkplain IOException} is thrown. * <p> * It is discouraged to have files with the same name existing * already in the destination path. */ public static void CopyFiles(File[] fromFiles, final File toPath) throws IOException { EachFile(fromFiles, new FileCallback() { public void action(File f) throws IOException { File toFile = new File(toPath, f.getName()); if (!CopyFile(f, toFile)) throw new IOException("Copy failed: "+f+" -> "+toFile); } public void reverseAction(File f) throws IOException { File toFile = new File(toPath, f.getName()); if (!toFile.delete()) throw new IOException("Delete failed: "+toFile); } }); } /** Moves a list of files to a directory. * <p> * When an error occurs, files already moved are put back and an * {@linkplain IOException} is thrown. * <p> * It is discouraged to have files with the same name * existing already in the destination path. */ public static void MoveFiles(File[] fromFiles, final File toPath) throws IOException { EachFile(fromFiles, new FileCallback() { public void action(File f) throws IOException { File toFile = new File(toPath, f.getName()); if (!f.renameTo(toFile)) throw new IOException("Move failed: "+f+" -> "+toFile); } public void reverseAction(File f) throws IOException { File toFile = new File(toPath, f.getName()); if (!toFile.renameTo(f)) throw new IOException("Move back failed: "+toFile+" -> "+f); } }); } /** Runs a callback on each file specified. * <p> * Implements a rollback mechanism: when the callback throws an {@linkplain IOException}, * the previous operations are undone by means of the {@link FileCallback#reverseAction} * method. */ protected static void EachFile(File[] fromFiles, FileCallback callback) throws IOException { // then copy or move int i=0; try { for (i=0; i<fromFiles.length; i++) { callback.action(fromFiles[i]); } } catch (IOException e1) { String extra = ""; // move already moved files back for (int j=0; j<i; j++) { try { callback.reverseAction(fromFiles[j]); } catch (IOException e2) { extra += "\n" + e2.getLocalizedMessage(); } } // and propagate exception if (extra=="") throw e1; else throw new IOException(e1.getLocalizedMessage() + "\n\nNote that the following errors occured on rollback(!):\n" + extra); } } /** Callback handler for {@link #EachFile} */ protected interface FileCallback { /** Does an action on a File */ public void action(File f) throws IOException; /** Reverses the action of {@linkplain #action} on a File */ public void reverseAction(File f) throws IOException; } /** * Return the contents of a text file as String */ public static String readFile(File file) throws IOException { String s = System.getProperty("line.separator"); BufferedReader r = new BufferedReader(new FileReader(file)); StringBuffer buf = new StringBuffer(); String line; while ( (line = r.readLine() ) != null) { buf.append(line); buf.append(s); } r.close(); return buf.toString(); } /** * Change file permissions * <p> * Not supported natively until java 1.6. Bad Java. * Note that the ownerOnly argument differs from Java. When {@code ownerOnly} is * true for Java's {@link File#setReadable}, {@link File#setWritable} or * File.setExecutable(), the other/group permissions are left as they are. * This method resets them instead. When ownerOnly is false, behaviour is * as Java's. * * @param file File to set permissions on * @param read if reading should be allowed * @param write if writing should be allowed * @param exec if executing should be allowed * @param ownerOnly true to set group&world permissions to none, * false to set them all alike */ static public boolean chmod(File file, boolean read, boolean write, boolean exec, boolean ownerOnly) { try { // Try Java 1.6 method first. // This is also compilable on lower java versions boolean ret = true; Method setReadable = File.class.getDeclaredMethod("setReadable", new Class[] { boolean.class, boolean.class }); Method setWritable = File.class.getDeclaredMethod("setWritable", new Class[] { boolean.class, boolean.class }); Method setExecutable = File.class.getDeclaredMethod("setExecutable", new Class[] { boolean.class, boolean.class }); // first remove all permissions if ownerOnly is wanted, because File.set* // doesn't touch other/group permissions when ownerOnly is true. if (ownerOnly) { ret &= (Boolean)setReadable.invoke(file, new Object[]{ false, false }); ret &= (Boolean)setWritable.invoke(file, new Object[]{ false, false }); ret &= (Boolean)setExecutable.invoke(file, new Object[]{ false, false }); } // then set owner/all permissions ret &= (Boolean)setReadable.invoke(file, new Object[] { read, ownerOnly }); ret &= (Boolean)setWritable.invoke(file, new Object[] { write, ownerOnly }); ret &= (Boolean)setExecutable.invoke(file, new Object[] { exec, ownerOnly }); if (logger.isLoggable(Level.FINEST)) { String perms = new String(new char[] { read? 'r' : '-', write? 'w' : '-', exec? 'x' : '-' }) + (ownerOnly ? "user" : "all"); logger.finest("Java 1.6 chmod "+perms+" of "+file+" returns "+ret); } return ret; } catch (InvocationTargetException e) { // throw exceptions caused by set* methods throw (SecurityException)e.getTargetException(); // return false; // (would be unreachable code) } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (IllegalArgumentException e) { } try { // fallback to unix command int perm = 0; if (read) perm |= 4; if (write) perm |= 2; if (exec) perm |= 1; String[] chmodcmd = { "chmod", null, file.getPath() }; if (ownerOnly) { Object args[] = { new Integer(perm) }; chmodcmd[1] = String.format("0%1d00", args); } else { Object args[] = {new Integer(perm),new Integer(perm),new Integer(perm)}; chmodcmd[1] = String.format("0%1d%1d%1d", args); } return Exec(chmodcmd) == 0; } catch (Exception e2) { return false; } } /** Create a temporary directory with read-only permissions. * <p> * TODO Current code contains a race-condition. Please see Sun * bug <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4735419">4735419</a> * for a better solution. */ public static File createTempDir(String prefix, File directory) throws IOException { File d = File.createTempFile(prefix, null, directory); d.delete(); d.mkdirs(); chmod(d, true, true, true, true); return d; } public static File createTempDir(String prefix) throws IOException { return createTempDir(prefix, new File(System.getProperty("java.io.tmpdir"))); } /** Exec invocation index, to keep track of logging lines */ private static int globalExecIndex = 0; /** Execute a command, enter input on stdin, and return the exit code while storing stdout and stderr. * <p> * The process must stop waiting for input by itself, and not rely on its stdin * being closed. This doesn't work on Windows, so the process will never terminate. * * @param cmd command to run * @param input String to feed to process's stdin * @param output String to which stdout and stderr is appended, or null * @return process exit code * * @throws IOException */ public static int Exec(String[] cmd, String input, StringBuffer output) throws IOException { // get current exec invocation number for stdout/stderr tracking int index = globalExecIndex++; // log String scmd = ""; for (int i=0; i<cmd.length; i++) scmd += " "+cmd[i]; logger.finer("exec #"+index+":"+scmd); // run Process p = Runtime.getRuntime().exec(cmd); if (input!=null) { p.getOutputStream().write(input.getBytes()); p.getOutputStream().close(); } // retrieve output String s = System.getProperty("line.separator"); String lineout = null, lineerr = null; BufferedReader stdout = new BufferedReader( new InputStreamReader(p.getInputStream())); BufferedReader stderr = new BufferedReader( new InputStreamReader(p.getErrorStream())); while ( (lineout=stdout.readLine()) != null || (lineerr=stderr.readLine()) != null) { if (lineout!=null) logger.finest("[stdout #"+index+"] "+lineout); if (lineerr!=null) logger.finest("[stderr #"+index+"] "+lineerr); if (lineout!=null && output!=null) output.append(lineout + s); if (lineerr!=null && output!=null) output.append(lineerr + s); } stdout.close(); // log and return int ret = -1; try { ret = p.waitFor(); } catch (InterruptedException e) { // TODO verify this is the right thing to do throw new IOException(e.getMessage()); } logger.finest("exec"+scmd+" returns "+ret); return ret; } /** Execute a command and return the exit code while storing stdout and stderr. * * @param cmd command to run * @param output String to which stdin and stdout is appended. * @return process exit code * * @throws IOException */ public static int Exec(String[] cmd, String output) throws IOException { return Exec(cmd, null, null); } /** Execute a command and return the exit code * @throws IOException */ public static int Exec(String[] cmd) throws IOException { return Exec(cmd, null); } }
true
true
public static boolean CopyFile(File in, File out) throws IOException { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { boolean hasRobocopy = false; // windows: use special copy program to retain permissions. // on Vista, "xcopy /O" requires administrative rights, so we // have to resort to using robocopy there. try { int ret = Exec(new String[]{"robocopy.exe"}); if (ret==0 && ret==16) hasRobocopy = true; } catch (Exception e) { } if (hasRobocopy) { // we have robocopy. But ... its destination filename // needs to be equal to the source filename :( // So we rename any existing file out of the way, copy // the new file, rename it to the new name, and restore // the optional original file. All this is required to // copy a file retaining its permissions. // TODO proper return value handling (!) // move old file out of the way File origFile = new File(out.getParentFile(), in.getName()); File origFileRenamed = null; if (origFile.exists()) { origFileRenamed = new File(origFile.getParentFile(), origFile.getName()+".xxx_tmp"); origFile.renameTo(origFileRenamed); } else { origFile = null; } // copy file to new place cmd = new String[]{"robocopy.exe", in.getParent(), out.getParent(), in.getName(), "/SEC", "/NP", "/NS", "/NC", "/NFL", "/NDL"}; int ret = Exec(cmd); boolean success = ret < 4 && ret >= 0; // rename new file if (success) { new File(out.getParentFile(), in.getName()).renameTo(out); } // move old file to original place again if (origFile!=null) origFileRenamed.renameTo(origFile); return success; } else { // use xcopy instead cmd = new String[]{"xcopy.exe", in.getAbsolutePath(), out.getAbsolutePath(), "/O", "/Q", "/Y"}; // If the file/ doesn't exist on copying, xcopy will ask whether you want // to create it as a directory or just copy a file, so we always // just put "F" in xcopy's stdin. return Exec(cmd, "F", null) == 1; } } else { // other, assume unix-like cmd = new String[]{"cp", "-f", "-p", in.getAbsolutePath(), out.getAbsolutePath()}; return Exec(cmd) == 0; } }
public static boolean CopyFile(File in, File out) throws IOException { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { boolean hasRobocopy = false; // windows: use special copy program to retain permissions. // on Vista, "xcopy /O" requires administrative rights, so we // have to resort to using robocopy there. try { int ret = Exec(new String[]{"robocopy.exe"}); if (ret==0 || ret==16) hasRobocopy = true; } catch (Exception e) { } if (hasRobocopy) { // we have robocopy. But ... its destination filename // needs to be equal to the source filename :( // So we rename any existing file out of the way, copy // the new file, rename it to the new name, and restore // the optional original file. All this is required to // copy a file retaining its permissions. // TODO proper return value handling (!) // move old file out of the way File origFile = new File(out.getParentFile(), in.getName()); File origFileRenamed = null; if (origFile.exists()) { origFileRenamed = new File(origFile.getParentFile(), origFile.getName()+".xxx_tmp"); origFile.renameTo(origFileRenamed); } else { origFile = null; } // copy file to new place cmd = new String[]{"robocopy.exe", in.getParent(), out.getParent(), in.getName(), "/SEC", "/NP", "/NS", "/NC", "/NFL", "/NDL"}; int ret = Exec(cmd); boolean success = ret < 4 && ret >= 0; // rename new file if (success) { new File(out.getParentFile(), in.getName()).renameTo(out); } // move old file to original place again if (origFile!=null) origFileRenamed.renameTo(origFile); return success; } else { // use xcopy instead cmd = new String[]{"xcopy.exe", in.getAbsolutePath(), out.getAbsolutePath(), "/O", "/Q", "/Y"}; // If the file/ doesn't exist on copying, xcopy will ask whether you want // to create it as a directory or just copy a file, so we always // just put "F" in xcopy's stdin. return Exec(cmd, "F", null) == 1; } } else { // other, assume unix-like cmd = new String[]{"cp", "-f", "-p", in.getAbsolutePath(), out.getAbsolutePath()}; return Exec(cmd) == 0; } }
diff --git a/src/de/fhb/trendsys/lsc/db/control/Worker.java b/src/de/fhb/trendsys/lsc/db/control/Worker.java index 324c380..632dc7b 100644 --- a/src/de/fhb/trendsys/lsc/db/control/Worker.java +++ b/src/de/fhb/trendsys/lsc/db/control/Worker.java @@ -1,285 +1,288 @@ package de.fhb.trendsys.lsc.db.control; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javafx.scene.chart.XYChart; import javafx.application.Platform; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import de.fhb.trendsys.amazonfunctions.dynamodb.DynamoDBHandler; import de.fhb.trendsys.lsc.model.ChartVO; import de.fhb.trendsys.lsc.model.AppModel; import de.fhb.trendsys.lsc.model.NewsVO; /** * Die Klasse stellt den Hintergrund-Thread dar, der periodisch * neue Aktiendaten aus der Amazon DynamoDB l�dt. * * @author Frank Mertens * */ public class Worker extends Thread { private static Worker instance; private static final long FAST_UPDATE_DELAY = 60000; // 1 Min. private static final long SLOW_UPDATE_RATE = FAST_UPDATE_DELAY * 10L; private DynamoDBHandler ddbClient; private AppModel model; private Map<Integer, Long> stockUpdateQueue; private int priorityStock = 0; /** * Gibt die Instanz des Thread zur�ck. Existiert sie nicht, * wird der Thread erzeugt und gestartet und die neue Instanz zur�ckgegeben. * @param model Referenz auf das Appmodel, um dort Daten aktualisieren zu k�nnen. * @return Instanz des Threads */ public static Worker getInstance(AppModel model) { if (Worker.instance == null || Worker.instance.isAlive() == false || Worker.interrupted() == true) { Worker.instance = new Worker(model); Worker.instance.start(); } return Worker.instance; } /** * Konstruktor des Threads * Bereit alles f�r den Thread vor und initialisiert auch eine Verbindung zur Amazon Cloud. * * @param model * @see Worker#getInstance(AppModel) */ private Worker(AppModel model) { this.model = model; this.stockUpdateQueue = new HashMap<Integer, Long>(); this.ddbClient = new DynamoDBHandler(Regions.EU_WEST_1, "stockdata"); } public void run() { this.stockUpdateQueue = this.getStockIds(); while (!this.isInterrupted()) { System.out.println("Worker: Waking up."); this.processQueue(); System.out.println("Worker: Sleeping."); synchronized (this) { try { this.wait(Worker.FAST_UPDATE_DELAY); } catch (InterruptedException e) { // Interrupt } } } } /** * Gibt alle Aktien-IDs in der Datenbank zur�ck. Setzt auch den Zeitpunkt der letzten Aktualisierung auf von vor 24h. * Die Methode bereitet alles f�r die Update Queue vor. * * @return * @see #processQueue() * @see #updateStockChartData(List) * @see #updateStock(int, long) */ private Map<Integer, Long> getStockIds() { Map<Integer, Long> returnMap = new HashMap<Integer, Long>(); Map<String, AttributeValue> resultMap = (this.ddbClient.getAllItems(0, 0L)).get(0); Set<Entry<String, AttributeValue>> resultSet = resultMap.entrySet(); int stockId; long lastUpdateTime; for (Entry<String, AttributeValue> item : resultSet) { if (item.getKey().startsWith("stockid")) { stockId = Integer.parseInt(item.getValue().getS()); lastUpdateTime = System.currentTimeMillis() - 86400000L; // vor einem Tag returnMap.put(stockId, lastUpdateTime); } } return returnMap; } /** * Gibt den Firmennamen zu einer ID aus. * Darf nicht mit der ID = 0 verwendet werden. * @param id - Aktie * @return Firmenname */ private String getStockName(int id) { List<Map<String, AttributeValue>> resultList = this.ddbClient.getAllItems(id, 0L, 0L); String returnString = null; for (Map<String, AttributeValue> resultMap : resultList) { Set<Entry<String, AttributeValue>> resultSet = resultMap.entrySet(); for (Entry<String, AttributeValue> item : resultSet) { if (item.getKey().equals("stockname")) { returnString = item.getValue().getS(); } } } return returnString; } /** * Fragt alle Tupel einer Aktie ab, die seit dem angegeben Zeitstempel in die Datenbank geschrieben wurden. * Es wird auch das {@link AppModel} aktualisiert. * * @param id Prim�rschl�ssel der Aktie in der DB * @param timestamp �ltester Zeitpunkt der Daten * @see #processQueue() * @see #updateStockChartData(List) * */ private void updateStock(int id, long timestamp) { List<Map<String, AttributeValue>> updatedStockDataList = this.ddbClient.getAllItems(id, timestamp, System.currentTimeMillis()); System.out.println("Worker: ID " + id + " has " + updatedStockDataList.size() + " new items to process."); this.updateStockChartData(updatedStockDataList); } /** * Verarbeitet die Ergebnisse der DB-Abfrage und aktualisiert damit das Model. * * @param updatedStockDataList Ergebnis der DB-Abfrage * @see #processQueue() * @see #updateStock(int, long) * */ private void updateStockChartData(List<Map<String, AttributeValue>> updatedStockDataList) { String stockName = null; int id = 0; String timeStamp = null; double stockValue = 0d; String newsTitle = null; String newsDescription = null; String newsUrl = null; if (this.model != null) { for (Map<String, AttributeValue> stockMap : updatedStockDataList) { Set<Entry<String, AttributeValue>> stockSet = stockMap.entrySet(); stockName = null; id = 0; timeStamp = null; stockValue = 0d; newsTitle = null; newsDescription = null; newsUrl = null; for (Entry<String, AttributeValue> item : stockSet) { String type = item.getKey(); if (type.equals("id")) id = Integer.parseInt(item.getValue().getN()); if (type.equals("timestamp")) timeStamp = item.getValue().getS(); if (type.equals("stock")) stockValue = Double.parseDouble(item.getValue().getS()); if (type.equals("newstitle")) newsTitle = item.getValue().getS(); if (type.equals("newsdescription")) newsDescription = item.getValue().getS(); if (type.equals("newsurl")) newsUrl = item.getValue().getS(); } if (id > 0 && !timeStamp.isEmpty()) { ChartVO chart = model.returnChartById(id); if (chart != null) { System.out.println("Worker: Async calling model for updating " + id + " whith new stock value " + stockValue + " from time " + this.model.millisToHHMM(Long.parseLong(timeStamp))); - updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); + //TODO Problem der Sereis-Daten durcheinader bringt +// updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); + updateModelAsync(chart, timeStamp, stockValue); } else { if (stockName == null) stockName = getStockName(id); if (stockName == null) stockName = "unknown stock"; chart = new ChartVO(id, stockName); model.addToChartList(chart); System.out.println("Worker: Async calling model for creating " + id + " whith new stock value " + stockValue + " from time " + this.model.millisToHHMM(Long.parseLong(timeStamp))); - updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); +// updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); + updateModelAsync(chart, timeStamp, stockValue); } } if (newsTitle != null && newsDescription != null && newsUrl != null) { NewsVO news = new NewsVO(newsTitle, newsDescription, newsUrl, new Date(Long.parseLong(timeStamp))); ChartVO chart = model.returnChartById(id); chart.getNewsFeeds().add(news); } } } } /** * Startet einen Thread, in dem direkt das Model und indirekt das ViewModel aktualisiert wird. Das ist n�tig, * weil das ViewModel im JavaFX-Thread l�uft und der normale Zugriff von Au�en zu Fehlern f�hren w�rde. * @param chart VO-Objekt, das aktualisiert werden soll * @param timeStamp Zeitstempel der Aktualisierung * @param stockValue Kurs zu der gegeben Zeit */ private void updateModelAsync(final ChartVO chart, final String timeStamp, final double stockValue) { Platform.runLater(new Runnable() { @Override public void run() { System.out.println("Zeit: " + timeStamp + " Aktie: " + chart.getName() + " Kurs: " + stockValue); chart.getChart().getData().add(new XYChart.Data<String, Number>(timeStamp, stockValue)); model.updateTicker(); } }); } /** * Aktualisiert entsprechend der Queue die Aktiendaten. * * @see #updateStock(int, long) */ private void processQueue() { int id; long nextUpdateTime; Set<Entry<Integer, Long>> stockSet = stockUpdateQueue.entrySet(); long currentTime = System.currentTimeMillis(); for (Entry<Integer, Long> stock : stockSet) { id = stock.getKey(); nextUpdateTime = stock.getValue(); if (nextUpdateTime < currentTime) { System.out.println("Worker: Update of ID " + stock.getKey() + " nescessary."); this.updateStock(stock.getKey(), nextUpdateTime); nextUpdateTime = currentTime + ((id == this.priorityStock) ? Worker.FAST_UPDATE_DELAY : Worker.SLOW_UPDATE_RATE); stock.setValue(nextUpdateTime); } } } /** * Legt die Aktie fest, die jede Minute aktualisiert werden soll. * Alle anderen Aktien werden alle 10 Minuten aktualisiert. * * @param id Aktie, die �fters aktualisiert werden soll */ public void setPriorityStock(int id) { if (id > 0) this.priorityStock = id; int stockId; Set<Entry<Integer, Long>> stockSet = stockUpdateQueue.entrySet(); for (Entry<Integer, Long> stock : stockSet) { stockId = stock.getKey(); if (stockId == this.priorityStock) stock.setValue(System.currentTimeMillis()); } } }
false
true
private void updateStockChartData(List<Map<String, AttributeValue>> updatedStockDataList) { String stockName = null; int id = 0; String timeStamp = null; double stockValue = 0d; String newsTitle = null; String newsDescription = null; String newsUrl = null; if (this.model != null) { for (Map<String, AttributeValue> stockMap : updatedStockDataList) { Set<Entry<String, AttributeValue>> stockSet = stockMap.entrySet(); stockName = null; id = 0; timeStamp = null; stockValue = 0d; newsTitle = null; newsDescription = null; newsUrl = null; for (Entry<String, AttributeValue> item : stockSet) { String type = item.getKey(); if (type.equals("id")) id = Integer.parseInt(item.getValue().getN()); if (type.equals("timestamp")) timeStamp = item.getValue().getS(); if (type.equals("stock")) stockValue = Double.parseDouble(item.getValue().getS()); if (type.equals("newstitle")) newsTitle = item.getValue().getS(); if (type.equals("newsdescription")) newsDescription = item.getValue().getS(); if (type.equals("newsurl")) newsUrl = item.getValue().getS(); } if (id > 0 && !timeStamp.isEmpty()) { ChartVO chart = model.returnChartById(id); if (chart != null) { System.out.println("Worker: Async calling model for updating " + id + " whith new stock value " + stockValue + " from time " + this.model.millisToHHMM(Long.parseLong(timeStamp))); updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); } else { if (stockName == null) stockName = getStockName(id); if (stockName == null) stockName = "unknown stock"; chart = new ChartVO(id, stockName); model.addToChartList(chart); System.out.println("Worker: Async calling model for creating " + id + " whith new stock value " + stockValue + " from time " + this.model.millisToHHMM(Long.parseLong(timeStamp))); updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); } } if (newsTitle != null && newsDescription != null && newsUrl != null) { NewsVO news = new NewsVO(newsTitle, newsDescription, newsUrl, new Date(Long.parseLong(timeStamp))); ChartVO chart = model.returnChartById(id); chart.getNewsFeeds().add(news); } } } }
private void updateStockChartData(List<Map<String, AttributeValue>> updatedStockDataList) { String stockName = null; int id = 0; String timeStamp = null; double stockValue = 0d; String newsTitle = null; String newsDescription = null; String newsUrl = null; if (this.model != null) { for (Map<String, AttributeValue> stockMap : updatedStockDataList) { Set<Entry<String, AttributeValue>> stockSet = stockMap.entrySet(); stockName = null; id = 0; timeStamp = null; stockValue = 0d; newsTitle = null; newsDescription = null; newsUrl = null; for (Entry<String, AttributeValue> item : stockSet) { String type = item.getKey(); if (type.equals("id")) id = Integer.parseInt(item.getValue().getN()); if (type.equals("timestamp")) timeStamp = item.getValue().getS(); if (type.equals("stock")) stockValue = Double.parseDouble(item.getValue().getS()); if (type.equals("newstitle")) newsTitle = item.getValue().getS(); if (type.equals("newsdescription")) newsDescription = item.getValue().getS(); if (type.equals("newsurl")) newsUrl = item.getValue().getS(); } if (id > 0 && !timeStamp.isEmpty()) { ChartVO chart = model.returnChartById(id); if (chart != null) { System.out.println("Worker: Async calling model for updating " + id + " whith new stock value " + stockValue + " from time " + this.model.millisToHHMM(Long.parseLong(timeStamp))); //TODO Problem der Sereis-Daten durcheinader bringt // updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); updateModelAsync(chart, timeStamp, stockValue); } else { if (stockName == null) stockName = getStockName(id); if (stockName == null) stockName = "unknown stock"; chart = new ChartVO(id, stockName); model.addToChartList(chart); System.out.println("Worker: Async calling model for creating " + id + " whith new stock value " + stockValue + " from time " + this.model.millisToHHMM(Long.parseLong(timeStamp))); // updateModelAsync(chart, this.model.millisToHHMM(Long.parseLong(timeStamp)), stockValue); updateModelAsync(chart, timeStamp, stockValue); } } if (newsTitle != null && newsDescription != null && newsUrl != null) { NewsVO news = new NewsVO(newsTitle, newsDescription, newsUrl, new Date(Long.parseLong(timeStamp))); ChartVO chart = model.returnChartById(id); chart.getNewsFeeds().add(news); } } } }
diff --git a/src/test/java/mock/NomicServiceMockTest.java b/src/test/java/mock/NomicServiceMockTest.java index eb9df9e..f3c7e20 100644 --- a/src/test/java/mock/NomicServiceMockTest.java +++ b/src/test/java/mock/NomicServiceMockTest.java @@ -1,108 +1,108 @@ package mock; import java.util.ArrayList; import java.util.Collection; import junit.framework.TestCase; import org.drools.KnowledgeBase; import org.drools.compiler.DroolsParserException; import org.drools.runtime.StatefulKnowledgeSession; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; import services.NomicService; import uk.ac.imperial.presage2.core.environment.EnvironmentSharedStateAccess; import uk.ac.imperial.presage2.core.event.EventBus; @RunWith(JMock.class) public class NomicServiceMockTest extends TestCase { Mockery context = new JUnit4Mockery(); @Test public void NomicServiceSingleStringRuleAdditionTest() { String newRule = "import agents.NomicAgent " + "rule \"Dynamic rule!\"" + "when" + " $agent : NomicAgent(SequentialID == 1)" + "then" + " System.out.println(\"Found agent 1!\");" + "end"; final EnvironmentSharedStateAccess ss = context.mock(EnvironmentSharedStateAccess.class); final StatefulKnowledgeSession session = context.mock(StatefulKnowledgeSession.class); final EventBus e = context.mock(EventBus.class); final KnowledgeBase base = context.mock(KnowledgeBase.class); context.checking(new Expectations() {{ oneOf(e).subscribe(with(any(NomicService.class))); oneOf(session).getKnowledgeBase(); will(returnValue(base)); oneOf(base).addKnowledgePackages(with(any(Collection.class))); }}); final NomicService service = new NomicService(ss, session, e); try { service.addRule(newRule); } catch (DroolsParserException e1) { fail("Rule was not parsed correctly."); } context.assertIsSatisfied(); } @Test public void NomicServiceMultipleStringRuleAdditionTest() { final EnvironmentSharedStateAccess ss = context.mock(EnvironmentSharedStateAccess.class); final StatefulKnowledgeSession session = context.mock(StatefulKnowledgeSession.class); final EventBus e = context.mock(EventBus.class); final KnowledgeBase base = context.mock(KnowledgeBase.class); context.checking(new Expectations() {{ exactly(3).of(e).subscribe(with(any(NomicService.class))); exactly(3).of(session).getKnowledgeBase(); will(returnValue(base)); exactly(3).of(base).addKnowledgePackages(with(any(Collection.class))); }}); final NomicService service = new NomicService(ss, session, e); ArrayList<String> imports = new ArrayList<String>(); imports.add("agents.NomicAgent"); String ruleName = "Dynamic Rule!"; ArrayList<String> conditions = new ArrayList<String>(); conditions.add("$agent : NomicAgent(SequentialID == 1)"); ArrayList<String> actions = new ArrayList<String>(); actions.add("System.out.println(\"Found agent 1!\");"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e1) { fail("Simple rule was not parsed directly." + e1.getMessage()); } - conditions.add("$agent : NomicAgent(SequentialID == 2)"); + conditions.add("$agent2 : NomicAgent(SequentialID == 2)"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e2) { fail("Multiple condition failure.\n" + e2.getMessage()); } actions.add("System.out.println(\"Testing multiple actions\");"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e2) { fail("Multiple actions failure.\n" + e2.getMessage()); } context.assertIsSatisfied(); } }
true
true
public void NomicServiceMultipleStringRuleAdditionTest() { final EnvironmentSharedStateAccess ss = context.mock(EnvironmentSharedStateAccess.class); final StatefulKnowledgeSession session = context.mock(StatefulKnowledgeSession.class); final EventBus e = context.mock(EventBus.class); final KnowledgeBase base = context.mock(KnowledgeBase.class); context.checking(new Expectations() {{ exactly(3).of(e).subscribe(with(any(NomicService.class))); exactly(3).of(session).getKnowledgeBase(); will(returnValue(base)); exactly(3).of(base).addKnowledgePackages(with(any(Collection.class))); }}); final NomicService service = new NomicService(ss, session, e); ArrayList<String> imports = new ArrayList<String>(); imports.add("agents.NomicAgent"); String ruleName = "Dynamic Rule!"; ArrayList<String> conditions = new ArrayList<String>(); conditions.add("$agent : NomicAgent(SequentialID == 1)"); ArrayList<String> actions = new ArrayList<String>(); actions.add("System.out.println(\"Found agent 1!\");"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e1) { fail("Simple rule was not parsed directly." + e1.getMessage()); } conditions.add("$agent : NomicAgent(SequentialID == 2)"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e2) { fail("Multiple condition failure.\n" + e2.getMessage()); } actions.add("System.out.println(\"Testing multiple actions\");"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e2) { fail("Multiple actions failure.\n" + e2.getMessage()); } context.assertIsSatisfied(); }
public void NomicServiceMultipleStringRuleAdditionTest() { final EnvironmentSharedStateAccess ss = context.mock(EnvironmentSharedStateAccess.class); final StatefulKnowledgeSession session = context.mock(StatefulKnowledgeSession.class); final EventBus e = context.mock(EventBus.class); final KnowledgeBase base = context.mock(KnowledgeBase.class); context.checking(new Expectations() {{ exactly(3).of(e).subscribe(with(any(NomicService.class))); exactly(3).of(session).getKnowledgeBase(); will(returnValue(base)); exactly(3).of(base).addKnowledgePackages(with(any(Collection.class))); }}); final NomicService service = new NomicService(ss, session, e); ArrayList<String> imports = new ArrayList<String>(); imports.add("agents.NomicAgent"); String ruleName = "Dynamic Rule!"; ArrayList<String> conditions = new ArrayList<String>(); conditions.add("$agent : NomicAgent(SequentialID == 1)"); ArrayList<String> actions = new ArrayList<String>(); actions.add("System.out.println(\"Found agent 1!\");"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e1) { fail("Simple rule was not parsed directly." + e1.getMessage()); } conditions.add("$agent2 : NomicAgent(SequentialID == 2)"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e2) { fail("Multiple condition failure.\n" + e2.getMessage()); } actions.add("System.out.println(\"Testing multiple actions\");"); try { service.addRule(imports, ruleName, conditions, actions); } catch (DroolsParserException e2) { fail("Multiple actions failure.\n" + e2.getMessage()); } context.assertIsSatisfied(); }
diff --git a/src/java/com/eviware/soapui/impl/wsdl/support/wsdl/UrlWsdlLoader.java b/src/java/com/eviware/soapui/impl/wsdl/support/wsdl/UrlWsdlLoader.java index 1163ff641..e070fa26f 100644 --- a/src/java/com/eviware/soapui/impl/wsdl/support/wsdl/UrlWsdlLoader.java +++ b/src/java/com/eviware/soapui/impl/wsdl/support/wsdl/UrlWsdlLoader.java @@ -1,419 +1,419 @@ /* * soapUI, copyright (C) 2004-2011 eviware.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details at gnu.org. */ package com.eviware.soapui.impl.wsdl.support.wsdl; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.AuthPolicy; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import com.eviware.soapui.SoapUI; import com.eviware.soapui.impl.support.definition.DefinitionLoader; import com.eviware.soapui.impl.wsdl.support.CompressionSupport; import com.eviware.soapui.impl.wsdl.support.PathUtils; import com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport; import com.eviware.soapui.impl.wsdl.support.http.ProxyUtils; import com.eviware.soapui.model.ModelItem; import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext; import com.eviware.soapui.model.settings.Settings; import com.eviware.soapui.settings.HttpSettings; import com.eviware.soapui.support.StringUtils; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.swing.SwingWorker; import com.eviware.soapui.support.types.StringToStringMap; import com.eviware.x.form.XForm; import com.eviware.x.form.XFormDialog; import com.eviware.x.form.XFormDialogBuilder; import com.eviware.x.form.XFormFactory; /** * WsdlLoader for URLs * * @author ole.matzura */ public class UrlWsdlLoader extends WsdlLoader implements DefinitionLoader { private HttpContext state; protected HttpGet getMethod; private boolean aborted; protected Map<String, byte[]> urlCache = new HashMap<String, byte[]>(); protected boolean finished; private boolean useWorker; private ModelItem contextModelItem; private org.apache.http.HttpResponse httpResponse; public UrlWsdlLoader( String url ) { this( url, null ); } public UrlWsdlLoader( String url, ModelItem contextModelItem ) { super( url ); this.contextModelItem = contextModelItem; state = new BasicHttpContext(); } public boolean isUseWorker() { return useWorker; } public void setUseWorker( boolean useWorker ) { this.useWorker = useWorker; } public InputStream load() throws Exception { return load( getBaseURI() ); } public synchronized InputStream load( String url ) throws Exception { if( !PathUtils.isHttpPath( url ) ) { try { File file = new File( url.replace( '/', File.separatorChar ) ); if( file.exists() ) url = file.toURI().toURL().toString(); } catch( Exception e ) { } } if( urlCache.containsKey( url ) ) { setNewBaseURI( url ); return new ByteArrayInputStream( urlCache.get( url ) ); } if( url.startsWith( "file:" ) ) { return handleFile( url ); } log.debug( "Getting wsdl component from [" + url + "]" ); createGetMethod( url ); if( aborted ) return null; LoaderWorker worker = new LoaderWorker(); if( useWorker ) worker.start(); else worker.construct(); while( !aborted && !finished ) { Thread.sleep( 200 ); } // wait for method to catch up - required in unit tests.. // limited looping to 10 loops because of eclipse plugin which entered // endless loop without it int counter = 0; byte[] content = null; if( httpResponse != null ) { content = EntityUtils.toByteArray( new BufferedHttpEntity( httpResponse.getEntity() ) ); } while( !aborted && content == null && counter < 10 ) { Thread.sleep( 200 ); counter++ ; } if( aborted ) { throw new Exception( "Load of url [" + url + "] was aborted" ); } else { if( content != null ) { String compressionAlg = HttpClientSupport.getResponseCompressionType( httpResponse ); if( compressionAlg != null ) content = CompressionSupport.decompress( compressionAlg, content ); urlCache.put( url, content ); String newUrl = getMethod.getURI().toString(); if( !url.equals( newUrl ) ) log.info( "BaseURI was redirected to [" + newUrl + "]" ); setNewBaseURI( newUrl ); urlCache.put( newUrl, content ); return new ByteArrayInputStream( content ); } else { - throw new Exception( "Failed to load url; " + url + throw new Exception( "Failed to load url; " + url + ", " + ( httpResponse != null ? httpResponse.getStatusLine().getStatusCode() : 0 ) + " - " + ( httpResponse != null ? httpResponse.getStatusLine().getReasonPhrase() : "" ) ); } } } protected InputStream handleFile( String url ) throws Exception { setNewBaseURI( url ); return new URL( url ).openStream(); } protected void createGetMethod( String url ) { getMethod = new HttpGet( url ); getMethod.getParams().setParameter( ClientPNames.HANDLE_REDIRECTS, true ); state.setAttribute( ClientContext.CREDS_PROVIDER, new WsdlCredentialsProvider() ); if( SoapUI.getSettings().getBoolean( HttpSettings.AUTHENTICATE_PREEMPTIVELY ) ) { if( !StringUtils.isNullOrEmpty( getUsername() ) && !StringUtils.isNullOrEmpty( getPassword() ) ) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials( getUsername(), getPassword() ); getMethod.addHeader( BasicScheme.authenticate( creds, "utf-8", false ) ); } } } public final class LoaderWorker extends SwingWorker { public Object construct() { DefaultHttpClient httpClient = HttpClientSupport.getHttpClient(); try { Settings soapuiSettings = SoapUI.getSettings(); HttpClientSupport.applyHttpSettings( getMethod, soapuiSettings ); ProxyUtils.initProxySettings( soapuiSettings, getMethod, state, getMethod.getURI().toString(), contextModelItem == null ? null : new DefaultPropertyExpansionContext( contextModelItem ) ); httpResponse = httpClient.execute( getMethod, state ); } catch( Exception e ) { return e; } finally { finished = true; } return null; } } public boolean abort() { if( getMethod != null ) getMethod.abort(); aborted = true; return true; } public boolean isAborted() { return aborted; } /** * CredentialsProvider for providing login information during WSDL loading * * @author ole.matzura */ private static Map<String, Credentials> cache = new HashMap<String, Credentials>(); public final class WsdlCredentialsProvider implements CredentialsProvider { private XFormDialog basicDialog; private XFormDialog ntDialog; public WsdlCredentialsProvider() { } public Credentials getCredentials( final AuthScope authScope ) { if( authScope == null ) { throw new IllegalArgumentException( "Authentication scope may not be null" ); } String key = authScope.getHost() + "-" + authScope.getPort() + "-" + authScope.getRealm() + "-" + authScope.getScheme(); if( cache.containsKey( key ) ) { return cache.get( key ); } String pw = getPassword(); if( pw == null ) pw = ""; if( AuthPolicy.NTLM.equalsIgnoreCase( authScope.getScheme() ) || AuthPolicy.SPNEGO.equalsIgnoreCase( authScope.getScheme() ) ) { String workstation = ""; try { workstation = InetAddress.getLocalHost().getHostName(); } catch( UnknownHostException e ) { } if( hasCredentials() ) { log.info( "Returning url credentials" ); return new NTCredentials( getUsername(), pw, workstation, null ); } log.info( authScope.getHost() + ":" + authScope.getPort() + " requires Windows authentication" ); if( ntDialog == null ) { buildNtDialog(); } StringToStringMap values = new StringToStringMap(); values.put( "Info", "Authentication required for [" + authScope.getHost() + ":" + authScope.getPort() + "]" ); ntDialog.setValues( values ); if( ntDialog.show() ) { values = ntDialog.getValues(); NTCredentials credentials = new NTCredentials( values.get( "Username" ), values.get( "Password" ), workstation, values.get( "Domain" ) ); cache.put( key, credentials ); return credentials; } } else if( AuthPolicy.BASIC.equalsIgnoreCase( authScope.getScheme() ) || AuthPolicy.DIGEST.equalsIgnoreCase( authScope.getScheme() ) || AuthPolicy.SPNEGO.equalsIgnoreCase( authScope.getScheme() ) ) { if( hasCredentials() ) { log.info( "Returning url credentials" ); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( getUsername(), pw ); cache.put( key, credentials ); return credentials; } log.info( authScope.getHost() + ":" + authScope.getPort() + " requires authentication with the realm '" + authScope.getRealm() + "'" ); ShowDialog showDialog = new ShowDialog(); showDialog.values.put( "Info", "Authentication required for [" + authScope.getHost() + ":" + authScope.getPort() + "]" ); UISupport.getUIUtils().runInUIThreadIfSWT( showDialog ); if( showDialog.result ) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( showDialog.values.get( "Username" ), showDialog.values.get( "Password" ) ); cache.put( key, credentials ); return credentials; } } return null; } private void buildBasicDialog() { XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "Basic Authentication" ); XForm mainForm = builder.createForm( "Basic" ); mainForm.addLabel( "Info", "" ); mainForm.addTextField( "Username", "Username for authentication", XForm.FieldType.TEXT ); mainForm.addTextField( "Password", "Password for authentication", XForm.FieldType.PASSWORD ); basicDialog = builder.buildDialog( builder.buildOkCancelActions(), "Specify Basic Authentication Credentials", UISupport.OPTIONS_ICON ); } private void buildNtDialog() { XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "NT Authentication" ); XForm mainForm = builder.createForm( "Basic" ); mainForm.addLabel( "Info", "" ); mainForm.addTextField( "Username", "Username for authentication", XForm.FieldType.TEXT ); mainForm.addTextField( "Password", "Password for authentication", XForm.FieldType.PASSWORD ); mainForm.addTextField( "Domain", "NT Domain for authentication", XForm.FieldType.TEXT ); ntDialog = builder.buildDialog( builder.buildOkCancelActions(), "Specify NT Authentication Credentials", UISupport.OPTIONS_ICON ); } private class ShowDialog implements Runnable { StringToStringMap values = new StringToStringMap(); boolean result; public void run() { if( basicDialog == null ) buildBasicDialog(); basicDialog.setValues( values ); result = basicDialog.show(); if( result ) { values = basicDialog.getValues(); } } } public void clear() { } public void setCredentials( AuthScope arg0, Credentials arg1 ) { } } public void close() { } }
true
true
public synchronized InputStream load( String url ) throws Exception { if( !PathUtils.isHttpPath( url ) ) { try { File file = new File( url.replace( '/', File.separatorChar ) ); if( file.exists() ) url = file.toURI().toURL().toString(); } catch( Exception e ) { } } if( urlCache.containsKey( url ) ) { setNewBaseURI( url ); return new ByteArrayInputStream( urlCache.get( url ) ); } if( url.startsWith( "file:" ) ) { return handleFile( url ); } log.debug( "Getting wsdl component from [" + url + "]" ); createGetMethod( url ); if( aborted ) return null; LoaderWorker worker = new LoaderWorker(); if( useWorker ) worker.start(); else worker.construct(); while( !aborted && !finished ) { Thread.sleep( 200 ); } // wait for method to catch up - required in unit tests.. // limited looping to 10 loops because of eclipse plugin which entered // endless loop without it int counter = 0; byte[] content = null; if( httpResponse != null ) { content = EntityUtils.toByteArray( new BufferedHttpEntity( httpResponse.getEntity() ) ); } while( !aborted && content == null && counter < 10 ) { Thread.sleep( 200 ); counter++ ; } if( aborted ) { throw new Exception( "Load of url [" + url + "] was aborted" ); } else { if( content != null ) { String compressionAlg = HttpClientSupport.getResponseCompressionType( httpResponse ); if( compressionAlg != null ) content = CompressionSupport.decompress( compressionAlg, content ); urlCache.put( url, content ); String newUrl = getMethod.getURI().toString(); if( !url.equals( newUrl ) ) log.info( "BaseURI was redirected to [" + newUrl + "]" ); setNewBaseURI( newUrl ); urlCache.put( newUrl, content ); return new ByteArrayInputStream( content ); } else { throw new Exception( "Failed to load url; " + url + ( httpResponse != null ? httpResponse.getStatusLine().getStatusCode() : 0 ) + " - " + ( httpResponse != null ? httpResponse.getStatusLine().getReasonPhrase() : "" ) ); } } }
public synchronized InputStream load( String url ) throws Exception { if( !PathUtils.isHttpPath( url ) ) { try { File file = new File( url.replace( '/', File.separatorChar ) ); if( file.exists() ) url = file.toURI().toURL().toString(); } catch( Exception e ) { } } if( urlCache.containsKey( url ) ) { setNewBaseURI( url ); return new ByteArrayInputStream( urlCache.get( url ) ); } if( url.startsWith( "file:" ) ) { return handleFile( url ); } log.debug( "Getting wsdl component from [" + url + "]" ); createGetMethod( url ); if( aborted ) return null; LoaderWorker worker = new LoaderWorker(); if( useWorker ) worker.start(); else worker.construct(); while( !aborted && !finished ) { Thread.sleep( 200 ); } // wait for method to catch up - required in unit tests.. // limited looping to 10 loops because of eclipse plugin which entered // endless loop without it int counter = 0; byte[] content = null; if( httpResponse != null ) { content = EntityUtils.toByteArray( new BufferedHttpEntity( httpResponse.getEntity() ) ); } while( !aborted && content == null && counter < 10 ) { Thread.sleep( 200 ); counter++ ; } if( aborted ) { throw new Exception( "Load of url [" + url + "] was aborted" ); } else { if( content != null ) { String compressionAlg = HttpClientSupport.getResponseCompressionType( httpResponse ); if( compressionAlg != null ) content = CompressionSupport.decompress( compressionAlg, content ); urlCache.put( url, content ); String newUrl = getMethod.getURI().toString(); if( !url.equals( newUrl ) ) log.info( "BaseURI was redirected to [" + newUrl + "]" ); setNewBaseURI( newUrl ); urlCache.put( newUrl, content ); return new ByteArrayInputStream( content ); } else { throw new Exception( "Failed to load url; " + url + ", " + ( httpResponse != null ? httpResponse.getStatusLine().getStatusCode() : 0 ) + " - " + ( httpResponse != null ? httpResponse.getStatusLine().getReasonPhrase() : "" ) ); } } }