answer
stringlengths
17
10.2M
package net.mgsx.rainstick; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader; import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader; import net.mgsx.game.core.GameApplication; import net.mgsx.game.core.GameRegistry; import net.mgsx.game.core.GameScreen; import net.mgsx.game.core.screen.Transitions; import net.mgsx.rainstick.model.Rainstick; import net.mgsx.rainstick.screens.RainstickIntroScreen; import net.mgsx.rainstick.screens.RainstickSelectorScreen; import net.mgsx.rainstick.screens.RainstickSplashScreen; /** * Rainstick application is made of 2 screens : * - a loading screen displaying some credits and branding info. * - the rainstick screen * * @author mgsx * */ public class RainstickApplication extends GameApplication { private RainstickSplashScreen splashScreen; private RainstickSelectorScreen selectorScreen; private RainstickIntroScreen introScreen; @Override public void create() { super.create(); // TODO register loader where ? assets.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(assets.getFileHandleResolver())); assets.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(assets.getFileHandleResolver())); // We force asset loading for splash screen. splashScreen = new RainstickSplashScreen(assets); assets.finishLoading(); selectorScreen = new RainstickSelectorScreen(this, assets); introScreen = new RainstickIntroScreen(assets); // configure default loading screen with splash screen setDefaultLoadingScreen(Transitions.loader(assets, splashScreen)); // add transition (fade) from loading screen to rainstickScreen // loading screen is splash screen with minimum timeout of 2 seconds. setScreen(Transitions.loader(assets, Transitions.timeout(splashScreen, 2))); addTransition(Transitions.fade(Transitions.timeout(selectorScreen, 2), 2.3f)); } public void showRainstick(Rainstick rainstick) { introScreen.setRainstick(rainstick); // create registry based on RainstickPlugin configuration GameRegistry registry = new GameRegistry(); registry.registerPlugin(new RainStickPlugin()); // create default rainstick screen (loading default rainstick data) GameScreen rainstickScreen = new GameScreen(this, assets, registry){ @Override public void render(float delta) { super.render(delta); if(Gdx.input.isKeyPressed(Input.Keys.BACK)) showMenu(); } @Override public void hide() { // TODO free all (dispose) super.hide(); dispose(); } }; rainstickScreen.load(Gdx.files.internal(rainstick.path)); setTransition(Transitions.fade(Transitions.loader(assets, introScreen), 1.5f)); addTransition(Transitions.fade(Transitions.timeout(rainstickScreen, 2), 2.3f)); } public void showMenu() { setTransition(Transitions.fade(Transitions.empty(Color.WHITE), 5.5f)); addTransition(Transitions.fade(selectorScreen, 1)); } }
package ch.ice.view; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; import java.util.concurrent.CopyOnWriteArrayList; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressBar; import javafx.scene.control.TextField; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import ch.ice.controller.MainController; public class GUIController implements Initializable { @FXML private Button selectFileButton; @FXML private Button startSearchButton; @FXML private TextField fileTextField; @FXML private ProgressBar searchProgressBar; @FXML private MenuItem MetaTags; @FXML private MenuItem quitMenuItem; @FXML private Button cancelMetaButton; @FXML private Button okMetaButton; @FXML private Label metaTagsList; @FXML private TextField pathTextField; @FXML private Button changeDirectory; public static ObservableValue<? extends String> test; public static PropertiesConfiguration config; public static List<String> metaTagElements; public static String path; public static void getProperties(Label label) { try { config = new PropertiesConfiguration("conf/app.properties"); metaTagElements = new CopyOnWriteArrayList<String>( Arrays.asList(config .getStringArray("crawler.searchForMetaTags"))); label.setText(metaTagElements.toString()); } catch (ConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public static String getSaveProperties() { try { config = new PropertiesConfiguration("conf/app.properties"); path = config.getString(("writer.file.path")); } catch (ConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return path; } public static void setSaveProperties(String chosenPath) { try { config = new PropertiesConfiguration("conf/app.properties"); config.setProperty("writer.file.path", chosenPath); } catch (ConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public void initialize(URL location, ResourceBundle resources) { metaTagsList.setWrapText(true); metaTagsList.setMaxWidth(550); metaTagsList.setMaxHeight(80); Platform.runLater(new Runnable() { @Override public void run() { selectFileButton.requestFocus(); } }); getProperties(metaTagsList); FileChooser filechooser = new FileChooser(); DirectoryChooser directoryChooser = new DirectoryChooser(); getSaveProperties(); pathTextField.setText(path); selectFileButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Stage stage = new Stage(); try { filechooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter( "Excel-File (*.xlsx)", "*.xlsx"), new FileChooser.ExtensionFilter( "Excel-File (*.xls)", "*.xls")); MainController.file = filechooser.showOpenDialog(stage); if (MainController.file != null) { fileTextField.setText(MainController.file .getAbsolutePath()); } } catch (NullPointerException e) { System.out.println("No File selected"); fileTextField.setText(""); } } }); changeDirectory.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // TODO Auto-generated method stub Stage stage = new Stage(); try { File pathFile = directoryChooser.showDialog(stage); if (pathFile != null) { setSaveProperties(pathFile.getAbsolutePath()); config.save(); getSaveProperties(); pathTextField.setText(path); } } catch (NullPointerException | ConfigurationException e) { System.out.println("No Path selected"); pathTextField.setText(""); } } }); startSearchButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource( "SaveFile.fxml")); Parent root1; try { Thread t1 = new Thread() { public void run() { MainController main = new MainController(); main.startMainController(); } }; t1.start(); root1 = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.setTitle("File processed"); stage.setScene(new Scene(root1)); stage.initStyle(StageStyle.UNDECORATED); stage.showAndWait(); Platform.runLater(new Runnable() { @Override public void run() { } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); MetaTags.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource( "metaChoice.fxml")); Parent root1; try { root1 = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.setTitle("Choose your Meta Tags"); stage.setScene(new Scene(root1)); stage.initStyle(StageStyle.UNDECORATED); stage.showAndWait(); Platform.runLater(new Runnable() { @Override public void run() { getProperties(metaTagsList); } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); quitMenuItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.exit(0); } }); } }
package org.voltdb; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.FailureSiteUpdateMessage; import org.voltcore.messaging.HeartbeatMessage; import org.voltcore.messaging.HeartbeatResponseMessage; import org.voltcore.messaging.LocalObjectMessage; import org.voltcore.messaging.Mailbox; import org.voltcore.messaging.RecoveryMessage; import org.voltcore.messaging.Subject; import org.voltcore.messaging.TransactionInfoBaseMessage; import org.voltcore.messaging.VoltMessage; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.EstTime; import org.voltcore.utils.Pair; import org.voltdb.RecoverySiteProcessor.MessageHandler; import org.voltdb.VoltProcedure.VoltAbortException; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Database; import org.voltdb.catalog.SnapshotSchedule; import org.voltdb.catalog.Table; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcedureInvocationType; import org.voltdb.dtxn.DtxnConstants; import org.voltdb.dtxn.MultiPartitionParticipantTxnState; import org.voltdb.dtxn.ReplayedTxnState; import org.voltdb.dtxn.RestrictedPriorityQueue; import org.voltdb.dtxn.RestrictedPriorityQueue.QueueState; import org.voltdb.dtxn.SinglePartitionTxnState; import org.voltdb.dtxn.SiteTracker; import org.voltdb.dtxn.SiteTransactionConnection; import org.voltdb.dtxn.TransactionState; import org.voltdb.dtxn.TransactionState.RejoinState; import org.voltdb.exceptions.EEException; import org.voltdb.exceptions.SQLException; import org.voltdb.exceptions.SerializableException; import org.voltdb.export.processors.RawProcessor; import org.voltdb.fault.FaultDistributorInterface.PPDPolicyDecision; import org.voltdb.fault.FaultHandler; import org.voltdb.fault.SiteFailureFault; import org.voltdb.fault.VoltFault; import org.voltdb.fault.VoltFault.FaultType; import org.voltdb.jni.ExecutionEngine; import org.voltdb.jni.ExecutionEngineIPC; import org.voltdb.jni.ExecutionEngineJNI; import org.voltdb.jni.MockExecutionEngine; import org.voltdb.messaging.CompleteTransactionMessage; import org.voltdb.messaging.CompleteTransactionResponseMessage; import org.voltdb.messaging.FastDeserializer; import org.voltdb.messaging.FragmentResponseMessage; import org.voltdb.messaging.FragmentTaskLogMessage; import org.voltdb.messaging.FragmentTaskMessage; import org.voltdb.messaging.InitiateResponseMessage; import org.voltdb.messaging.InitiateTaskMessage; import org.voltdb.messaging.MultiPartitionParticipantMessage; import org.voltdb.messaging.RejoinMessage; import org.voltdb.messaging.RejoinMessage.Type; import org.voltdb.rejoin.RejoinSiteProcessor; import org.voltdb.rejoin.TaskLog; import org.voltdb.sysprocs.saverestore.SnapshotUtil; import org.voltdb.sysprocs.saverestore.SnapshotUtil.SnapshotResponseHandler; import org.voltdb.utils.LogKeys; import org.voltdb.utils.MiscUtils; /** * The main executor of transactional work in the system. Controls running * stored procedures and manages the execution engine's running of plan * fragments. Interacts with the DTXN system to get work to do. The thread might * do other things, but this is where the good stuff happens. */ public class ExecutionSite implements Runnable, SiteTransactionConnection, SiteProcedureConnection, SiteSnapshotConnection { private VoltLogger m_txnlog; private final VoltLogger m_recoveryLog = new VoltLogger("RECOVERY"); private static final VoltLogger log = new VoltLogger("EXEC"); private static final VoltLogger hostLog = new VoltLogger("HOST"); private static final AtomicInteger siteIndexCounter = new AtomicInteger(0); static final AtomicInteger recoveringSiteCount = new AtomicInteger(0); private final int siteIndex = siteIndexCounter.getAndIncrement(); private final ExecutionSiteNodeFailureFaultHandler m_faultHandler = new ExecutionSiteNodeFailureFaultHandler(); final LoadedProcedureSet m_loadedProcedures; final Mailbox m_mailbox; final ExecutionEngine ee; final HsqlBackend hsql; public volatile boolean m_shouldContinue = true; private final long m_startupTime = System.currentTimeMillis(); private PartitionDRGateway m_partitionDRGateway = null; /* * Recover a site at a time to make the interval in which other sites * are blocked as small as possible. The permit will be generated once. * The permit is only acquired by recovering partitions and not the source * partitions. */ public static final Semaphore m_recoveryPermit = new Semaphore(Integer.MAX_VALUE); private boolean m_rejoining = false; private boolean m_haveRecoveryPermit = false; private long m_recoveryStartTime = 0; private static AtomicLong m_recoveryBytesTransferred = new AtomicLong(); // Catalog public CatalogContext m_context; protected SiteTracker m_tracker; final long m_siteId; public long getSiteId() { return m_siteId; } HashMap<Long, TransactionState> m_transactionsById = new HashMap<Long, TransactionState>(); private final RestrictedPriorityQueue m_transactionQueue; private TransactionState m_currentTransactionState; // The time in ms since epoch of the last call to tick() long lastTickTime = 0; long lastCommittedTxnId = 0; long lastCommittedTxnTime = 0; /* * Due to failures we may find out about commited multi-part txns * before running the commit fragment. Handle node fault will generate * the fragment, but it is possible for a new failure to be detected * before the fragment can be run due to the order messages are pulled * from subjects. Maintain and send this value when discovering/sending * failure data. * * This value only gets updated on multi-partition transactions that are * not read-only. */ long lastKnownGloballyCommitedMultiPartTxnId = 0; public final static long kInvalidUndoToken = -1L; private long latestUndoToken = 0L; public long getNextUndoToken() { return ++latestUndoToken; } // Each execution site manages snapshot using a SnapshotSiteProcessor private final SnapshotSiteProcessor m_snapshotter; private RecoverySiteProcessor m_recoveryProcessor = null; // The following variables are used for new rejoin private RejoinSiteProcessor m_rejoinSnapshotProcessor = null; private volatile long m_rejoinSnapshotTxnId = -1; // The snapshot completion handler will set this to true private volatile boolean m_rejoinSnapshotFinished = false; private long m_rejoinSnapshotBytes = 0; private long m_rejoinCoordinatorHSId = -1; private TaskLog m_rejoinTaskLog = null; // Used to track if the site can keep up on rejoin, default is 10 seconds private static final long MAX_BEHIND_DURATION = Long.parseLong(System.getProperty("MAX_REJOIN_BEHIND_DURATION", "10000")); private long m_lastTimeMadeProgress = 0; private long m_remainingTasks = 0; private long m_executedTaskCount = 0; private long m_loggedTaskCount = 0; private long m_taskExeStartTime = 0; private final SnapshotCompletionInterest m_snapshotCompletionHandler = new SnapshotCompletionInterest() { @Override public CountDownLatch snapshotCompleted(String nonce, long txnId, boolean truncationSnapshot) { if (m_rejoinSnapshotTxnId != -1) { if (m_rejoinSnapshotTxnId == txnId) { m_recoveryLog.debug("Rejoin snapshot for site " + getSiteId() + " is finished"); VoltDB.instance().getSnapshotCompletionMonitor().removeInterest(this); // Notify the rejoin coordinator so that it can start the next site if (m_rejoinCoordinatorHSId != -1) { RejoinMessage msg = new RejoinMessage(getSiteId(), RejoinMessage.Type.SNAPSHOT_FINISHED); m_mailbox.send(m_rejoinCoordinatorHSId, msg); } m_rejoinSnapshotFinished = true; } } return new CountDownLatch(0); } }; // Trigger if shutdown has been run already. private boolean haveShutdownAlready; private final TableStats m_tableStats; private final IndexStats m_indexStats; private final StarvationTracker m_starvationTracker; // This message is used to start a local snapshot. The snapshot // is *not* automatically coordinated across the full node set. // That must be arranged separately. public static class ExecutionSiteLocalSnapshotMessage extends VoltMessage { public final String path; public final String nonce; public final boolean crash; /** * @param roadblocktxnid * @param path * @param nonce * @param crash Should Volt crash itself afterwards */ public ExecutionSiteLocalSnapshotMessage(long roadblocktxnid, String path, String nonce, boolean crash) { m_roadblockTransactionId = roadblocktxnid; this.path = path; this.nonce = nonce; this.crash = crash; } @Override public byte getSubject() { return Subject.FAILURE.getId(); } long m_roadblockTransactionId; @Override protected void initFromBuffer(ByteBuffer buf) { } @Override public void flattenToBuffer(ByteBuffer buf) { } } // This message is used locally to schedule a node failure event's // required processing at an execution site. class ExecutionSiteNodeFailureMessage extends VoltMessage { final HashSet<SiteFailureFault> m_failedSites; ExecutionSiteNodeFailureMessage(HashSet<SiteFailureFault> failedSites) { m_failedSites = failedSites; m_sourceHSId = m_siteId; } @Override public byte getSubject() { return Subject.FAILURE.getId(); } @Override protected void initFromBuffer(ByteBuffer buf) { } @Override public void flattenToBuffer(ByteBuffer buf) { } } /** * Generated when a snapshot buffer is discarded. Reminds the EE thread * that there is probably more snapshot work to do. */ private class PotentialSnapshotWorkMessage extends VoltMessage { public PotentialSnapshotWorkMessage() { m_sourceHSId = m_siteId; } @Override public byte getSubject() { return Subject.DEFAULT.getId(); } @Override protected void initFromBuffer(ByteBuffer buf) { } @Override public void flattenToBuffer(ByteBuffer buf) { } } // This message is used locally to get the currently active TransactionState // to check whether or not its WorkUnit's dependencies have been satisfied. // Necessary after handling a node failure. static class CheckTxnStateCompletionMessage extends VoltMessage { final long m_txnId; CheckTxnStateCompletionMessage(long txnId, long siteId) { m_txnId = txnId; m_sourceHSId = siteId; } @Override protected void initFromBuffer(ByteBuffer buf) { } @Override public void flattenToBuffer(ByteBuffer buf) { } } private class ExecutionSiteNodeFailureFaultHandler implements FaultHandler { @Override public void faultOccured(Set<VoltFault> faults) { if (m_shouldContinue == false) { return; } HashSet<SiteFailureFault> failedSites = new HashSet<SiteFailureFault>(); for (VoltFault fault : faults) { if (fault instanceof SiteFailureFault) { SiteFailureFault site_fault = (SiteFailureFault)fault; failedSites.add(site_fault); } } if (!failedSites.isEmpty()) { m_mailbox.deliver(new ExecutionSiteNodeFailureMessage(failedSites)); } } } /** * Log settings changed. Signal EE to update log level. */ @Override public void updateBackendLogLevels() { ee.setLogLevels(org.voltdb.jni.EELoggers.getLogLevels()); } void startShutdown() { m_shouldContinue = false; } /** * Shutdown all resources that need to be shutdown for this <code>ExecutionSite</code>. * May be called twice if recursing via recursableRun(). Protected against that.. */ public void shutdown() { if (haveShutdownAlready) { return; } haveShutdownAlready = true; m_shouldContinue = false; boolean finished = false; while (!finished) { try { m_transactionQueue.shutdown(); // Forget the m_partitionDrGateway. InvocationBufferServer // will be shutdown after all sites have terminated. m_partitionDRGateway = null; if (hsql != null) { HsqlBackend.shutdownInstance(); } if (ee != null) { ee.release(); } finished = true; } catch (final InterruptedException e) { e.printStackTrace(); } } m_snapshotter.shutdown(); } /** * Passed to recovery processors which forward non-recovery messages to this handler. * Also used when recovery is enabled and there is no recovery processor for messages * received once the priority queue is initialized and returning txns. It is necessary * to do the special prehandling in this handler where txnids that are earlier then what * has been released from the queue during recovery because multi-part txns can involve * the recovering partition after the queue has already released work after the multi-part txn. * The recovering partition was going to give an empty responses anyways so it is fine to do * that in this message handler. */ private final MessageHandler m_recoveryMessageHandler = new MessageHandler() { @Override public void handleMessage(VoltMessage message, long txnId) { if (message instanceof TransactionInfoBaseMessage) { long noticeTxnId = ((TransactionInfoBaseMessage)message).getTxnId(); /** * If the recovery processor and by extension this site receives * a message regarding a txnid < the current supplied txnId then * the message is for a multi-part txn that this site is a member of * but doesn't have any info for. Send an ack with no extra processing. */ if (noticeTxnId < txnId) { if (message instanceof CompleteTransactionMessage) { CompleteTransactionMessage complete = (CompleteTransactionMessage)message; CompleteTransactionResponseMessage ctrm = new CompleteTransactionResponseMessage(complete, m_siteId); m_mailbox.send(complete.getCoordinatorHSId(), ctrm); } else if (message instanceof FragmentTaskMessage) { FragmentTaskMessage ftask = (FragmentTaskMessage)message; FragmentResponseMessage response = new FragmentResponseMessage(ftask, m_siteId); response.setRecovering(true); response.setStatus(FragmentResponseMessage.SUCCESS, null); // add a dummy table for all of the expected dependency ids for (int i = 0; i < ftask.getFragmentCount(); i++) { response.addDependency(ftask.getOutputDepId(i), new VoltTable(new VoltTable.ColumnInfo("DUMMY", VoltType.BIGINT))); } m_mailbox.send(response.getDestinationSiteId(), response); } else { handleMailboxMessageNonRecursable(message); } } else { handleMailboxMessageNonRecursable(message); } } else { handleMailboxMessageNonRecursable(message); } } }; /** * This is invoked after all recovery data has been received/sent. The processor can be nulled out for GC. */ private final Runnable m_onRejoinCompletion = new Runnable() { @Override public void run() { final long now = System.currentTimeMillis(); final boolean newRejoin = m_recoveryProcessor == null; long transferred = 0; if (m_recoveryProcessor != null) { transferred = m_recoveryProcessor.bytesTransferred(); } else { transferred = m_rejoinSnapshotBytes; } final long bytesTransferredTotal = m_recoveryBytesTransferred.addAndGet(transferred); final long megabytes = transferred / (1024 * 1024); final double megabytesPerSecond = megabytes / ((now - m_recoveryStartTime) / 1000.0); /* * The logged txn count will be greater than the replayed txn count * because some logged ones were before the stream snapshot */ final long duration = (System.currentTimeMillis() - m_taskExeStartTime) / 1000; final long throughput = duration == 0 ? m_executedTaskCount : m_executedTaskCount / duration; m_recoveryLog.info("Logged " + m_loggedTaskCount + " tasks"); m_recoveryLog.info("Executed " + m_executedTaskCount + " tasks in " + duration + " seconds at a rate of " + throughput + " tasks/second"); m_recoveryProcessor = null; m_rejoinSnapshotProcessor = null; m_rejoinSnapshotTxnId = -1; m_rejoinSnapshotFinished = false; m_rejoinTaskLog = null; m_rejoining = false; if (m_haveRecoveryPermit) { m_haveRecoveryPermit = false; /* * If it's not using pauseless rejoin, no need to release the * permit here because it was never set. Pauseless rejoin has * its own coordinator that makes sure only one site is doing * snapshot streaming at any point of time. */ if (!newRejoin) { m_recoveryPermit.release(); } m_recoveryLog.info( "Destination recovery complete for site " + CoreUtils.hsIdToString(m_siteId) + " partition " + m_tracker.getPartitionForSite(m_siteId) + " after " + ((now - m_recoveryStartTime) / 1000) + " seconds " + " with " + megabytes + " megabytes transferred " + " at a rate of " + megabytesPerSecond + " megabytes/sec"); int remaining = recoveringSiteCount.decrementAndGet(); if (remaining == 0) { ee.toggleProfiler(0); /* * If it's the new rejoin code, the rejoin coordinator * handles this. */ if (!newRejoin) { VoltDB.instance().onExecutionSiteRejoinCompletion(bytesTransferredTotal); } } /* * New rejoin is site independent, so don't have to look at the * remaining count */ if (newRejoin) { // Notify the rejoin coordinator that this site has finished if (m_rejoinCoordinatorHSId != -1) { RejoinMessage msg = new RejoinMessage(getSiteId(), RejoinMessage.Type.REPLAY_FINISHED); m_mailbox.send(m_rejoinCoordinatorHSId, msg); } m_rejoinCoordinatorHSId = -1; } } else { m_recoveryLog.info("Source recovery complete for site " + m_siteId + " partition " + m_tracker.getPartitionForSite(m_siteId) + " after " + ((now - m_recoveryStartTime) / 1000) + " seconds " + " with " + megabytes + " megabytes transferred " + " at a rate of " + megabytesPerSecond + " megabytes/sec"); } } }; public void tick() { /* * poke the PartitionDRGateway regularly even if we are not idle. In the * case where we only have multipart work to do and we are not the * coordinator, we still need to send heartbeat buffers. * * If the last seen txnId is larger than the current txnId, use the * current txnId, or otherwise we'll end up closing a buffer * prematurely. * * If the txnId is from before the process started, caused by command * log replay, then ignore it. */ long seenTxnId = m_transactionQueue.getEarliestSeenTxnIdAcrossInitiatorsWhenEmpty(); if (m_currentTransactionState != null) { if (seenTxnId == 0 || seenTxnId > m_currentTransactionState.txnId) { seenTxnId = m_currentTransactionState.txnId; } } long seenTxnTime = TransactionIdManager.getTimestampFromTransactionId(seenTxnId); if (seenTxnTime > m_startupTime) { m_partitionDRGateway.tick(seenTxnId); } // invoke native ee tick if at least one second has passed final long time = EstTime.currentTimeMillis(); final long prevLastTickTime = lastTickTime; if ((time - lastTickTime) >= 1000) { if ((lastTickTime != 0) && (ee != null)) { ee.tick(time, lastCommittedTxnId); } lastTickTime = time; } // do other periodic work m_snapshotter.doSnapshotWork(ee, false); /* * grab the table statistics from ee and put it into the statistics * agent if at least 1/3 of the statistics broadcast interval has past. * This ensures that when the statistics are broadcasted, they are * relatively up-to-date. */ if (m_tableStats != null && (time - prevLastTickTime) >= StatsManager.POLL_INTERVAL * 2) { CatalogMap<Table> tables = m_context.database.getTables(); int[] tableIds = new int[tables.size()]; int i = 0; for (Table table : tables) { tableIds[i++] = table.getRelativeIndex(); } // data to aggregate long tupleCount = 0; int tupleDataMem = 0; int tupleAllocatedMem = 0; int indexMem = 0; int stringMem = 0; // update table stats final VoltTable[] s1 = ee.getStats(SysProcSelector.TABLE, tableIds, false, time); if (s1 != null) { VoltTable stats = s1[0]; assert(stats != null); // rollup the table memory stats for this site while (stats.advanceRow()) { tupleCount += stats.getLong(7); tupleAllocatedMem += (int) stats.getLong(8); tupleDataMem += (int) stats.getLong(9); stringMem += (int) stats.getLong(10); } stats.resetRowPosition(); m_tableStats.setStatsTable(stats); } // update index stats final VoltTable[] s2 = ee.getStats(SysProcSelector.INDEX, tableIds, false, time); if ((s2 != null) && (s2.length > 0)) { VoltTable stats = s2[0]; assert(stats != null); // rollup the index memory stats for this site while (stats.advanceRow()) { indexMem += stats.getLong(10); } stats.resetRowPosition(); m_indexStats.setStatsTable(stats); } // update the rolled up memory statistics MemoryStats memoryStats = VoltDB.instance().getMemoryStatsSource(); if (memoryStats != null) { memoryStats.eeUpdateMemStats(m_siteId, tupleCount, tupleDataMem, tupleAllocatedMem, indexMem, stringMem, ee.getThreadLocalPoolAllocations()); } } } /** * SystemProcedures are "friends" with ExecutionSites and granted * access to internal state via m_systemProcedureContext. */ protected class SystemProcedureContext implements SystemProcedureExecutionContext { @Override public Database getDatabase() { return m_context.database; } @Override public Cluster getCluster() { return m_context.cluster; } @Override public long getLastCommittedTxnId() { return lastCommittedTxnId; } @Override public long getCurrentTxnId() { return m_currentTransactionState.txnId; } @Override public long getNextUndo() { return getNextUndoToken(); } @Override public HashMap<String, ProcedureRunner> getProcedures() { return m_loadedProcedures.procs; } @Override public long getSiteId() { return m_siteId; } @Override public boolean isLowestSiteId() { return m_siteId == m_tracker.getLowestSiteForHost(getHostId()); } @Override public int getHostId() { return SiteTracker.getHostForSite(m_siteId); } @Override public int getPartitionId() { return m_tracker.getPartitionForSite(m_siteId); } @Override public long getCatalogCRC() { return m_context.getCatalogCRC(); } @Override public SiteTracker getSiteTracker() { return m_tracker; } @Override public int getNumberOfPartitions() { return m_tracker.m_numberOfPartitions; } @Override public SiteProcedureConnection getSiteProcedureConnection() { return ExecutionSite.this; } @Override public SiteSnapshotConnection getSiteSnapshotConnection() { return ExecutionSite.this; } @Override public void updateBackendLogLevels() { ExecutionSite.this.updateBackendLogLevels(); } @Override public boolean updateCatalog(String diffCmds, CatalogContext context, CatalogSpecificPlanner csp) { return ExecutionSite.this.updateCatalog(diffCmds, context, csp); } } SystemProcedureContext m_systemProcedureContext; /** * Dummy ExecutionSite useful to some tests that require Mock/Do-Nothing sites. * @param siteId */ ExecutionSite(long siteId) { m_siteId = siteId; m_systemProcedureContext = new SystemProcedureContext(); ee = null; hsql = null; m_loadedProcedures = new LoadedProcedureSet(this, null, m_siteId, siteIndex, 2); m_snapshotter = null; m_mailbox = null; m_transactionQueue = null; m_starvationTracker = null; m_tableStats = null; m_indexStats = null; // initialize the DR gateway m_partitionDRGateway = new PartitionDRGateway(); } ExecutionSite(VoltDBInterface voltdb, Mailbox mailbox, String serializedCatalog, RestrictedPriorityQueue transactionQueue, boolean recovering, boolean replicationActive, final long txnId, int configuredNumberOfPartitions, CatalogSpecificPlanner csp) throws Exception { this(voltdb, mailbox, serializedCatalog, transactionQueue, new ProcedureRunnerFactory(), recovering, replicationActive, txnId, configuredNumberOfPartitions, csp); } ExecutionSite(VoltDBInterface voltdb, Mailbox mailbox, String serializedCatalog, RestrictedPriorityQueue transactionQueue, ProcedureRunnerFactory runnerFactory, boolean recovering, boolean replicationActive, final long txnId, int configuredNumberOfPartitions, CatalogSpecificPlanner csp) throws Exception { m_siteId = mailbox.getHSId(); hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_Initializing.name(), new Object[] { String.valueOf(m_siteId) }, null); m_context = voltdb.getCatalogContext(); m_tracker = VoltDB.instance().getSiteTracker(); final int partitionId = m_tracker.getPartitionForSite(m_siteId); String txnlog_name = ExecutionSite.class.getName() + "." + m_siteId; m_txnlog = new VoltLogger(txnlog_name); m_rejoining = recovering; //lastCommittedTxnId = txnId; VoltDB.instance().getFaultDistributor(). registerFaultHandler(SiteFailureFault.SITE_FAILURE_EXECUTION_SITE, m_faultHandler, FaultType.SITE_FAILURE); // initialize the DR gateway File overflowDir = new File(VoltDB.instance().getCatalogContext().cluster.getVoltroot(), "dr_overflow"); m_partitionDRGateway = PartitionDRGateway.getInstance(partitionId, replicationActive, overflowDir); if (voltdb.getBackendTargetType() == BackendTarget.NONE) { ee = new MockExecutionEngine(); hsql = null; } else if (voltdb.getBackendTargetType() == BackendTarget.HSQLDB_BACKEND) { hsql = HsqlBackend.initializeHSQLBackend(m_siteId, m_context); ee = new MockExecutionEngine(); } else { if (serializedCatalog == null) { serializedCatalog = voltdb.getCatalogContext().catalog.serialize(); } hsql = null; ee = initializeEE(voltdb.getBackendTargetType(), serializedCatalog, txnId, configuredNumberOfPartitions); } m_systemProcedureContext = new SystemProcedureContext(); m_mailbox = mailbox; // allow dependency injection of the transaction queue implementation m_transactionQueue = (transactionQueue != null) ? transactionQueue : initializeTransactionQueue(m_siteId); // setup the procedure runner wrappers. if (runnerFactory != null) { runnerFactory.configure(this, m_systemProcedureContext); } m_loadedProcedures = new LoadedProcedureSet(this, runnerFactory, getSiteId(), siteIndex, m_tracker.m_numberOfPartitions); m_loadedProcedures.loadProcedures(m_context, voltdb.getBackendTargetType(), csp); int snapshotPriority = 6; if (m_context.cluster.getDeployment().get("deployment") != null) { snapshotPriority = m_context.cluster.getDeployment().get("deployment"). getSystemsettings().get("systemsettings").getSnapshotpriority(); } m_snapshotter = new SnapshotSiteProcessor(new Runnable() { @Override public void run() { m_mailbox.deliver(new PotentialSnapshotWorkMessage()); } }, snapshotPriority); final StatsAgent statsAgent = VoltDB.instance().getStatsAgent(); m_starvationTracker = new StarvationTracker(getCorrespondingSiteId()); statsAgent.registerStatsSource(SysProcSelector.STARVATION, m_siteId, m_starvationTracker); m_tableStats = new TableStats( getCorrespondingSiteId()); statsAgent.registerStatsSource(SysProcSelector.TABLE, m_siteId, m_tableStats); m_indexStats = new IndexStats(getCorrespondingSiteId()); statsAgent.registerStatsSource(SysProcSelector.INDEX, m_siteId, m_indexStats); } private RestrictedPriorityQueue initializeTransactionQueue(final long siteId) { // build an array of all the initiators Set<Long> allInitiators = m_tracker.getAllInitiators(); int initiatorCount = allInitiators.size(); final long[] initiatorIds = new long[initiatorCount]; int index = 0; for (long s : allInitiators) initiatorIds[index++] = s; // turn off the safety dance for single-node voltdb boolean useSafetyDance = m_tracker.getAllHosts().size() > 1; assert(m_mailbox != null); RestrictedPriorityQueue retval = new RestrictedPriorityQueue( initiatorIds, siteId, m_mailbox, useSafetyDance); return retval; } private ExecutionEngine initializeEE(BackendTarget target, String serializedCatalog, final long txnId, int configuredNumberOfPartitions) { String hostname = CoreUtils.getHostnameOrAddress(); ExecutionEngine eeTemp = null; try { if (target == BackendTarget.NATIVE_EE_JNI) { eeTemp = new ExecutionEngineJNI( m_context.cluster.getRelativeIndex(), getSiteId(), m_tracker.getPartitionForSite(getSiteId()), SiteTracker.getHostForSite(getSiteId()), hostname, m_context.cluster.getDeployment().get("deployment"). getSystemsettings().get("systemsettings").getMaxtemptablesize(), configuredNumberOfPartitions); eeTemp.loadCatalog( txnId, serializedCatalog); lastTickTime = EstTime.currentTimeMillis(); eeTemp.tick( lastTickTime, txnId); } else { // set up the EE over IPC eeTemp = new ExecutionEngineIPC( m_context.cluster.getRelativeIndex(), getSiteId(), m_tracker.getPartitionForSite(getSiteId()), SiteTracker.getHostForSite(getSiteId()), hostname, m_context.cluster.getDeployment().get("deployment"). getSystemsettings().get("systemsettings").getMaxtemptablesize(), target, VoltDB.instance().getConfig().m_ipcPorts.remove(0), m_tracker.m_numberOfPartitions); eeTemp.loadCatalog( 0, serializedCatalog); lastTickTime = EstTime.currentTimeMillis(); eeTemp.tick( lastTickTime, 0); } } // just print error info an bail if we run into an error here catch (final Exception ex) { hostLog.l7dlog( Level.FATAL, LogKeys.host_ExecutionSite_FailedConstruction.name(), new Object[] { getSiteId(), siteIndex }, ex); VoltDB.crashLocalVoltDB(ex.getMessage(), true, ex); } return eeTemp; } public boolean updateClusterState() { return true; } public boolean updateCatalog(String catalogDiffCommands, CatalogContext context, CatalogSpecificPlanner csp) { m_context = context; m_loadedProcedures.loadProcedures(m_context, VoltDB.getEEBackendType(), csp); //Necessary to quiesce before updating the catalog //so export data for the old generation is pushed to Java. ee.quiesce(lastCommittedTxnId); ee.updateCatalog( context.m_transactionId, catalogDiffCommands); return true; } /** * Primary run method that is invoked a single time when the thread is started. * Has the opportunity to do startup config. */ @Override public void run() { // enumerate site id (pad to 4 digits for sort) String name = "ExecutionSite: "; name += CoreUtils.hsIdToString(getSiteId()); Thread.currentThread().setName(name); try { // Only poll messaging layer if necessary. Allow the poll // to block if the execution site is truly idle. while (m_shouldContinue) { /* * If this partition is recovering, check for a permit and RPQ * readiness. If it is time, create a recovery processor and send * the initiate message. */ if (m_rejoining && !m_haveRecoveryPermit && !VoltDB.instance().getConfig().m_newRejoin) { Long safeTxnId = m_transactionQueue.safeToRecover(); if (safeTxnId != null && m_recoveryPermit.tryAcquire()) { m_haveRecoveryPermit = true; m_recoveryStartTime = System.currentTimeMillis(); m_recoveryProcessor = RecoverySiteProcessorDestination.createProcessor( m_context.database, m_tracker, ee, m_mailbox, m_siteId, m_onRejoinCompletion, m_recoveryMessageHandler); } } TransactionState currentTxnState = (TransactionState)m_transactionQueue.poll(); m_currentTransactionState = currentTxnState; if (currentTxnState == null) { // poll the messaging layer for a while as this site has nothing to do // this will likely have a message/several messages immediately in a heavy workload // Before blocking record the starvation VoltMessage message = m_mailbox.recv(); if (message == null) { //Will return null if there is no work, safe to block on the mailbox if there is no work boolean hadWork = (m_snapshotter.doSnapshotWork( ee, EstTime.currentTimeMillis() - lastCommittedTxnTime > 5) != null); /* * Do rejoin work here before it blocks on the mailbox * so that it can rejoin quickly without interrupting * load too much. * * Rejoin and snapshot should never happen at the same * time on a rejoining node, so it's fine to assign the * value to hadWork here. */ hadWork = doRejoinWork(); if (hadWork) { continue; } else { m_starvationTracker.beginStarvation(); message = m_mailbox.recvBlocking(5); m_starvationTracker.endStarvation(); } } // do periodic work tick(); if (message != null) { handleMailboxMessage(message); } else { //idle, do snapshot work m_snapshotter.doSnapshotWork(ee, EstTime.currentTimeMillis() - lastCommittedTxnTime > 5); } } if (currentTxnState != null) { /* * Before doing a transaction check if it is time to start recovery * or do recovery work. The recovery processor checks * if the txn is greater than X */ if (m_recoveryProcessor != null) { m_recoveryProcessor.doRecoveryWork(currentTxnState.txnId); } recursableRun(currentTxnState); } else if (m_recoveryProcessor != null) { /* * If there is no work in the system the minimum safe txnId is used to move * recovery forward. This works because heartbeats will move the minimum safe txnId * up even when there is no work for this partition. */ Long foo = m_transactionQueue.safeToRecover(); if (foo != null) { m_recoveryProcessor.doRecoveryWork(foo); } } } } catch (final RuntimeException e) { hostLog.l7dlog( Level.ERROR, LogKeys.host_ExecutionSite_RuntimeException.name(), e); throw e; } shutdown(); } /** * Do rejoin work, including streaming snapshot blocks and replaying logged * transactions. * * @return true if there was real work done. */ private boolean doRejoinWork() { boolean doneWork = false; /* * Wait until we know the txnId of the rejoin snapshot, then start * restoring the snapshot blocks. When the snapshot transfer is over, * the snapshot processor will be set to null. If the task log is not * null, replay any transactions logged. */ if (m_rejoinSnapshotProcessor != null && m_rejoinSnapshotTxnId != -1) { doneWork = restoreSnapshotForRejoin(); } else if (m_rejoinSnapshotProcessor == null && m_rejoinTaskLog != null) { /* * snapshot streaming is done, try to replay a batch of transactions * to speed up the rejoin process. it should be really fast. */ for (int i = 0; i < 1000; i++) { doneWork = replayTransactionForRejoin(); if (!doneWork) { // no more work to do for now break; } } checkTaskExecutionProgress(); } return doneWork; } /** * Check if the site is executing tasks faster than they come in. If the * site cannot keep up in a certain period of time, break rejoin. */ private void checkTaskExecutionProgress() { final long remainingTasks = m_loggedTaskCount - m_executedTaskCount; final long currTime = System.currentTimeMillis(); if (m_lastTimeMadeProgress == 0 || remainingTasks < m_remainingTasks) { m_lastTimeMadeProgress = currTime; } m_remainingTasks = remainingTasks; if (currTime > (m_lastTimeMadeProgress + MAX_BEHIND_DURATION)) { int duration = (int) (currTime - m_lastTimeMadeProgress) / 1000; VoltDB.crashLocalVoltDB("Site " + CoreUtils.hsIdToString(getSiteId()) + " has not made any progress in " + duration + " seconds, please reduce workload and " + "try pauseless rejoin again, or use " + "paused rejoin", false, null); } } /** * Restore snapshot blocks streamed from other site if there are any. * * @return true if there was real work done. */ private boolean restoreSnapshotForRejoin() { boolean doneWork = false; Pair<Integer, ByteBuffer> rejoinWork = m_rejoinSnapshotProcessor.poll(); if (rejoinWork != null) { int tableId = rejoinWork.getFirst(); ByteBuffer buffer = rejoinWork.getSecond(); VoltTable table = PrivateVoltTableFactory.createVoltTableFromBuffer(buffer.duplicate(), true); //m_recoveryLog.info("table " + tableId + ": " + table.toString()); loadTable(m_rejoinSnapshotTxnId, tableId, table); doneWork = true; } else if (m_rejoinSnapshotProcessor.isEOF()) { m_recoveryLog.debug("Rejoin snapshot transfer is finished"); m_rejoinSnapshotProcessor.close(); m_rejoinSnapshotBytes = m_rejoinSnapshotProcessor.bytesTransferred(); m_rejoinSnapshotProcessor = null; m_taskExeStartTime = System.currentTimeMillis(); /* * Don't notify the rejoin coordinator yet. The stream snapshot may * have not finished on all nodes, let the snapshot completion * monitor tell the rejoin coordinator. */ } return doneWork; } /** * Replays transactions logged for rejoin since the stream snapshot was * initiated. * * @return true if actual work was done, false otherwise */ private boolean replayTransactionForRejoin() { boolean doneWork = false; if (m_rejoinTaskLog == null) { return doneWork; } // get the next task to replay TransactionState ts = null; try { TransactionInfoBaseMessage msg = m_rejoinTaskLog.getNextMessage(); if (msg != null) { ts = new ReplayedTxnState(this, msg); } } catch (IOException e) { m_recoveryLog.error("Failed to replay logged transactions: " + e.getMessage()); } if (ts != null) { // Run the transaction, but don't send response recursableRun(ts); doneWork = true; m_recoveryLog.trace("Replayed " + ts.getNotice().getTxnId()); m_executedTaskCount++; } else { boolean rejoinCompleted = false; try { if (m_rejoinTaskLog.isEmpty() && m_rejoinSnapshotFinished) { rejoinCompleted = true; } } catch (IOException e) { m_recoveryLog.error("Failed to determine if the task log is empty: " + e.getMessage()); } if (rejoinCompleted) { try { m_rejoinTaskLog.close(); } catch (IOException e) { m_recoveryLog.error("Failed to close the task log:" + e.getMessage()); } m_onRejoinCompletion.run(); } } return doneWork; } /** * Construct a stream snapshot receiver and initiate rejoin snapshot. */ private void initiateRejoin(long rejoinCoordinatorHSId) { m_rejoinCoordinatorHSId = rejoinCoordinatorHSId; // Set rejoin permit m_haveRecoveryPermit = true; m_recoveryStartTime = System.currentTimeMillis(); // Construct a snapshot stream receiver Class<?> klass = MiscUtils.loadProClass("org.voltdb.rejoin.StreamSnapshotSink", "Rejoin", false); Constructor<?> constructor; try { constructor = klass.getConstructor(long.class); m_rejoinSnapshotProcessor = (RejoinSiteProcessor) constructor.newInstance(getSiteId()); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to construct stream snapshot receiver", true, e); } Pair<List<byte[]>, Integer> endPoints = m_rejoinSnapshotProcessor.initialize(); List<byte[]> addresses = endPoints.getFirst(); int port = endPoints.getSecond(); // Construct task log and start logging task messages int partition = getCorrespondingPartitionId(); File overflowDir = new File(VoltDB.instance().getCatalogContext().cluster.getVoltroot(), "rejoin_overflow"); Class<?> taskLogKlass = MiscUtils.loadProClass("org.voltdb.rejoin.TaskLogImpl", "Rejoin", false); Constructor<?> taskLogConstructor; try { taskLogConstructor = taskLogKlass.getConstructor(int.class, File.class); m_rejoinTaskLog = (TaskLog) taskLogConstructor.newInstance(partition, overflowDir); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to construct rejoin task log", true, e); } m_recoveryLog.info("Initiating rejoin from site " + CoreUtils.hsIdToString(getSiteId())); initiateRejoinSnapshot(addresses, port); } /** * Try to request a stream snapshot. * * @param addresses The addresses other replica can connect to. * @param port The port number other replica can connect to. */ private RejoinMessage initiateRejoinSnapshot(List<byte[]> addresses, int port) { // Pick a replica of the same partition to send us data int partition = getCorrespondingPartitionId(); long sourceSite = 0; List<Long> sourceSites = new ArrayList<Long>(m_tracker.getSitesForPartition(partition)); sourceSites.remove(getSiteId()); try { sourceSite = sourceSites.get(0); } catch (ArrayIndexOutOfBoundsException e) { VoltDB.crashLocalVoltDB("No source for partition " + partition, false, null); } // Initiate a snapshot with stream snapshot target String data = null; try { JSONStringer jsStringer = new JSONStringer(); jsStringer.object(); jsStringer.key("addresses").array(); for (byte[] addr : addresses) { InetAddress inetAddress = InetAddress.getByAddress(addr); jsStringer.value(inetAddress.getHostAddress()); } jsStringer.endArray(); jsStringer.key("port").value(port); // make this snapshot only contain data from this site m_recoveryLog.debug("Rejoin source for site " + CoreUtils.hsIdToString(getSiteId()) + " is " + CoreUtils.hsIdToString(sourceSite)); jsStringer.key("target_hsid").value(sourceSite); jsStringer.endObject(); data = jsStringer.toString(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to serialize to JSON", true, e); } /* * The handler will be called when a snapshot request response comes * back. It could potentially take a long time to successfully queue the * snapshot request, or it may fail. */ SnapshotResponseHandler handler = new SnapshotResponseHandler() { @Override public void handleResponse(ClientResponse resp) { if (resp == null) { VoltDB.crashLocalVoltDB("Failed to initiate rejoin snapshot", false, null); } else if (resp.getStatus() != ClientResponseImpl.SUCCESS) { VoltDB.crashLocalVoltDB("Failed to initiate rejoin snapshot: " + resp.getStatusString(), false, null); } VoltTable[] results = resp.getResults(); if (SnapshotUtil.didSnapshotRequestSucceed(results)) { long txnId = -1; String appStatus = resp.getAppStatusString(); if (appStatus == null) { VoltDB.crashLocalVoltDB("Rejoin snapshot request failed: " + resp.getStatusString(), false, null); } try { JSONObject jsObj = new JSONObject(appStatus); txnId = jsObj.getLong("txnId"); } catch (JSONException e) { VoltDB.crashLocalVoltDB("Failed to get the rejoin snapshot txnId", true, e); return; } // Send a message to self to avoid synchronization RejoinMessage msg = new RejoinMessage(txnId); m_mailbox.send(getSiteId(), msg); } else { VoltDB.crashLocalVoltDB("Snapshot request for rejoin failed", false, null); } } }; String nonce = "Rejoin_" + getSiteId() + "_" + System.currentTimeMillis(); SnapshotUtil.requestSnapshot(0l, "", nonce, false, SnapshotFormat.STREAM, data, handler); return null; } /** * Handle rejoin message * @param rm */ private void handleRejoinMessage(RejoinMessage rm) { Type type = rm.getType(); if (type == RejoinMessage.Type.INITIATION) { // rejoin coordinator says go ahead initiateRejoin(rm.m_sourceHSId); } else if (type == RejoinMessage.Type.REQUEST_RESPONSE) { m_rejoinSnapshotTxnId = rm.getSnapshotTxnId(); if (m_rejoinTaskLog != null) { m_rejoinTaskLog.setEarliestTxnId(m_rejoinSnapshotTxnId); } VoltDB.instance().getSnapshotCompletionMonitor() .addInterest(m_snapshotCompletionHandler); } else { VoltDB.crashLocalVoltDB("Unknown rejoin message type " + type, false, null); } } /** * Run the execution site execution loop, for tests currently. * Will integrate this in to the real run loop soon.. ish. */ public void runLoop(boolean loopUntilPoison) { while (m_shouldContinue) { TransactionState currentTxnState = (TransactionState)m_transactionQueue.poll(); m_currentTransactionState = currentTxnState; if (currentTxnState == null) { // poll the messaging layer for a while as this site has nothing to do // this will likely have a message/several messages immediately in a heavy workload VoltMessage message = m_mailbox.recv(); tick(); if (message != null) { handleMailboxMessage(message); } else if (!loopUntilPoison){ // Terminate run loop on empty mailbox AND no currentTxnState return; } } if (currentTxnState != null) { recursableRun(currentTxnState); } } } private void completeTransaction(TransactionState txnState) { if (m_txnlog.isTraceEnabled()) { m_txnlog.trace("FUZZTEST completeTransaction " + txnState.txnId); } if (!txnState.isReadOnly()) { assert(latestUndoToken != kInvalidUndoToken); assert(latestUndoToken >= txnState.getBeginUndoToken()); if (txnState.getBeginUndoToken() == kInvalidUndoToken) { if (m_rejoining == false) { throw new AssertionError("Non-recovering write txn has invalid undo state."); } } // release everything through the end of the current window. else if (latestUndoToken > txnState.getBeginUndoToken()) { ee.releaseUndoToken(latestUndoToken); } /* * send to DR Agent if conditions are right * * If the txnId is from before the process started, caused by command * log replay, then ignore it. */ StoredProcedureInvocation invocation = txnState.getInvocation(); long ts = TransactionIdManager.getTimestampFromTransactionId(txnState.txnId); if ((invocation != null) && (m_rejoining == false) && (ts > m_startupTime)) { if (!txnState.needsRollback()) { m_partitionDRGateway.onSuccessfulProcedureCall(txnState.txnId, invocation, txnState.getResults()); } } /* * log task message for rejoin if it's not a replayed transaction. * Replayed transactions do not send responses. */ if ((txnState.getRejoinState() == RejoinState.REJOINING) && m_rejoinTaskLog != null && !txnState.needsRollback()) { try { TransactionInfoBaseMessage base = txnState.getTransactionInfoBaseMessageForRejoinLog(); if (base != null) { // this is for multi-partition only // sysproc frags should be exempt if (base instanceof FragmentTaskLogMessage) { FragmentTaskLogMessage ftlm = (FragmentTaskLogMessage) base; if (ftlm.getFragmentTasks().size() > 0) { m_rejoinTaskLog.logTask(ftlm); m_loggedTaskCount++; } } // this is for single-partition only else if (base instanceof InitiateTaskMessage) { InitiateTaskMessage itm = (InitiateTaskMessage) base; // TODO: this is a pretty horrible hack if ((itm.getStoredProcedureName().startsWith("@") == false) || (itm.getStoredProcedureName().startsWith("@AdHoc") == true)) { m_rejoinTaskLog.logTask(itm); m_loggedTaskCount++; } } // the base message should hit one of the ifs above else { hostLog.error("Logged a notice of type: " + base.getClass().getCanonicalName() + "for replay."); assert(false); } } else { //hostLog.info("not logging transaction that didn't write"); } } catch (IOException e) { VoltDB.crashLocalVoltDB("Failed to log task message", true, e); } } // reset for error checking purposes txnState.setBeginUndoToken(kInvalidUndoToken); } // advance the committed transaction point. Necessary for both Export // commit tracking and for fault detection transaction partial-transaction // resolution. if (!txnState.needsRollback()) { if (txnState.txnId > lastCommittedTxnId) { lastCommittedTxnId = txnState.txnId; lastCommittedTxnTime = EstTime.currentTimeMillis(); if (!txnState.isSinglePartition() && !txnState.isReadOnly()) { lastKnownGloballyCommitedMultiPartTxnId = Math.max(txnState.txnId, lastKnownGloballyCommitedMultiPartTxnId); } } } } private void handleMailboxMessage(VoltMessage message) { if (m_rejoining == true && m_recoveryProcessor == null && m_currentTransactionState != null) { m_recoveryMessageHandler.handleMessage(message, m_currentTransactionState.txnId); } else { handleMailboxMessageNonRecursable(message); } } private void handleMailboxMessageNonRecursable(VoltMessage message) { /* * Don't listen to messages from unknown sources. The expectation is that they are from beyond * the grave */ if (!m_tracker.m_allSitesImmutable.contains(message.m_sourceHSId)) { hostLog.warn("Dropping message " + message + " because it is from a unknown site id " + CoreUtils.hsIdToString(message.m_sourceHSId)); return; } if (message instanceof TransactionInfoBaseMessage) { TransactionInfoBaseMessage info = (TransactionInfoBaseMessage)message; assertTxnIdOrdering(info); // Special case heartbeats which only update RPQ if (info instanceof HeartbeatMessage) { // use the heartbeat to unclog the priority queue if clogged long lastSeenTxnFromInitiator = m_transactionQueue.noteTransactionRecievedAndReturnLastSeen( info.getInitiatorHSId(), info.getTxnId(), true, ((HeartbeatMessage) info).getLastSafeTxnId()); // respond to the initiator with the last seen transaction HeartbeatResponseMessage response = new HeartbeatResponseMessage( m_siteId, lastSeenTxnFromInitiator, m_transactionQueue.getQueueState() == QueueState.BLOCKED_SAFETY); m_mailbox.send(info.getInitiatorHSId(), response); // we're done here (in the case of heartbeats) return; } else if (info instanceof InitiateTaskMessage) { m_transactionQueue.noteTransactionRecievedAndReturnLastSeen(info.getInitiatorHSId(), info.getTxnId(), false, ((InitiateTaskMessage) info).getLastSafeTxnId()); } //Participant notices are sent enmasse from the initiator to multiple partitions // and don't communicate any information about safe replication, hence DUMMY_LAST_SEEN_TXN_ID // it can be used for global ordering since it is a valid txnid from an initiator else if (info instanceof MultiPartitionParticipantMessage) { m_transactionQueue.noteTransactionRecievedAndReturnLastSeen(info.getInitiatorHSId(), info.getTxnId(), false, DtxnConstants.DUMMY_LAST_SEEN_TXN_ID); } // Every non-heartbeat notice requires a transaction state. TransactionState ts = m_transactionsById.get(info.getTxnId()); if (info instanceof CompleteTransactionMessage) { CompleteTransactionMessage complete = (CompleteTransactionMessage)info; if (ts != null) { ts.processCompleteTransaction(complete); } else { // if we're getting a CompleteTransactionMessage // and there's no transaction state, it's because // we were the cause of the rollback and we bailed // as soon as we signaled our failure to the coordinator. // Just generate an ack to keep the coordinator happy. if (complete.requiresAck()) { CompleteTransactionResponseMessage ctrm = new CompleteTransactionResponseMessage(complete, m_siteId); m_mailbox.send(complete.getCoordinatorHSId(), ctrm); } } return; } if (ts == null) { if (info.isSinglePartition()) { ts = new SinglePartitionTxnState(m_mailbox, this, info); } else { ts = new MultiPartitionParticipantTxnState(m_mailbox, this, info); } if (m_transactionQueue.add(ts)) { m_transactionsById.put(ts.txnId, ts); } else { hostLog.info( "Dropping txn " + ts.txnId + " data from failed initiatorSiteId: " + ts.initiatorHSId); } } if (ts != null) { if (message instanceof FragmentTaskMessage) { ts.createLocalFragmentWork((FragmentTaskMessage)message, false); } } } else if (message instanceof RecoveryMessage) { final RecoveryMessage rm = (RecoveryMessage)message; if (rm.recoveryMessagesAvailable()) { return; } assert(!m_rejoining); /* * Recovery site processor hasn't been cleaned up from the previous * rejoin. New rejoin request cannot be processed now. Telling the * rejoining site to retry later. */ if (m_recoveryProcessor != null || m_rejoinSnapshotProcessor != null) { m_recoveryLog.error("ExecutionSite is not ready to handle " + "recovery request from site " + CoreUtils.hsIdToString(rm.sourceSite())); RecoveryMessage recoveryResponse = new RecoveryMessage(false); m_mailbox.send(rm.sourceSite(), recoveryResponse); return; } final long recoveringPartitionTxnId = rm.txnId(); m_recoveryStartTime = System.currentTimeMillis(); m_recoveryLog.info( "Recovery initiate received at site " + CoreUtils.hsIdToString(m_siteId) + " from site " + CoreUtils.hsIdToString(rm.sourceSite()) + " requesting recovery start before txnid " + recoveringPartitionTxnId); m_recoveryProcessor = RecoverySiteProcessorSource.createProcessor( this, rm, m_context.database, m_tracker, ee, m_mailbox, m_siteId, m_onRejoinCompletion, m_recoveryMessageHandler); } else if (message instanceof RejoinMessage) { RejoinMessage rm = (RejoinMessage) message; handleRejoinMessage(rm); } else if (message instanceof FragmentResponseMessage) { FragmentResponseMessage response = (FragmentResponseMessage)message; TransactionState txnState = m_transactionsById.get(response.getTxnId()); // possible in rollback to receive an unnecessary response if (txnState != null) { assert (txnState instanceof MultiPartitionParticipantTxnState); txnState.processRemoteWorkResponse(response); } } else if (message instanceof CompleteTransactionResponseMessage) { CompleteTransactionResponseMessage response = (CompleteTransactionResponseMessage)message; TransactionState txnState = m_transactionsById.get(response.getTxnId()); // I believe a null txnState should eventually be impossible, let's // check for null for now if (txnState != null) { assert (txnState instanceof MultiPartitionParticipantTxnState); txnState.processCompleteTransactionResponse(response); } } else if (message instanceof ExecutionSiteNodeFailureMessage) { discoverGlobalFaultData((ExecutionSiteNodeFailureMessage)message); } else if (message instanceof CheckTxnStateCompletionMessage) { long txn_id = ((CheckTxnStateCompletionMessage)message).m_txnId; TransactionState txnState = m_transactionsById.get(txn_id); if (txnState != null) { assert(txnState instanceof MultiPartitionParticipantTxnState); ((MultiPartitionParticipantTxnState)txnState).checkWorkUnits(); } } else if (message instanceof RawProcessor.ExportInternalMessage) { RawProcessor.ExportInternalMessage exportm = (RawProcessor.ExportInternalMessage) message; ee.exportAction(exportm.m_m.isSync(), exportm.m_m.getAckOffset(), 0, exportm.m_m.getPartitionId(), exportm.m_m.getSignature()); } else if (message instanceof PotentialSnapshotWorkMessage) { m_snapshotter.doSnapshotWork(ee, false); } else if (message instanceof ExecutionSiteLocalSnapshotMessage) { hostLog.info("Executing local snapshot. Completing any on-going snapshots."); // first finish any on-going snapshot try { HashSet<Exception> completeSnapshotWork = m_snapshotter.completeSnapshotWork(ee); if (completeSnapshotWork != null && !completeSnapshotWork.isEmpty()) { for (Exception e : completeSnapshotWork) { hostLog.error("Error completing in progress snapshot.", e); } } } catch (InterruptedException e) { hostLog.warn("Interrupted during snapshot completion", e); } hostLog.info("Executing local snapshot. Creating new snapshot."); //Flush export data to the disk before the partition detection snapshot ee.quiesce(lastCommittedTxnId); // then initiate the local snapshot ExecutionSiteLocalSnapshotMessage snapshotMsg = (ExecutionSiteLocalSnapshotMessage) message; String nonce = snapshotMsg.nonce + "_" + snapshotMsg.m_roadblockTransactionId; SnapshotSaveAPI saveAPI = new SnapshotSaveAPI(); VoltTable startSnapshotting = saveAPI.startSnapshotting(snapshotMsg.path, nonce, SnapshotFormat.NATIVE, (byte) 0x1, snapshotMsg.m_roadblockTransactionId, null, m_systemProcedureContext, CoreUtils.getHostnameOrAddress()); if (SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() == -1 && snapshotMsg.crash) { String msg = "Executing local snapshot. Finished final snapshot. Shutting down. " + "Result: " + startSnapshotting.toString(); VoltDB.crashLocalVoltDB(msg, false, null); } } else if (message instanceof LocalObjectMessage) { LocalObjectMessage lom = (LocalObjectMessage)message; ((Runnable)lom.payload).run(); } else { hostLog.l7dlog(Level.FATAL, LogKeys.org_voltdb_dtxn_SimpleDtxnConnection_UnkownMessageClass.name(), new Object[] { message.getClass().getName() }, null); VoltDB.crashLocalVoltDB("No additional info.", false, null); } } private void assertTxnIdOrdering(final TransactionInfoBaseMessage notice) { // Because of our rollback implementation, fragment tasks can arrive // late. This participant can have aborted and rolled back already, // for example. // Additionally, commit messages for read-only MP transactions can // arrive after sneaked-in SP transactions have advanced the last // committed transaction point. A commit message is a fragment task // with a null payload. if (notice instanceof FragmentTaskMessage || notice instanceof CompleteTransactionMessage) { return; } if (notice.getTxnId() < lastCommittedTxnId) { StringBuilder msg = new StringBuilder(); msg.append("Txn ordering deadlock (DTXN) at site ").append(m_siteId).append(":\n"); msg.append(" txn ").append(lastCommittedTxnId).append(" ("); msg.append(TransactionIdManager.toString(lastCommittedTxnId)).append(" HB: ?"); msg.append(") before\n"); msg.append(" txn ").append(notice.getTxnId()).append(" ("); msg.append(TransactionIdManager.toString(notice.getTxnId())).append(" HB:"); msg.append(notice instanceof HeartbeatMessage).append(").\n"); TransactionState txn = m_transactionsById.get(notice.getTxnId()); if (txn != null) { msg.append("New notice transaction already known: " + txn.toString() + "\n"); } else { msg.append("New notice is for new or completed transaction.\n"); } msg.append("New notice of type: " + notice.getClass().getName()); VoltDB.crashLocalVoltDB(msg.toString(), false, null); } if (notice instanceof InitiateTaskMessage) { InitiateTaskMessage task = (InitiateTaskMessage)notice; assert (task.getInitiatorHSId() != getSiteId()); } } /* * When doing fault handling, it may not finish if their * are concurrent faults. New faults are added to this set. */ private final HashSet<Long> m_pendingFailedSites = new HashSet<Long>(); /** * Find the global multi-partition commit point and the global initiator point for the * failed host. * * @param failedHostId the host id of the failed node. */ private void discoverGlobalFaultData(ExecutionSiteNodeFailureMessage message) { //Keep it simple and don't try to recover on the recovering node. if (m_rejoining) { VoltDB.crashLocalVoltDB("Aborting recovery due to a remote node failure. Retry again.", false, null); } SiteTracker newTracker = VoltDB.instance().getSiteTracker(); HashSet<SiteFailureFault> failures = message.m_failedSites; // Fix context and associated site tracker first - need // an accurate topology to perform discovery. m_context = VoltDB.instance().getCatalogContext(); for (SiteFailureFault fault : failures) { for (Long siteId : fault.getSiteIds()) { if (!m_pendingFailedSites.add(siteId)) { VoltDB.crashLocalVoltDB("A site id shouldn't be distributed as a fault twice", true, null); } } } /* * Check and make sure the delta between site trackers matches the report of sites * that have failed e.g. we got the right one */ HashSet<Long> delta = new HashSet<Long>(m_tracker.m_allSitesImmutable); delta.removeAll(newTracker.m_allSitesImmutable); /* * In this case there were concurrent failures and the necessary matching site trackers * are not available for this set of failures bail out and wait for the next fault report * from the fault distributor that will contain a set that matches the new site tracker * Should the site tracker be versioned and come with the fault set? */ // if (!delta.equals(m_pendingFailedSites)) { // System.out.println("Bailing out because delta does not = pending failed sites"); // return; HashMap<Long, Long> initiatorSafeInitPoint = new HashMap<Long, Long>(); discoverGlobalFaultData_send(newTracker); Long multiPartitionCommitPoint = null; if (discoverGlobalFaultData_rcv( newTracker)) { multiPartitionCommitPoint = extractGlobalFaultData( newTracker, initiatorSafeInitPoint); } else { return; } // Use this agreed new-fault set to make PPD decisions. // Since this agreement process should eventually be moved to // the fault distributor - this is written with some intentional // feature envy. PPDPolicyDecision makePPDPolicyDecisions = VoltDB.instance().getFaultDistributor().makePPDPolicyDecisions(m_pendingFailedSites, newTracker); if (makePPDPolicyDecisions == PPDPolicyDecision.NodeFailure) { handleSiteFaults(false, m_pendingFailedSites, multiPartitionCommitPoint, initiatorSafeInitPoint); } else if (makePPDPolicyDecisions == PPDPolicyDecision.PartitionDetection) { handleSiteFaults(true, m_pendingFailedSites, multiPartitionCommitPoint, initiatorSafeInitPoint); } m_tracker = newTracker;//Get a snapshot of the site tracker // make sure the restricted priority queue knows about all of the up initiators // for most catalog changes this will do nothing // for rejoin, it will matter for (Long initiator : m_tracker.m_allInitiatorsImmutable) { m_transactionQueue.ensureInitiatorIsKnown(initiator); } m_pendingFailedSites.clear(); } private Long extractGlobalFaultData( SiteTracker newTracker, HashMap<Long, Long> initiatorSafeInitPoint) { if (!haveNecessaryFaultInfo(newTracker, m_pendingFailedSites, false)) { VoltDB.crashLocalVoltDB("Error extracting fault data", true, null); } long commitPoint = Long.MIN_VALUE; final int localPartitionId = newTracker.getPartitionForSite(m_siteId); Iterator<Map.Entry<Pair<Long, Long>, Pair<Long, Long>>> iter = m_failureSiteUpdateLedger.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<Pair<Long, Long>, Pair<Long, Long>> entry = iter.next(); final Pair<Long, Long> key = entry.getKey(); final Pair<Long, Long> value = entry.getValue(); final Long safeTxnId = value.getFirst(); final Long commitedTxnId = value.getSecond(); /* * Can receive messages from beyond the grave */ if (!m_tracker.m_allExecutionSitesImmutable.contains(key.getFirst())) { continue; } final int remotePartitionId = m_tracker.getPartitionForSite(key.getFirst()); commitPoint = Math.max(commitPoint, commitedTxnId); if (remotePartitionId == localPartitionId) { Long initiatorId = key.getSecond(); if (!initiatorSafeInitPoint.containsKey(initiatorId)) { initiatorSafeInitPoint.put( initiatorId, Long.MIN_VALUE); } initiatorSafeInitPoint.put( initiatorId, Math.max(initiatorSafeInitPoint.get(initiatorId), safeTxnId)); } } assert(commitPoint != Long.MIN_VALUE); return commitPoint; } /** * Send one message to each surviving execution site providing this site's * multi-partition commit point and this site's safe txnid * (the receiver will filter the later for its * own partition). Do this once for each failed initiator that we know about. * Sends all data all the time to avoid a need for request/response. */ private void discoverGlobalFaultData_send(SiteTracker newTracker) { Set<Long> survivors = newTracker.getAllSites(); m_recoveryLog.info("Sending fault data " + CoreUtils.hsIdCollectionToString(m_pendingFailedSites) + " to " + CoreUtils.hsIdCollectionToString(survivors) + " survivors with lastKnownGloballyCommitedMultiPartTxnId " + lastKnownGloballyCommitedMultiPartTxnId); for (Long site : m_pendingFailedSites) { /* * Check the queue for the data and get it from the ledger if necessary.\ * It might not even be in the ledger if the site has been failed * since recovery of this node began. */ Long txnId = m_transactionQueue.getNewestSafeTransactionForInitiator(site); FailureSiteUpdateMessage srcmsg = new FailureSiteUpdateMessage( m_pendingFailedSites, site, txnId != null ? txnId : Long.MIN_VALUE, lastKnownGloballyCommitedMultiPartTxnId); m_mailbox.send(com.google.common.primitives.Longs.toArray(survivors), srcmsg); } } /* * Key is source site, and initiator id * Value is safe txnid, last committed txnid */ private final HashMap<Pair<Long, Long>, Pair<Long, Long>> m_failureSiteUpdateLedger = new HashMap<Pair<Long, Long>, Pair<Long, Long>>(); /** * Collect the failure site update messages from all sites This site sent * its own mailbox the above broadcast the maximum is local to this site. * This also ensures at least one response. * * Concurrent failures can be detected by additional reports from the FaultDistributor * or a mismatch in the set of failed hosts reported in a message from another site */ private boolean discoverGlobalFaultData_rcv( SiteTracker newTracker) { java.util.ArrayList<FailureSiteUpdateMessage> messages = new java.util.ArrayList<FailureSiteUpdateMessage>(); long blockedOnReceiveStart = System.currentTimeMillis(); long lastReportTime = 0; do { VoltMessage m = m_mailbox.recvBlocking(new Subject[] { Subject.FAILURE, Subject.FAILURE_SITE_UPDATE }, 5); /* * If fault resolution takes longer then 10 seconds start logging */ final long now = System.currentTimeMillis(); if (now - blockedOnReceiveStart > 10000) { if (now - lastReportTime > 60000) { lastReportTime = System.currentTimeMillis(); haveNecessaryFaultInfo(newTracker, m_pendingFailedSites, true); } } //Invoke tick periodically to ensure that the last snapshot continues in the event that the failure //process does not complete if (m == null) { tick(); continue; } FailureSiteUpdateMessage fm = null; if (m.getSubject() == Subject.FAILURE_SITE_UPDATE.getId()) { fm = (FailureSiteUpdateMessage)m; messages.add(fm); m_failureSiteUpdateLedger.put( Pair.of(fm.m_sourceHSId, fm.m_initiatorForSafeTxnId), Pair.of(fm.m_safeTxnId, fm.m_committedTxnId)); } else if (m.getSubject() == Subject.FAILURE.getId()) { /* * If the fault distributor reports a new fault, redeliver the message to ourself and then abort so * that the process can restart. */ HashSet<SiteFailureFault> faults = ((ExecutionSiteNodeFailureMessage)m).m_failedSites; HashSet<Long> newFailedSiteIds = new HashSet<Long>(); for (SiteFailureFault fault : faults) { newFailedSiteIds.addAll((fault).getSiteIds()); } m_mailbox.deliverFront(m); m_recoveryLog.info("Detected a concurrent failure from FaultDistributor, new failed sites " + CoreUtils.hsIdCollectionToString(newFailedSiteIds)); return false; } m_recoveryLog.info("Received failure message from " + CoreUtils.hsIdToString(fm.m_sourceHSId) + " for failed sites " + CoreUtils.hsIdCollectionToString(fm.m_failedHSIds) + " for initiator id " + CoreUtils.hsIdToString(fm.m_initiatorForSafeTxnId) + " with commit point " + fm.m_committedTxnId + " safe txn id " + fm.m_safeTxnId); } while(!haveNecessaryFaultInfo(newTracker, m_pendingFailedSites, false)); return true; } private boolean haveNecessaryFaultInfo( SiteTracker newTracker, Set<Long> sitesBeingFailed, boolean log) { Set<Long> failingInitiators = new HashSet<Long>(sitesBeingFailed); failingInitiators.retainAll(m_tracker.getAllInitiators()); List<Pair<Long, Long>> missingMessages = new ArrayList<Pair<Long, Long>>(); for (long otherSite : newTracker.getAllSites()) { for (Long failingInitiator : failingInitiators) { Pair<Long, Long> key = Pair.of( otherSite, failingInitiator); if (!m_failureSiteUpdateLedger.containsKey(key)) { missingMessages.add(key); } } } if (log) { StringBuilder sb = new StringBuilder(); sb.append('['); boolean first = true; for (Pair<Long, Long> p : missingMessages) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(p.getFirst())); sb.append('-'); sb.append(CoreUtils.hsIdToString(p.getSecond())); } sb.append(']'); m_recoveryLog.warn("Failure resolution stalled waiting for ( ExecutionSite, Initiator ) " + "information: " + sb.toString()); } return missingMessages.isEmpty(); } /** * Process a node failure detection. * * Different sites can process UpdateCatalog sysproc and handleNodeFault() * in different orders. UpdateCatalog changes MUST be commutative with * handleNodeFault. * @param partitionDetected * * @param siteIds Hashset<Long> of host ids of failed nodes * @param globalCommitPoint the surviving cluster's greatest committed multi-partition transaction id * @param globalInitiationPoint the greatest transaction id acknowledged as globally * 2PC to any surviving cluster execution site by the failed initiator. * */ void handleSiteFaults(boolean partitionDetected, HashSet<Long> failedSites, long globalMultiPartCommitPoint, HashMap<Long, Long> initiatorSafeInitiationPoint) { HashSet<Long> failedInitiators = new HashSet<Long>(); HashSet<Integer> failedHosts = new HashSet<Integer>(); for (Long siteId : failedSites) { failedHosts.add(SiteTracker.getHostForSite(siteId)); } StringBuilder sb = new StringBuilder(); for (Integer hostId : failedHosts) { sb.append(hostId).append(' '); } final String failedHostsString = sb.toString(); if (m_txnlog.isTraceEnabled()) { m_txnlog.trace("FUZZTEST handleNodeFault " + failedHostsString + " with globalMultiPartCommitPoint " + globalMultiPartCommitPoint + " and safeInitiationPoints " + initiatorSafeInitiationPoint); } else { m_recoveryLog.info("Handling node faults " + failedHostsString + " with globalMultiPartCommitPoint " + globalMultiPartCommitPoint + " and safeInitiationPoints " + CoreUtils.hsIdKeyMapToString(initiatorSafeInitiationPoint)); } lastKnownGloballyCommitedMultiPartTxnId = globalMultiPartCommitPoint; // If possibly partitioned, run through the safe initiated transaction and stall // The unsafe txns from each initiators will be dropped. after this partition detected branch if (partitionDetected) { Long globalInitiationPoint = Long.MIN_VALUE; for (Long initiationPoint : initiatorSafeInitiationPoint.values()) { globalInitiationPoint = Math.max( initiationPoint, globalInitiationPoint); } m_recoveryLog.info("Scheduling snapshot after txnId " + globalInitiationPoint + " for cluster partition fault. Current commit point: " + this.lastCommittedTxnId); SnapshotSchedule schedule = m_context.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"); m_transactionQueue.makeRoadBlock( globalInitiationPoint, QueueState.BLOCKED_CLOSED, new ExecutionSiteLocalSnapshotMessage(globalInitiationPoint, schedule.getPath(), schedule.getPrefix(), true)); } // Fix safe transaction scoreboard in transaction queue // Not all of these are initiators, but it is safe... for (Long i : failedSites) { failedInitiators.add(i); m_transactionQueue.gotFaultForInitiator(i); } /* * List of txns that were not initiated or rolled back. * This will be synchronously logged to the command log * so they can be skipped at replay time. */ Set<Long> faultedTxns = new HashSet<Long>(); //System.out.println("Site " + m_siteId + " dealing with faultable txns " + m_transactionsById.keySet()); // Correct transaction state internals and commit // or remove affected transactions from RPQ and txnId hash. Iterator<Long> it = m_transactionsById.keySet().iterator(); while (it.hasNext()) { final long tid = it.next(); TransactionState ts = m_transactionsById.get(tid); ts.handleSiteFaults(failedSites); // Fault a transaction that was not globally initiated by a failed initiator if (initiatorSafeInitiationPoint.containsKey(ts.initiatorHSId) && ts.txnId > initiatorSafeInitiationPoint.get(ts.initiatorHSId) && failedSites.contains(ts.initiatorHSId)) { m_recoveryLog.info("Site " + m_siteId + " faulting non-globally initiated transaction " + ts.txnId); it.remove(); if (!ts.isReadOnly()) { faultedTxns.add(ts.txnId); } m_transactionQueue.faultTransaction(ts); } // Multipartition transaction without a surviving coordinator: // Commit a txn that is in progress and committed elsewhere. // (Must have lost the commit message during the failure.) // Otherwise, without a coordinator, the transaction can't // continue. Must rollback, if in progress, or fault it // from the queues if not yet started. else if (ts instanceof MultiPartitionParticipantTxnState && failedSites.contains(ts.coordinatorSiteId)) { MultiPartitionParticipantTxnState mpts = (MultiPartitionParticipantTxnState) ts; if (ts.isInProgress() && ts.txnId <= globalMultiPartCommitPoint) { m_recoveryLog.info("Committing in progress multi-partition txn " + ts.txnId + " even though coordinator was on a failed host because the txnId <= " + "the global multi-part commit point"); CompleteTransactionMessage ft = mpts.createCompleteTransactionMessage(false, false); ft.m_sourceHSId = m_siteId; m_mailbox.deliverFront(ft); } else if (ts.isInProgress() && ts.txnId > globalMultiPartCommitPoint) { m_recoveryLog.info("Rolling back in progress multi-partition txn " + ts.txnId + " because the coordinator was on a failed host and the txnId > " + "the global multi-part commit point"); CompleteTransactionMessage ft = mpts.createCompleteTransactionMessage(true, false); ft.m_sourceHSId = m_siteId; if (!ts.isReadOnly()) { faultedTxns.add(ts.txnId); } m_mailbox.deliverFront(ft); } else { m_recoveryLog.info("Faulting multi-part transaction " + ts.txnId + " because the coordinator was on a failed node"); it.remove(); if (!ts.isReadOnly()) { faultedTxns.add(ts.txnId); } m_transactionQueue.faultTransaction(ts); } } // If we're the coordinator, then after we clean up our internal // state due to a failed node, we need to poke ourselves to check // to see if all the remaining dependencies are satisfied. Do this // with a message to our mailbox so that happens in the // execution site thread else if (ts instanceof MultiPartitionParticipantTxnState && ts.coordinatorSiteId == m_siteId) { if (ts.isInProgress()) { m_mailbox.deliverFront(new CheckTxnStateCompletionMessage(ts.txnId, m_siteId)); } } } if (m_recoveryProcessor != null) { m_recoveryProcessor.handleSiteFaults(failedSites, m_tracker); } try { //Log it and acquire the completion permit from the semaphore VoltDB.instance().getCommandLog().logFault(failedInitiators, faultedTxns).acquire(); } catch (InterruptedException e) { VoltDB.crashLocalVoltDB("Interrupted while attempting to log a fault", true, e); } } private FragmentResponseMessage processSysprocFragmentTask( final TransactionState txnState, final HashMap<Integer,List<VoltTable>> dependencies, final long fragmentId, final FragmentResponseMessage currentFragResponse, final ParameterSet params) { // assume success. errors correct this assumption as they occur currentFragResponse.setStatus(FragmentResponseMessage.SUCCESS, null); ProcedureRunner runner = m_loadedProcedures.getSysproc(fragmentId); try { final DependencyPair dep = runner.executePlanFragment(txnState, dependencies, fragmentId, params); sendDependency(currentFragResponse, dep.depId, dep.dependency); } catch (final EEException e) { hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_ExceptionExecutingPF.name(), new Object[] { fragmentId }, e); currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, e); } catch (final SQLException e) { hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_ExceptionExecutingPF.name(), new Object[] { fragmentId }, e); currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, e); } catch (final Exception e) { // Just indicate that we failed completely currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, new SerializableException(e)); } return currentFragResponse; } private FragmentResponseMessage processCustomFragmentTask(TransactionState txnState, HashMap<Integer, List<VoltTable>> dependencies, FragmentResponseMessage currentFragResponse, ParameterSet params, String fragmentPlan, int outputDepId) { assert(fragmentPlan != null); // assume success. errors correct this assumption as they occur currentFragResponse.setStatus(FragmentResponseMessage.SUCCESS, null); try { int inputDepId = -1; // make dependency ids available to the execution engine if ((dependencies != null) && (dependencies.size() > 0)) { assert(dependencies.size() <= 1); if (dependencies.size() == 1) { inputDepId = dependencies.keySet().iterator().next(); } stashWorkUnitDependencies(dependencies); } VoltTable table = null; table = executeCustomPlanFragment(fragmentPlan, inputDepId, txnState.txnId, params, txnState.isReadOnly()); DependencyPair dep = new DependencyPair(outputDepId, table); sendDependency(currentFragResponse, dep.depId, dep.dependency); } catch (final EEException e) { hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_ExceptionExecutingPF.name(), e); currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, e); } catch (final SQLException e) { hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_ExceptionExecutingPF.name(), e); currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, e); } catch (final Exception e) { // Just indicate that we failed completely currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, new SerializableException(e)); } return currentFragResponse; } private void sendDependency( final FragmentResponseMessage currentFragResponse, final int dependencyId, final VoltTable dependency) { if (log.isTraceEnabled()) { log.l7dlog(Level.TRACE, LogKeys.org_voltdb_ExecutionSite_SendingDependency.name(), new Object[] { dependencyId }, null); } currentFragResponse.addDependency(dependencyId, dependency); } /* * Do snapshot work exclusively until there is no more. Also blocks * until the syncing and closing of snapshot data targets has completed. */ @Override public void initiateSnapshots(Deque<SnapshotTableTask> tasks, long txnId, int numLiveHosts) { m_snapshotter.initiateSnapshots(ee, tasks, txnId, numLiveHosts); } @Override public HashSet<Exception> completeSnapshotWork() throws InterruptedException { return m_snapshotter.completeSnapshotWork(ee); } /* * SiteConnection Interface (VoltProcedure -> ExecutionSite) */ @Override public long getCorrespondingSiteId() { return m_siteId; } @Override public int getCorrespondingPartitionId() { return m_tracker.getPartitionForSite(m_siteId); } @Override public int getCorrespondingHostId() { return SiteTracker.getHostForSite(m_siteId); } @Override public void loadTable( long txnId, String clusterName, String databaseName, String tableName, VoltTable data) throws VoltAbortException { Cluster cluster = m_context.cluster; if (cluster == null) { throw new VoltAbortException("cluster '" + clusterName + "' does not exist"); } Database db = cluster.getDatabases().get(databaseName); if (db == null) { throw new VoltAbortException("database '" + databaseName + "' does not exist in cluster " + clusterName); } Table table = db.getTables().getIgnoreCase(tableName); if (table == null) { throw new VoltAbortException("table '" + tableName + "' does not exist in database " + clusterName + "." + databaseName); } loadTable(txnId, table.getRelativeIndex(), data); } /** * @param txnId * @param data * @param table */ private void loadTable(long txnId, int tableId, VoltTable data) { long undo_token = getNextUndoToken(); ee.loadTable(tableId, data, txnId, lastCommittedTxnId, undo_token); ee.releaseUndoToken(undo_token); getNextUndoToken(); } @Override public VoltTable[] executeQueryPlanFragmentsAndGetResults( long[] planFragmentIds, int numFragmentIds, ParameterSet[] parameterSets, int numParameterSets, long txnId, boolean readOnly) throws EEException { return ee.executeQueryPlanFragmentsAndGetResults( planFragmentIds, numFragmentIds, parameterSets, numParameterSets, txnId, lastCommittedTxnId, readOnly ? Long.MAX_VALUE : getNextUndoToken()); } @Override public void simulateExecutePlanFragments(long txnId, boolean readOnly) { if (!readOnly) { // pretend real work was done getNextUndoToken(); } } /** * Continue doing runnable work for the current transaction. * If doWork() returns true, the transaction is over. * Otherwise, the procedure may have more java to run * or a dependency or fragment to collect from the network. * * doWork() can sneak in a new SP transaction. Maybe it would * be better if transactions didn't trigger other transactions * and those optimization decisions where made somewhere closer * to this code? */ @Override public Map<Integer, List<VoltTable>> recursableRun(TransactionState currentTxnState) { while (m_shouldContinue) { /* * when it's replaying transactions during rejoin, we want real work * to be done. If during rejoin, a transaction needs to send a * response, only send a dummy response. A replayed transaction * during rejoin needs real work to be done, but no response to be * sent. */ if (currentTxnState.doWork(m_rejoining)) { if (currentTxnState.needsRollback()) { rollbackTransaction(currentTxnState); } completeTransaction(currentTxnState); m_transactionsById.remove(currentTxnState.txnId); return null; } else if (currentTxnState.shouldResumeProcedure()){ Map<Integer, List<VoltTable>> retval = currentTxnState.getPreviousStackFrameDropDependendencies(); assert(retval != null); return retval; } // This is a bit ugly; more or less a straight-forward // extraction of the logic that used to be in // MultiPartitionParticipantTxnState.doWork() else if (currentTxnState.isBlocked() && !currentTxnState.isDone() && currentTxnState.isCoordinator() && currentTxnState.isReadOnly() && !currentTxnState.hasTransactionalWork()) { assert(!currentTxnState.isSinglePartition()); tryToSneakInASinglePartitionProcedure(); } else { VoltMessage message = m_mailbox.recvBlocking(5); tick(); if (message != null) { handleMailboxMessage(message); } else { //idle, do snapshot work m_snapshotter.doSnapshotWork(ee, EstTime.currentTimeMillis() - lastCommittedTxnTime > 5); } /** * If this site is the source for a recovering partition the recovering * partition might be blocked waiting for the txn to sync at from here. * Since this site is blocked on the multi-part waiting for the destination to respond * to a plan fragment it is a deadlock. * Poke the destination so that it will execute past the current * multi-part txn. */ if (m_recoveryProcessor != null) { m_recoveryProcessor.notifyBlockedOnMultiPartTxn( currentTxnState.txnId ); } } } // should only get here on shutdown return null; } /* * * SiteTransactionConnection Interface (TransactionState -> ExecutionSite) * */ @Override public SiteTracker getSiteTracker() { return m_tracker; } /** * Set the txn id from the WorkUnit and set/release undo tokens as * necessary. The DTXN currently has no notion of maintaining undo * tokens beyond the life of a transaction so it is up to the execution * site to release the undo data in the EE up until the current point * when the transaction ID changes. */ @Override public void beginNewTxn(TransactionState txnState) { if (m_txnlog.isTraceEnabled()) { m_txnlog.trace("FUZZTEST beginNewTxn " + txnState.txnId + " " + (txnState.isSinglePartition() ? "single" : "multi") + " " + (txnState.isReadOnly() ? "readonly" : "readwrite") + " " + (txnState.isCoordinator() ? "coord" : "part")); } if (!txnState.isReadOnly()) { assert(txnState.getBeginUndoToken() == kInvalidUndoToken); txnState.setBeginUndoToken(latestUndoToken); assert(txnState.getBeginUndoToken() != kInvalidUndoToken); } } public void rollbackTransaction(TransactionState txnState) { if (m_txnlog.isTraceEnabled()) { m_txnlog.trace("FUZZTEST rollbackTransaction " + txnState.txnId); } if (!txnState.isReadOnly()) { assert(latestUndoToken != kInvalidUndoToken); assert(txnState.getBeginUndoToken() != kInvalidUndoToken); assert(latestUndoToken >= txnState.getBeginUndoToken()); // don't go to the EE if no work was done if (latestUndoToken > txnState.getBeginUndoToken()) { ee.undoUndoToken(txnState.getBeginUndoToken()); } } } @Override public FragmentResponseMessage processFragmentTask( TransactionState txnState, final HashMap<Integer,List<VoltTable>> dependencies, final VoltMessage task) { final FragmentTaskMessage ftask = (FragmentTaskMessage) task; final FragmentResponseMessage currentFragResponse = new FragmentResponseMessage(ftask, getSiteId()); currentFragResponse.setStatus(FragmentResponseMessage.SUCCESS, null); if (!ftask.isSysProcTask()) { if (dependencies != null) { ee.stashWorkUnitDependencies(dependencies); } } for (int frag = 0; frag < ftask.getFragmentCount(); frag++) { final long fragmentId = ftask.getFragmentId(frag); final int outputDepId = ftask.getOutputDepId(frag); // this is a horrible performance hack, and can be removed with small changes // to the ee interface layer.. (rtb: not sure what 'this' encompasses...) ParameterSet params = null; final ByteBuffer paramData = ftask.getParameterDataForFragment(frag); if (paramData != null) { final FastDeserializer fds = new FastDeserializer(paramData); try { params = fds.readObject(ParameterSet.class); } catch (final IOException e) { hostLog.l7dlog( Level.FATAL, LogKeys.host_ExecutionSite_FailedDeserializingParamsForFragmentTask.name(), e); VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } } else { params = new ParameterSet(); } String fragmentPlan = ftask.getFragmentPlan(frag); if (fragmentPlan != null) { return processCustomFragmentTask(txnState, dependencies, currentFragResponse, params, fragmentPlan, outputDepId); } else if (ftask.isSysProcTask()) { return processSysprocFragmentTask(txnState, dependencies, fragmentId, currentFragResponse, params); } else { final int inputDepId = ftask.getOnlyInputDepId(frag); /* * Currently the error path when executing plan fragments * does not adequately distinguish between fatal errors and * abort type errors that should result in a roll back. * Assume that it is ninja: succeeds or doesn't return. * No roll back support. */ try { final VoltTable dependency = ee.executePlanFragment(fragmentId, inputDepId, params, txnState.txnId, lastCommittedTxnId, txnState.isReadOnly() ? Long.MAX_VALUE : getNextUndoToken()); sendDependency(currentFragResponse, outputDepId, dependency); } catch (final EEException e) { hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_ExceptionExecutingPF.name(), new Object[] { fragmentId }, e); currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, e); break; } catch (final SQLException e) { hostLog.l7dlog( Level.TRACE, LogKeys.host_ExecutionSite_ExceptionExecutingPF.name(), new Object[] { fragmentId }, e); currentFragResponse.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, e); break; } } } return currentFragResponse; } @Override public InitiateResponseMessage processInitiateTask( TransactionState txnState, final VoltMessage task) { final InitiateTaskMessage itask = (InitiateTaskMessage)task; final ProcedureRunner runner = m_loadedProcedures.procs.get(itask.getStoredProcedureName()); final InitiateResponseMessage response = new InitiateResponseMessage(itask); // feasible to receive a transaction initiated with an earlier catalog. if (runner == null) { response.setResults( new ClientResponseImpl(ClientResponse.GRACEFUL_FAILURE, new VoltTable[] {}, "Procedure does not exist: " + itask.getStoredProcedureName())); } else { try { Object[] callerParams = null; /* * Parameters are lazily deserialized. We may not find out until now * that the parameter set is corrupt */ try { callerParams = itask.getParameters(); } catch (RuntimeException e) { Writer result = new StringWriter(); PrintWriter pw = new PrintWriter(result); e.printStackTrace(pw); response.setResults( new ClientResponseImpl(ClientResponse.GRACEFUL_FAILURE, new VoltTable[] {}, "Exception while deserializing procedure params\n" + result.toString())); } if (callerParams != null) { ClientResponseImpl cr = null; // find the txn id visible to the proc long txnId = txnState.txnId; StoredProcedureInvocation invocation = txnState.getInvocation(); if ((invocation != null) && (invocation.getType() == ProcedureInvocationType.REPLICATED)) { txnId = invocation.getOriginalTxnId(); } // call the proc runner.setupTransaction(txnState); cr = runner.call(txnId, itask.getParameters()); response.setResults(cr, itask); // record the results of write transactions to the transaction state // this may be used to verify the DR replica cluster gets the same value // skip for multi-partition txns because only 1 of k+1 partitions will // have the real results if ((!itask.isReadOnly()) && itask.isSinglePartition()) { txnState.storeResults(cr); } } } catch (final ExpectedProcedureException e) { log.l7dlog( Level.TRACE, LogKeys.org_voltdb_ExecutionSite_ExpectedProcedureException.name(), e); response.setResults( new ClientResponseImpl( ClientResponse.GRACEFUL_FAILURE, new VoltTable[]{}, e.toString())); } catch (final Exception e) { // Should not be able to reach here. VoltProcedure.call caught all invocation target exceptions // and converted them to error responses. Java errors are re-thrown, and not caught by this // exception clause. A truly unexpected exception reached this point. Crash. It's a defect. hostLog.l7dlog( Level.ERROR, LogKeys.host_ExecutionSite_UnexpectedProcedureException.name(), e); VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } } log.l7dlog( Level.TRACE, LogKeys.org_voltdb_ExecutionSite_SendingCompletedWUToDtxn.name(), null); return response; } /** * Try to execute a single partition procedure if one is available in the * priority queue. * * @return false if there is no possibility for speculative work. */ private boolean tryToSneakInASinglePartitionProcedure() { // poll for an available message. don't block VoltMessage message = m_mailbox.recv(); tick(); // unclear if this necessary (rtb) if (message != null) { handleMailboxMessage(message); return true; } else { TransactionState nextTxn = (TransactionState)m_transactionQueue.peek(); // only sneak in single partition work if (nextTxn instanceof SinglePartitionTxnState) { boolean success = nextTxn.doWork(m_rejoining); assert(success); return true; } else { // multipartition is next or no work return false; } } } public PartitionDRGateway getPartitionDRGateway() { return m_partitionDRGateway; } @Override public long getReplicatedDMLDivisor() { return m_tracker.m_numberOfPartitions; } public void notifySitesAdded(final SiteTracker st) { Runnable r = new Runnable() { @Override public void run() { if (!m_pendingFailedSites.isEmpty()) { return; } /* * Failure processing may pick up the site tracker eagerly */ if (st.m_version <= m_tracker.m_version){ return; } m_tracker = st; // make sure the restricted priority queue knows about all of the up initiators // for most catalog changes this will do nothing // for rejoin, it will matter for (Long initiator : m_tracker.m_allInitiatorsImmutable) { m_transactionQueue.ensureInitiatorIsKnown(initiator); } } }; LocalObjectMessage lom = new LocalObjectMessage(r); lom.m_sourceHSId = m_siteId; m_mailbox.deliver(lom); } // do-nothing implementation of IV2 SiteProcedeConnection API @Override public void truncateUndoLog(boolean rollback, long token, long txnId) { throw new RuntimeException("Unsupported IV2-only API."); } // do-nothing implementation of IV2 sysproc fragment API. @Override public DependencyPair executePlanFragment( TransactionState txnState, Map<Integer, List<VoltTable>> dependencies, long fragmentId, ParameterSet params) { throw new RuntimeException("Unsupported IV2-only API."); } @Override public VoltTable executePlanFragment(long planFragmentId, int inputDepId, ParameterSet parameterSet, long txnId, boolean readOnly) throws EEException { return ee.executePlanFragment(planFragmentId, inputDepId, parameterSet, txnId, lastCommittedTxnId, readOnly ? Long.MAX_VALUE : getNextUndoToken()); } @Override public void stashWorkUnitDependencies(Map<Integer, List<VoltTable>> dependencies) { ee.stashWorkUnitDependencies(dependencies); } @Override public HsqlBackend getHsqlBackendIfExists() { return hsql; } @Override public long[] getUSOForExportTable(String signature) { return ee.getUSOForExportTable(signature); } @Override public VoltTable executeCustomPlanFragment(String plan, int inputDepId, long txnId, ParameterSet params, boolean readOnly) { return ee.executeCustomPlanFragment(plan, inputDepId, txnId, lastCommittedTxnId, readOnly ? Long.MAX_VALUE : getNextUndoToken(), params); } @Override public void toggleProfiler(int toggle) { ee.toggleProfiler(toggle); } @Override public void quiesce() { ee.quiesce(lastCommittedTxnId); } @Override public void exportAction(boolean syncAction, int ackOffset, Long sequenceNumber, Integer partitionId, String tableSignature) { ee.exportAction(syncAction, ackOffset, sequenceNumber, partitionId, tableSignature); } @Override public VoltTable[] getStats(SysProcSelector selector, int[] locators, boolean interval, Long now) { return ee.getStats(selector, locators, interval, now); } }
package org.voltdb; import java.lang.reflect.Constructor; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.Pair; import com.google.common.base.Charsets; import com.google.common.base.Throwables; /** * Class that maps object values to partitions. It's rather simple * really. It'll get more complicated if you give it time. */ public abstract class TheHashinator { public static enum HashinatorType { LEGACY(0, LegacyHashinator.class) , ELASTIC(1, ElasticHashinator.class); public final int typeId; public final Class<? extends TheHashinator> hashinatorClass; private HashinatorType(int typeId, Class<? extends TheHashinator> hashinatorClass) { this.typeId = typeId; this.hashinatorClass = hashinatorClass; } public int typeId() { return typeId; } }; private static final VoltLogger hostLogger = new VoltLogger("HOST"); /* * Stamped instance, version associated with hash function, only update for newer versions */ private static final AtomicReference<Pair<Long, ? extends TheHashinator>> instance = new AtomicReference<Pair<Long, ? extends TheHashinator>>(); /** * Initialize TheHashinator with the specified implementation class and configuration. * The starting version number will be 0. */ public static void initialize(Class<? extends TheHashinator> hashinatorImplementation, byte config[]) { instance.set(Pair.of(0L, constructHashinator( hashinatorImplementation, config))); } /** * Helper method to do the reflection boilerplate to call the constructor * of the selected hashinator and convert the exceptions to runtime excetions. */ public static TheHashinator constructHashinator( Class<? extends TheHashinator> hashinatorImplementation, byte config[]) { try { Constructor<? extends TheHashinator> constructor = hashinatorImplementation.getConstructor(byte[].class); return constructor.newInstance(config); } catch (Exception e) { Throwables.propagate(e); } return null; } /** * Protected methods that implement hashination of specific data types. * Only string/varbinary and integer hashination is supported. String/varbinary * get the same handling once they the string is converted to UTF-8 binary * so there is only one protected method for bytes. * * Longs are converted to bytes in little endian order for elastic, modulus for legacy. */ abstract protected int pHashinateLong(long value); abstract protected int pHashinateBytes(byte[] bytes); abstract protected Pair<HashinatorType, byte[]> pGetCurrentConfig(); abstract protected Map<Long, Integer> pPredecessors(int partition); abstract protected Pair<Long, Integer> pPredecessor(int partition, long token); abstract protected Map<Long, Long> pGetRanges(int partition); /** * Given a long value, pick a partition to store the data. It's only called for legacy * hashinator, elastic hashinator hashes all types the same way through hashinateBytes(). * * @param value The value to hash. * @param partitionCount The number of partitions to choose from. * @return A value between 0 and partitionCount-1, hopefully pretty evenly * distributed. */ static int hashinateLong(long value) { return instance.get().getSecond().pHashinateLong(value); } /** * Given an byte[] bytes, pick a partition to store the data. * * @param value The value to hash. * @param partitionCount The number of partitions to choose from. * @return A value between 0 and partitionCount-1, hopefully pretty evenly * distributed. */ static int hashinateBytes(byte[] bytes) { if (bytes == null) { return 0; } else { return instance.get().getSecond().pHashinateBytes(bytes); } } /** * Given an object, map it to a partition. * @param obj The object to be mapped to a partition. * @return The id of the partition desired. */ public static int hashToPartition(Object obj) { HashinatorType type = getConfiguredHashinatorType(); if (type == HashinatorType.LEGACY) { // Annoying, legacy hashes numbers and bytes differently, need to preserve that. if (obj == null || VoltType.isNullVoltType(obj)) { return 0; } else if (obj instanceof Long) { long value = ((Long) obj).longValue(); return hashinateLong(value); } else if (obj instanceof Integer) { long value = ((Integer)obj).intValue(); return hashinateLong(value); } else if (obj instanceof Short) { long value = ((Short)obj).shortValue(); return hashinateLong(value); } else if (obj instanceof Byte) { long value = ((Byte)obj).byteValue(); return hashinateLong(value); } } return hashinateBytes(valueToBytes(obj)); } /** * Converts the object into bytes for hashing. * @param obj * @return null if the obj is null or is a Volt null type. */ public static byte[] valueToBytes(Object obj) { long value = 0; byte[] retval = null; if (VoltType.isNullVoltType(obj)) { return null; } else if (obj instanceof Long) { value = ((Long) obj).longValue(); } else if (obj instanceof String ) { retval = ((String) obj).getBytes(Charsets.UTF_8); } else if (obj instanceof Integer) { value = ((Integer)obj).intValue(); } else if (obj instanceof Short) { value = ((Short)obj).shortValue(); } else if (obj instanceof Byte) { value = ((Byte)obj).byteValue(); } else if (obj instanceof byte[]) { retval = (byte[]) obj; } if (retval == null) { ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.LITTLE_ENDIAN); buf.putLong(value); retval = buf.array(); } return retval; } /** * Given the type of the targeting partition parameter and an object, * coerce the object to the correct type and hash it. * @return The partition best set up to execute the procedure. * @throws Exception */ public static int getPartitionForParameter(int partitionType, Object invocationParameter) throws Exception { final VoltType partitionParamType = VoltType.get((byte)partitionType); // Special case: if the user supplied a string for a number column, // try to do the conversion. This makes it substantially easier to // load CSV data or other untyped inputs that match DDL without // requiring the loader to know precise the schema. if ((invocationParameter != null) && (invocationParameter.getClass() == String.class) && (partitionParamType.isNumber())) { invocationParameter = ParameterConverter.stringToLong( invocationParameter, partitionParamType.classFromType()); } return hashToPartition(invocationParameter); } /** * Update the hashinator in a thread safe manner with a newer version of the hash function. * A version number must be provided and the new config will only be used if it is greater than * the current version of the hash function. */ public static void updateHashinator( Class<? extends TheHashinator> hashinatorImplementation, long version, byte config[]) { while (true) { final Pair<Long, ? extends TheHashinator> snapshot = instance.get(); if (version > snapshot.getFirst()) { Pair<Long, ? extends TheHashinator> update = Pair.of(version, constructHashinator(hashinatorImplementation, config)); if (instance.compareAndSet(snapshot, update)) return; } else { return; } } } /** * By default returns LegacyHashinator.class, but for development another hashinator * can be specified using the environment variable HASHINATOR */ public static Class<? extends TheHashinator> getConfiguredHashinatorClass() { HashinatorType type = getConfiguredHashinatorType(); switch (type) { case LEGACY: return LegacyHashinator.class; case ELASTIC: return ElasticHashinator.class; } throw new RuntimeException("Should not reach here"); } private static volatile HashinatorType configuredHashinatorType = null; /** * By default returns HashinatorType.LEGACY, but for development another hashinator * can be specified using the environment variable or the Java property HASHINATOR */ public static HashinatorType getConfiguredHashinatorType() { if (configuredHashinatorType != null) { return configuredHashinatorType; } String hashinatorType = System.getenv("HASHINATOR"); if (hashinatorType == null) { hashinatorType = System.getProperty("HASHINATOR", HashinatorType.LEGACY.name()); } if (hostLogger.isDebugEnabled()) { hostLogger.debug("Overriding hashinator to use " + hashinatorType); } configuredHashinatorType = HashinatorType.valueOf(hashinatorType.trim().toUpperCase()); return configuredHashinatorType; } public static void setConfiguredHashinatorType(HashinatorType type) { configuredHashinatorType = type; } /** * Add new partitions to create a new hashinator configuration. */ public static byte[] addPartitions(Map<Long, Integer> tokensToPartitions) { HashinatorType type = getConfiguredHashinatorType(); switch (type) { case LEGACY: throw new RuntimeException("Legacy hashinator doesn't support adding partitions"); case ELASTIC: return ElasticHashinator.addPartitions(instance.get().getSecond(), tokensToPartitions); } throw new RuntimeException("Should not reach here"); } /** * Get a basic configuration for the currently selected hashinator type based * on the current partition count. If Elastic is in play */ public static byte[] getConfigureBytes(int partitionCount) { HashinatorType type = getConfiguredHashinatorType(); switch (type) { case LEGACY: return LegacyHashinator.getConfigureBytes(partitionCount); case ELASTIC: return ElasticHashinator.getConfigureBytes(partitionCount, ElasticHashinator.DEFAULT_TOKENS_PER_PARTITION); } throw new RuntimeException("Should not reach here"); } public static Pair<HashinatorType, byte[]> getCurrentConfig() { return instance.get().getSecond().pGetCurrentConfig(); } public static Map<Long, Integer> predecessors(int partition) { return instance.get().getSecond().pPredecessors(partition); } public static Pair<Long, Integer> predecessor(int partition, long token) { return instance.get().getSecond().pPredecessor(partition, token); } /** * Get the ranges the given partition is assigned to. * @param partition * @return A map of ranges, the key is the start of a range, the value is * the corresponding end. Ranges returned in the map are [start, end). * The ranges may or may not be contiguous. */ public static Map<Long, Long> getRanges(int partition) { return instance.get().getSecond().pGetRanges(partition); } }
package evaluation.evalBench.io; import java.awt.AWTException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Date; import javax.imageio.ImageIO; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; @XmlAccessorType(XmlAccessType.NONE) public class OutputManager { /** * {@link java.util.Formatter format string} for output directory. The * directory will be created if it does not exist. Arguments: * * <li>participant id <li>current date and time * * <p> * See {@link java.util.Formatter} */ @XmlElement private String directoryFormat = "evaluationJournal/%1$s_%2$tF"; /** * {@link java.util.Formatter format string} for journal file name. * Arguments: * * <li>participant id <li>session title <li>current date and time * * <p> * See {@link java.util.Formatter} */ @XmlElement private String journalPrefix = "%s_%s_%3$tH%3$tM%3$tS"; /** * {@link java.util.Formatter format string} for log file name. * Arguments: * * <li>participant id <li>session title <li>current date and time * * <p> * See {@link java.util.Formatter} */ @XmlElement private String logPrefix = "%s_%s_%3$tH%3$tM%3$tS"; /** * {@link java.util.Formatter format string} for screen shot file names. * Arguments: * * <li>participant id <li>task id <li>current date and time * * <p> * See {@link java.util.Formatter} */ @XmlElement private String screenshotName = "%2$s_%1$s_%3$tH%3$tM%3$tS"; @XmlElement private String stateFileName = "%2$s_%1$s_%3$tH%3$tM%3$tS"; @XmlTransient private File outputDirectory; @XmlTransient private String participantId; @XmlTransient private Robot robot = null; public OutputManager(String participantId) { this.participantId = participantId; } private void checkDirectory() { if (outputDirectory == null) { String dirName = String.format(directoryFormat, participantId, new Date()); outputDirectory = new File(dirName); } if (!outputDirectory.canWrite()) { try { boolean success = outputDirectory.mkdirs(); if (success) { Logger.getLogger(OutputManager.class).info( "Directory: " + outputDirectory.getPath() + " created"); } else { Logger.getLogger(OutputManager.class).warn( "Could not create directory: " + outputDirectory.getPath() + "!"); } } catch (SecurityException e) { Logger.getLogger(OutputManager.class).warn( "Directory creation error.", e); } } } public File getOutputDirectory() { return new File (outputDirectory, ""); } public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } public File getJournalFile(String sessionTitle, String suffix) { checkDirectory(); String fileName = String.format(journalPrefix, participantId, sessionTitle, new Date()) + suffix; return new File(outputDirectory, fileName); } public File getLogFile(String sessionTitle, String suffix) { checkDirectory(); String fileName = String.format(logPrefix, participantId, sessionTitle, new Date()) + suffix; return new File(outputDirectory, fileName); } public File getStateFile(String taskId, Date date, String suffix) { checkDirectory(); String fileName = String.format(stateFileName, participantId, taskId, date) + suffix; return new File(outputDirectory, fileName); } public String takeScreenshot(String taskId) { return takeScreenshot(taskId, new Date()); } public String takeScreenshot(String taskId, Date date) { String fileName = String.format(screenshotName, participantId, taskId, date) + ".png"; try { if (robot == null) { robot = new Robot(); } // TODO consider multi display -- see code from TimeRider // saving only main frame is not possible <- application dependent Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit() .getScreenSize()); BufferedImage bufferedImage = robot .createScreenCapture(captureSize); File outputFile = new File(outputDirectory, fileName); ImageIO.write(bufferedImage, "png", outputFile); } catch (AWTException e) { Logger.getLogger(OutputManager.class).warn( "Could not take a screenshot for the task"); } catch (IOException e) { Logger.getLogger(OutputManager.class).warn( "Could not save the screenshot for the task"); } return fileName; } /** * @param args */ public static void main(String[] args) { // TODO remove experimental main method BasicConfigurator.configure(); OutputManager o = new OutputManager("9725123"); o.checkDirectory(); System.out.println(o.getJournalFile("scatter", "_journal.csv")); } }
package foam.nanos.crunch; import foam.core.FObject; import foam.core.X; import foam.dao.ArraySink; import foam.dao.DAO; import foam.mlang.predicate.Predicate; import foam.nanos.auth.Subject; import foam.nanos.auth.User; import foam.nanos.logger.Logger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Queue; import static foam.mlang.MLang.*; public class ServerCrunchService implements CrunchService { public List getGrantPath(X x, String rootId) { return getCapabilityPath(x, rootId, true); } public List getCapabilityPath(X x, String rootId, boolean filterGrantedUCJ) { Logger logger = (Logger) x.get("logger"); DAO prerequisiteDAO = (DAO) x.get("prerequisiteCapabilityJunctionDAO"); DAO capabilityDAO = (DAO) x.get("capabilityDAO"); // Lookup for indices of previously observed capabilities List<String> alreadyListed = new ArrayList<String>(); // List of capabilities required to grant the desired capability. // Throughout the traversial algorithm this list starts with parents of // prerequisites appearing earlier in the list. Before returning, this // list is reversed so that the caller receives capabilities in order of // expected completion (i.e. pre-order traversial) List grantPath = new ArrayList<>(); Queue<String> nextSources = new ArrayDeque<String>(); nextSources.add(rootId); // Doing this instead of "this" could prevent unexpected behaviour // in the incident CrunchService's getJunction method is decorated CrunchService crunchService = (CrunchService) x.get("crunchService"); while ( nextSources.size() > 0 ) { String sourceCapabilityId = nextSources.poll(); if ( ! filterGrantedUCJ ) { UserCapabilityJunction ucj = crunchService.getJunction(x, sourceCapabilityId); if ( ucj != null && ucj.getStatus() == CapabilityJunctionStatus.GRANTED ) { continue; } } if ( alreadyListed.contains(sourceCapabilityId) ) continue; // Add capability to grant path, and remember index in case it's replaced Capability cap = (Capability) capabilityDAO.find(sourceCapabilityId); alreadyListed.add(sourceCapabilityId); if ( cap instanceof MinMaxCapability && ! rootId.equals(sourceCapabilityId) ) { List minMaxArray = new ArrayList<>(); // Manually grab the direct prereqs to the MinMaxCapability List prereqs = ( (ArraySink) prerequisiteDAO .where(AND( EQ(CapabilityCapabilityJunction.SOURCE_ID, sourceCapabilityId), NOT(IN(CapabilityCapabilityJunction.TARGET_ID, alreadyListed)) )) .select(new ArraySink()) ).getArray(); for ( int i = prereqs.size() - 1; i >= 0; i CapabilityCapabilityJunction prereq = (CapabilityCapabilityJunction) prereqs.get(i); var prereqGrantPath = this.getGrantPath(x, prereq.getTargetId()); // Essentially we reserve arrays to denote ANDs and ORs, must be at least 2 elements if ( prereqGrantPath.size() > 1 ) minMaxArray.add(prereqGrantPath); else minMaxArray.add(prereqGrantPath.get(0)); } /** Format of a min max for getGrantPath [[prereqsChoiceA, choiceA], [prereqsChoiceB,choiceB], minMaxCapa] */ minMaxArray.add(cap); /** Format of a min max for getGrantPath as a prereq for another capability [[[prereqsChoiceA, choiceA], [prereqsChoiceB,choiceB], minMaxCap],cap] */ grantPath.add(minMaxArray); continue; } grantPath.add(cap); // Enqueue prerequisites for adding to grant path List prereqs = ( (ArraySink) prerequisiteDAO .where(AND( EQ(CapabilityCapabilityJunction.SOURCE_ID, sourceCapabilityId), NOT(IN(CapabilityCapabilityJunction.TARGET_ID, alreadyListed)) )) .select(new ArraySink()) ).getArray(); for ( int i = prereqs.size() - 1; i >= 0; i CapabilityCapabilityJunction prereq = (CapabilityCapabilityJunction) prereqs.get(i); nextSources.add(prereq.getTargetId()); } } Collections.reverse(grantPath); return grantPath; } // Return capability path for multiple prerequisites without duplicates. public List getMultipleCapabilityPath( X x, String[] capabilityIds, boolean filterGrantedUCJ ) { Set alreadyListed = new HashSet<String>(); List multiplePath = new ArrayList(); for ( String capId : capabilityIds ) { List crunchyPath = getCapabilityPath(x, capId, filterGrantedUCJ); for ( Object obj : crunchyPath ) { Capability cap = null; if ( obj instanceof List ) { List list = (List) obj; cap = (Capability) list.get(list.size() - 1); } else { cap = (Capability) obj; } if ( alreadyListed.contains(cap.getId()) ) continue; multiplePath.add(obj); } } return multiplePath; } public UserCapabilityJunction getJunction(X x, String capabilityId) { Subject subject = (Subject) x.get("subject"); return this.getJunctionForSubject(x, capabilityId, subject); } public UserCapabilityJunction getJunctionForSubject( X x, String capabilityId, Subject subject ) { User user = subject.getUser(); User realUser = subject.getRealUser(); Predicate acjPredicate = INSTANCE_OF(AgentCapabilityJunction.class); Predicate targetPredicate = EQ(UserCapabilityJunction.TARGET_ID, capabilityId); try { DAO userCapabilityJunctionDAO = (DAO) x.get("userCapabilityJunctionDAO"); Predicate associationPredicate = OR( AND( NOT(acjPredicate), ( user != realUser ) ? OR( EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()), EQ(UserCapabilityJunction.SOURCE_ID, user.getId()) ) : EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()) ), AND( acjPredicate, EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()), EQ(AgentCapabilityJunction.EFFECTIVE_USER, user.getId()) ) ); UserCapabilityJunction ucj = (UserCapabilityJunction) userCapabilityJunctionDAO.find(AND(associationPredicate,targetPredicate)); if ( ucj != null ) { return ucj; } } catch ( Exception e ) { Logger logger = (Logger) x.get("logger"); logger.error("getJunction", capabilityId, e); } return null; } public void updateJunction(X x, String capabilityId, FObject data) { Subject subject = (Subject) x.get("subject"); UserCapabilityJunction ucj = this.getJunction(x, capabilityId); if ( ucj == null ) { // Need Capability to associate UCJ correctly DAO capabilityDAO = (DAO) x.get("capabilityDAO"); Capability cap = (Capability) capabilityDAO.find(capabilityId); if ( cap == null ) { throw new RuntimeException(String.format( "Capability with id '%s' not found", capabilityId )); } AssociatedEntity associatedEntity = cap.getAssociatedEntity(); boolean isAssociation = associatedEntity == AssociatedEntity.ACTING_USER; User associatedUser = associatedEntity == AssociatedEntity.USER ? subject.getUser() : subject.getRealUser() ; ucj = isAssociation ? new AgentCapabilityJunction.Builder(x) .setSourceId(associatedUser.getId()) .setTargetId(capabilityId) .setEffectiveUser(subject.getUser().getId()) .build() : new UserCapabilityJunction.Builder(x) .setSourceId(associatedUser.getId()) .setTargetId(capabilityId) .build() ; } if ( data != null ) { ucj.setData(data); } DAO userCapabilityJunctionDAO = (DAO) x.get("userCapabilityJunctionDAO"); userCapabilityJunctionDAO.inX(x).put(ucj); } public void maybeIntercept(X x, String[] capabilityOptions) { if ( capabilityOptions.length < 1 ) { Logger logger = (Logger) x.get("logger"); logger.warning("crunchService.maybeIntercept() performed with empty list"); return; } // Check that at least one capability option is satisfied boolean satisfied = false; for ( String capId : capabilityOptions ) { UserCapabilityJunction ucj = this.getJunction(x, capId); if ( ucj != null && ( // TODO: use getStatus().getBroadStatus() when available ucj.getStatus() == CapabilityJunctionStatus.GRANTED || ucj.getStatus() == CapabilityJunctionStatus.GRACE_PERIOD ) ) { satisfied = true; break; } } // Throw a capability intercept if none were satisfied if ( ! satisfied ) { CapabilityRuntimeException ex = new CapabilityRuntimeException( "Missing a required capability." ); for ( String capId : capabilityOptions ) { ex.addCapabilityId(capId); } throw ex; } } }
package org.voltcore.utils; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Inet4Address; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import jsr166y.LinkedTransferQueue; import org.voltcore.logging.VoltLogger; import org.voltcore.network.ReverseDNSCache; import com.google_voltpatches.common.base.Preconditions; import com.google_voltpatches.common.base.Supplier; import com.google_voltpatches.common.base.Suppliers; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.collect.ImmutableMap; import com.google_voltpatches.common.util.concurrent.ListenableFuture; import com.google_voltpatches.common.util.concurrent.ListeningExecutorService; import com.google_voltpatches.common.util.concurrent.MoreExecutors; import com.google_voltpatches.common.util.concurrent.SettableFuture; public class CoreUtils { private static final VoltLogger hostLog = new VoltLogger("HOST"); public static final int SMALL_STACK_SIZE = 1024 * 256; public static final int MEDIUM_STACK_SIZE = 1024 * 512; public static final ListenableFuture<Object> COMPLETED_FUTURE = new ListenableFuture<Object>() { @Override public void addListener(Runnable listener, Executor executor) { executor.execute(listener); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Object get() { return null; } @Override public Object get(long timeout, TimeUnit unit) { return null; } }; /** * Get a single thread executor that caches it's thread meaning that the thread will terminate * after keepAlive milliseconds. A new thread will be created the next time a task arrives and that will be kept * around for keepAlive milliseconds. On creation no thread is allocated, the first task creates a thread. * * Uses LinkedTransferQueue to accept tasks and has a small stack. */ public static ListeningExecutorService getCachedSingleThreadExecutor(String name, long keepAlive) { return MoreExecutors.listeningDecorator(new ThreadPoolExecutor( 0, 1, keepAlive, TimeUnit.MILLISECONDS, new LinkedTransferQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null))); } /** * Create an unbounded single threaded executor */ public static ListeningExecutorService getSingleThreadExecutor(String name) { ExecutorService ste = Executors.newSingleThreadExecutor(CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)); return MoreExecutors.listeningDecorator(ste); } public static ListeningExecutorService getSingleThreadExecutor(String name, int size) { ExecutorService ste = Executors.newSingleThreadExecutor(CoreUtils.getThreadFactory(null, name, size, false, null)); return MoreExecutors.listeningDecorator(ste); } /** * Create a bounded single threaded executor that rejects requests if more than capacity * requests are outstanding. */ public static ListeningExecutorService getBoundedSingleThreadExecutor(String name, int capacity) { LinkedBlockingQueue<Runnable> lbq = new LinkedBlockingQueue<Runnable>(capacity); ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, lbq, CoreUtils.getThreadFactory(name)); return MoreExecutors.listeningDecorator(tpe); } /* * Have shutdown actually means shutdown. Tasks that need to complete should use * futures. */ public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) { ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null)); ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); return ses; } public static ListeningExecutorService getListeningExecutorService( final String name, final int threads) { return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), null); } public static ListeningExecutorService getListeningExecutorService( final String name, final int coreThreads, final int threads) { return getListeningExecutorService(name, coreThreads, threads, new LinkedTransferQueue<Runnable>(), null); } public static ListeningExecutorService getListeningExecutorService( final String name, final int threads, Queue<String> coreList) { return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), coreList); } public static ListeningExecutorService getListeningExecutorService( final String name, int threadsTemp, final BlockingQueue<Runnable> queue, final Queue<String> coreList) { if (coreList != null && !coreList.isEmpty()) { threadsTemp = coreList.size(); } final int threads = threadsTemp; if (threads < 1) { throw new IllegalArgumentException("Must specify > 0 threads"); } if (name == null) { throw new IllegalArgumentException("Name cannot be null"); } return MoreExecutors.listeningDecorator( new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, queue, getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList))); } public static ListeningExecutorService getListeningExecutorService( final String name, int coreThreadsTemp, int threadsTemp, final BlockingQueue<Runnable> queue, final Queue<String> coreList) { if (coreThreadsTemp < 0) { throw new IllegalArgumentException("Must specify >= 0 core threads"); } if (coreThreadsTemp > threadsTemp) { throw new IllegalArgumentException("Core threads must be <= threads"); } if (coreList != null && !coreList.isEmpty()) { threadsTemp = coreList.size(); if (coreThreadsTemp > threadsTemp) { coreThreadsTemp = threadsTemp; } } final int coreThreads = coreThreadsTemp; final int threads = threadsTemp; if (threads < 1) { throw new IllegalArgumentException("Must specify > 0 threads"); } if (name == null) { throw new IllegalArgumentException("Name cannot be null"); } return MoreExecutors.listeningDecorator( new ThreadPoolExecutor(coreThreads, threads, 1L, TimeUnit.MINUTES, queue, getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList))); } /** * Create a bounded thread pool executor. The work queue is synchronous and can cause * RejectedExecutionException if there is no available thread to take a new task. * @param maxPoolSize: the maximum number of threads to allow in the pool. * @param keepAliveTime: when the number of threads is greater than the core, this is the maximum * time that excess idle threads will wait for new tasks before terminating. * @param unit: the time unit for the keepAliveTime argument. * @param threadFactory: the factory to use when the executor creates a new thread. */ public static ThreadPoolExecutor getBoundedThreadPoolExecutor(int maxPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory tFactory) { return new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, unit, new SynchronousQueue<Runnable>(), tFactory); } public static ThreadFactory getThreadFactory(String name) { return getThreadFactory(name, SMALL_STACK_SIZE); } public static ThreadFactory getThreadFactory(String groupName, String name) { return getThreadFactory(groupName, name, SMALL_STACK_SIZE, true, null); } public static ThreadFactory getThreadFactory(String name, int stackSize) { return getThreadFactory(null, name, stackSize, true, null); } /** * Creates a thread factory that creates threads within a thread group if * the group name is given. The threads created will catch any unhandled * exceptions and log them to the HOST logger. * * @param groupName * @param name * @param stackSize * @return */ public static ThreadFactory getThreadFactory( final String groupName, final String name, final int stackSize, final boolean incrementThreadNames, final Queue<String> coreList) { ThreadGroup group = null; if (groupName != null) { group = new ThreadGroup(Thread.currentThread().getThreadGroup(), groupName); } final ThreadGroup finalGroup = group; return new ThreadFactory() { private final AtomicLong m_createdThreadCount = new AtomicLong(0); private final ThreadGroup m_group = finalGroup; @Override public synchronized Thread newThread(final Runnable r) { final String threadName = name + (incrementThreadNames ? " - " + m_createdThreadCount.getAndIncrement() : ""); String coreTemp = null; if (coreList != null && !coreList.isEmpty()) { coreTemp = coreList.poll(); } final String core = coreTemp; Runnable runnable = new Runnable() { @Override public void run() { if (core != null) { // Remove Affinity for now to make this dependency dissapear from the client. // Goal is to remove client dependency on this class in the medium term. //PosixJNAAffinity.INSTANCE.setAffinity(core); } try { r.run(); } catch (Throwable t) { hostLog.error("Exception thrown in thread " + threadName, t); } } }; Thread t = new Thread(m_group, runnable, threadName, stackSize); t.setDaemon(true); return t; } }; } /** * Return the local hostname, if it's resolvable. If not, * return the IPv4 address on the first interface we find, if it exists. * If not, returns whatever address exists on the first interface. * @return the String representation of some valid host or IP address, * if we can find one; the empty string otherwise */ public static String getHostnameOrAddress() { final InetAddress addr = m_localAddressSupplier.get(); if (addr == null) return ""; return ReverseDNSCache.hostnameOrAddress(addr); } private static final Supplier<InetAddress> m_localAddressSupplier = Suppliers.memoizeWithExpiration(new Supplier<InetAddress>() { @Override public InetAddress get() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr; } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return null; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address; } } addresses = intf.getInetAddresses(); if (addresses.hasMoreElements()) { return addresses.nextElement(); } return null; } catch (SocketException e1) { return null; } } } }, 1, TimeUnit.DAYS); /** * Return the local IP address, if it's resolvable. If not, * return the IPv4 address on the first interface we find, if it exists. * If not, returns whatever address exists on the first interface. * @return the String representation of some valid host or IP address, * if we can find one; the empty string otherwise */ public static InetAddress getLocalAddress() { return m_localAddressSupplier.get(); } public static long getHSIdFromHostAndSite(int host, int site) { long HSId = site; HSId = (HSId << 32) + host; return HSId; } public static int getHostIdFromHSId(long HSId) { return (int) (HSId & 0xffffffff); } public static String hsIdToString(long hsId) { return Integer.toString((int)hsId) + ":" + Integer.toString((int)(hsId >> 32)); } public static String hsIdCollectionToString(Collection<Long> ids) { List<String> idstrings = new ArrayList<String>(); for (Long id : ids) { idstrings.add(hsIdToString(id)); } // Easy hack, sort hsIds lexically. Collections.sort(idstrings); StringBuilder sb = new StringBuilder(); boolean first = false; for (String id : idstrings) { if (!first) { first = true; } else { sb.append(", "); } sb.append(id); } return sb.toString(); } public static int getSiteIdFromHSId(long siteId) { return (int)(siteId>>32); } public static <K,V> ImmutableMap<K, ImmutableList<V>> unmodifiableMapCopy(Map<K, List<V>> m) { ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder(); for (Map.Entry<K, List<V>> e : m.entrySet()) { builder.put(e.getKey(), ImmutableList.<V>builder().addAll(e.getValue()).build()); } return builder.build(); } public static byte[] urlToBytes(String url) { if (url == null) { return null; } try { // get the URL/path for the deployment and prep an InputStream InputStream input = null; try { URL inputURL = new URL(url); input = inputURL.openStream(); } catch (MalformedURLException ex) { // Invalid URL. Try as a file. try { input = new FileInputStream(url); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } catch (IOException ioex) { throw new RuntimeException(ioex); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte readBytes[] = new byte[1024 * 8]; while (true) { int read = input.read(readBytes); if (read == -1) { break; } baos.write(readBytes, 0, read); } return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } } public static String throwableToString(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); return sw.toString(); } public static String hsIdKeyMapToString(Map<Long, ?> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<Long, ?> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(entry.getKey())); sb.append("->").append(entry.getValue()); } sb.append('}'); return sb.toString(); } public static String hsIdValueMapToString(Map<?, Long> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<?, Long> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(entry.getKey()).append("->"); sb.append(CoreUtils.hsIdToString(entry.getValue())); } sb.append('}'); return sb.toString(); } public static String hsIdMapToString(Map<Long, Long> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<Long, Long> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(entry.getKey())).append(" -> "); sb.append(CoreUtils.hsIdToString(entry.getValue())); } sb.append('}'); return sb.toString(); } public static int availableProcessors() { return Math.max(1, Runtime.getRuntime().availableProcessors()); } public static final class RetryException extends RuntimeException { public RetryException() {}; public RetryException(Throwable cause) { super(cause); } } /* * A helper for retrying tasks asynchronously returns a settable future * that can be used to attempt to cancel the task * * The first executor service is used to schedule retry attempts * The second is where the task will be subsmitted for execution * If the two services are the same only the scheduled service is used */ public static final<T> ListenableFuture<T> retryHelper( final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final Long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit) { Preconditions.checkNotNull(maxUnit); Preconditions.checkNotNull(startUnit); Preconditions.checkArgument(startUnit.toMillis(startInterval) >= 1); Preconditions.checkArgument(maxUnit.toMillis(maxInterval) >= 1); Preconditions.checkNotNull(callable); final SettableFuture<T> retval = SettableFuture.create(); /* * Base case with no retry, attempt the task once */ es.execute(new Runnable() { @Override public void run() { try { retval.set(callable.call()); } catch (RetryException e) { //Now schedule a retry retryHelper(ses, es, callable, maxAttempts, startInterval, startUnit, maxInterval, maxUnit, 0, retval); } catch (Exception e) { retval.setException(e); } } }); return retval; } private static final <T> void retryHelper( final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final Long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit, final long ii, final SettableFuture<T> retval) { long intervalMax = maxUnit.toMillis(maxInterval); final long interval = Math.min(intervalMax, startUnit.toMillis(startInterval) * 2); ses.schedule(new Runnable() { @Override public void run() { Runnable task = new Runnable() { @Override public void run() { if (retval.isCancelled()) return; try { retval.set(callable.call()); } catch (RetryException e) { retryHelper(ses, es, callable, maxAttempts, interval, TimeUnit.MILLISECONDS, maxInterval, maxUnit, ii + 1, retval); } catch (Exception e3) { retval.setException(e3); } } }; if (ses == es) task.run(); else es.execute(task); } }, interval, TimeUnit.MILLISECONDS); } }
package ca.corefacility.bioinformatics.irida.ria.web.services; import java.util.Locale; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException; import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow; import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaWorkflowDescription; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.launch.UIPipelineDetailsResponse; import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService; /** * UI Service for all things related to workflow pipelines. */ @Component public class UIPipelineService { private final IridaWorkflowsService workflowsService; private final MessageSource messageSource; @Autowired public UIPipelineService(IridaWorkflowsService workflowsService, MessageSource messageSource) { this.workflowsService = workflowsService; this.messageSource = messageSource; } /** * Get the information about a specific workflow pipeline * * @param id for a {@link IridaWorkflow} * @param locale current users {@link Locale} * @return Details contained within a {@link UIPipelineDetailsResponse} * @throws IridaWorkflowNotFoundException exception thrown if the workflow cannot be found. */ public UIPipelineDetailsResponse getPipelineDetails(UUID id, Locale locale) throws IridaWorkflowNotFoundException { IridaWorkflow workflow = workflowsService.getIridaWorkflow(id); IridaWorkflowDescription description = workflow.getWorkflowDescription(); UIPipelineDetailsResponse detailsResponse = new UIPipelineDetailsResponse(); /* Prefix for getting messages from IRIDA message properties file */ String prefix = "workflow." + description.getAnalysisType().getType() + "."; /* Set up basic information for the pipeline being launched. */ detailsResponse.setName(messageSource.getMessage(prefix + "title", new Object[]{}, locale)); detailsResponse.setDescription(messageSource.getMessage(prefix + "description", new Object[]{}, locale)); return detailsResponse; } }
package com.fasterxml.jackson.databind.introspect; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.ext.Java7Support; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter; import com.fasterxml.jackson.databind.ser.impl.AttributePropertyWriter; import com.fasterxml.jackson.databind.ser.std.RawSerializer; import com.fasterxml.jackson.databind.type.MapLikeType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.util.*; /** * {@link AnnotationIntrospector} implementation that handles standard * Jackson annotations. */ public class JacksonAnnotationIntrospector extends AnnotationIntrospector implements java.io.Serializable { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") private final static Class<? extends Annotation>[] ANNOTATIONS_TO_INFER_SER = (Class<? extends Annotation>[]) new Class<?>[] { JsonSerialize.class, JsonView.class, JsonFormat.class, JsonTypeInfo.class, JsonRawValue.class, JsonUnwrapped.class, JsonBackReference.class, JsonManagedReference.class }; @SuppressWarnings("unchecked") private final static Class<? extends Annotation>[] ANNOTATIONS_TO_INFER_DESER = (Class<? extends Annotation>[]) new Class<?>[] { JsonDeserialize.class, JsonView.class, JsonFormat.class, JsonTypeInfo.class, JsonUnwrapped.class, JsonBackReference.class, JsonManagedReference.class, JsonMerge.class // since 2.9 }; // NOTE: loading of Java7 dependencies is encapsulated by handlers in Java7Support, // here we do not really need any handling; but for extra-safety use try-catch private static final Java7Support _java7Helper; static { Java7Support x = null; try { x = Java7Support.instance(); } catch (Throwable t) { } _java7Helper = x; } /** * Since introspection of annotation types is a performance issue in some * use cases (rare, but do exist), let's try a simple cache to reduce * need for actual meta-annotation introspection. *<p> * Non-final only because it needs to be re-created after deserialization. * * @since 2.7 */ protected transient LRUMap<Class<?>,Boolean> _annotationsInside = new LRUMap<Class<?>,Boolean>(48, 48); /** * See {@link #setConstructorPropertiesImpliesCreator(boolean)} for * explanation. *<p> * Defaults to true. * * @since 2.7.4 */ protected boolean _cfgConstructorPropertiesImpliesCreator = true; public JacksonAnnotationIntrospector() { } @Override public Version version() { return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION; } protected Object readResolve() { if (_annotationsInside == null) { _annotationsInside = new LRUMap<Class<?>,Boolean>(48, 48); } return this; } /** * Method for changing behavior of {@link java.beans.ConstructorProperties}: * if set to `true`, existence DOES indicate that the given constructor should * be considered a creator; `false` that it should NOT be considered a creator * without explicit use of <code>JsonCreator</code> annotation. *<p> * Default setting is `true` * * @since 2.7.4 */ public JacksonAnnotationIntrospector setConstructorPropertiesImpliesCreator(boolean b) { _cfgConstructorPropertiesImpliesCreator = b; return this; } /** * Annotations with meta-annotation {@link JacksonAnnotationsInside} * are considered bundles. */ @Override public boolean isAnnotationBundle(Annotation ann) { // 22-Sep-2015, tatu: Caching here has modest effect on JavaSE, and only // mostly in degenerate cases where introspection used more often than // it should (like recreating ObjectMapper once per read/write). // But it may be more beneficial on platforms like Android (should verify) Class<?> type = ann.annotationType(); Boolean b = _annotationsInside.get(type); if (b == null) { b = type.getAnnotation(JacksonAnnotationsInside.class) != null; _annotationsInside.putIfAbsent(type, b); } return b.booleanValue(); } /** * Since 2.6, we have supported use of {@link JsonProperty} for specifying * explicit serialized name */ @Override @Deprecated // since 2.8 public String findEnumValue(Enum<?> value) { // 11-Jun-2015, tatu: As per [databind#677], need to allow explicit naming. // Unfortunately cannot quite use standard AnnotatedClass here (due to various // reasons, including odd representation JVM uses); has to do for now try { // We know that values are actually static fields with matching name so: Field f = value.getClass().getField(value.name()); if (f != null) { JsonProperty prop = f.getAnnotation(JsonProperty.class); if (prop != null) { String n = prop.value(); if (n != null && !n.isEmpty()) { return n; } } } } catch (SecurityException e) { // 17-Sep-2015, tatu: Anything we could/should do here? } catch (NoSuchFieldException e) { // 17-Sep-2015, tatu: should not really happen. But... can we do anything? } return value.name(); } @Override // since 2.7 public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names) { HashMap<String,String> expl = null; for (Field f : ClassUtil.getDeclaredFields(enumType)) { if (!f.isEnumConstant()) { continue; } JsonProperty prop = f.getAnnotation(JsonProperty.class); if (prop == null) { continue; } String n = prop.value(); if (n.isEmpty()) { continue; } if (expl == null) { expl = new HashMap<String,String>(); } expl.put(f.getName(), n); } // and then stitch them together if and as necessary if (expl != null) { for (int i = 0, end = enumValues.length; i < end; ++i) { String defName = enumValues[i].name(); String explValue = expl.get(defName); if (explValue != null) { names[i] = explValue; } } } return names; } /** * Finds the Enum value that should be considered the default value, if possible. * <p> * This implementation relies on {@link JsonEnumDefaultValue} annotation to determine the default value if present. * * @param enumCls The Enum class to scan for the default value. * @return null if none found or it's not possible to determine one. * @since 2.8 */ @Override public Enum<?> findDefaultEnumValue(Class<Enum<?>> enumCls) { return ClassUtil.findFirstAnnotatedEnumValue(enumCls, JsonEnumDefaultValue.class); } @Override public PropertyName findRootName(AnnotatedClass ac) { JsonRootName ann = _findAnnotation(ac, JsonRootName.class); if (ann == null) { return null; } String ns = ann.namespace(); if (ns != null && ns.length() == 0) { ns = null; } return PropertyName.construct(ann.value(), ns); } @Override // since 2.8 public JsonIgnoreProperties.Value findPropertyIgnorals(Annotated a) { JsonIgnoreProperties v = _findAnnotation(a, JsonIgnoreProperties.class); if (v == null) { return JsonIgnoreProperties.Value.empty(); } return JsonIgnoreProperties.Value.from(v); } @Override public Boolean isIgnorableType(AnnotatedClass ac) { JsonIgnoreType ignore = _findAnnotation(ac, JsonIgnoreType.class); return (ignore == null) ? null : ignore.value(); } @Override public Object findFilterId(Annotated a) { JsonFilter ann = _findAnnotation(a, JsonFilter.class); if (ann != null) { String id = ann.value(); // Empty String is same as not having annotation, to allow overrides if (id.length() > 0) { return id; } } return null; } @Override public Object findNamingStrategy(AnnotatedClass ac) { JsonNaming ann = _findAnnotation(ac, JsonNaming.class); return (ann == null) ? null : ann.value(); } @Override public String findClassDescription(AnnotatedClass ac) { JsonClassDescription ann = _findAnnotation(ac, JsonClassDescription.class); return (ann == null) ? null : ann.value(); } @Override public VisibilityChecker<?> findAutoDetectVisibility(AnnotatedClass ac, VisibilityChecker<?> checker) { JsonAutoDetect ann = _findAnnotation(ac, JsonAutoDetect.class); return (ann == null) ? checker : checker.with(ann); } @Override public String findImplicitPropertyName(AnnotatedMember m) { PropertyName n = _findConstructorName(m); return (n == null) ? null : n.getSimpleName(); } @Override public List<PropertyName> findPropertyAliases(Annotated m) { JsonAlias ann = _findAnnotation(m, JsonAlias.class); if (ann == null) { return null; } String[] strs = ann.value(); final int len = strs.length; if (len == 0) { return Collections.emptyList(); } List<PropertyName> result = new ArrayList<>(len); for (int i = 0; i < len; ++i) { result.add(PropertyName.construct(strs[i])); } return result; } @Override public boolean hasIgnoreMarker(AnnotatedMember m) { return _isIgnorable(m); } @Override public Boolean hasRequiredMarker(AnnotatedMember m) { JsonProperty ann = _findAnnotation(m, JsonProperty.class); if (ann != null) { return ann.required(); } return null; } @Override public JsonProperty.Access findPropertyAccess(Annotated m) { JsonProperty ann = _findAnnotation(m, JsonProperty.class); if (ann != null) { return ann.access(); } return null; } @Override public String findPropertyDescription(Annotated ann) { JsonPropertyDescription desc = _findAnnotation(ann, JsonPropertyDescription.class); return (desc == null) ? null : desc.value(); } @Override public Integer findPropertyIndex(Annotated ann) { JsonProperty prop = _findAnnotation(ann, JsonProperty.class); if (prop != null) { int ix = prop.index(); if (ix != JsonProperty.INDEX_UNKNOWN) { return Integer.valueOf(ix); } } return null; } @Override public String findPropertyDefaultValue(Annotated ann) { JsonProperty prop = _findAnnotation(ann, JsonProperty.class); if (prop == null) { return null; } String str = prop.defaultValue(); // Since annotations do not allow nulls, need to assume empty means "none" return str.isEmpty() ? null : str; } @Override public JsonFormat.Value findFormat(Annotated ann) { JsonFormat f = _findAnnotation(ann, JsonFormat.class); return (f == null) ? null : new JsonFormat.Value(f); } @Override public ReferenceProperty findReferenceType(AnnotatedMember member) { JsonManagedReference ref1 = _findAnnotation(member, JsonManagedReference.class); if (ref1 != null) { return AnnotationIntrospector.ReferenceProperty.managed(ref1.value()); } JsonBackReference ref2 = _findAnnotation(member, JsonBackReference.class); if (ref2 != null) { return AnnotationIntrospector.ReferenceProperty.back(ref2.value()); } return null; } @Override public NameTransformer findUnwrappingNameTransformer(AnnotatedMember member) { JsonUnwrapped ann = _findAnnotation(member, JsonUnwrapped.class); // if not enabled, just means annotation is not enabled; not necessarily // that unwrapping should not be done (relevant when using chained introspectors) if (ann == null || !ann.enabled()) { return null; } String prefix = ann.prefix(); String suffix = ann.suffix(); return NameTransformer.simpleTransformer(prefix, suffix); } @Override // since 2.9 public JacksonInject.Value findInjectableValue(AnnotatedMember m) { JacksonInject ann = _findAnnotation(m, JacksonInject.class); if (ann == null) { return null; } // Empty String means that we should use name of declared value class. JacksonInject.Value v = JacksonInject.Value.from(ann); if (!v.hasId()) { Object id; // slight complication; for setters, type if (!(m instanceof AnnotatedMethod)) { id = m.getRawType().getName(); } else { AnnotatedMethod am = (AnnotatedMethod) m; if (am.getParameterCount() == 0) { // getter id = m.getRawType().getName(); } else { // setter id = am.getRawParameterType(0).getName(); } } v = v.withId(id); } return v; } @Override @Deprecated // since 2.9 public Object findInjectableValueId(AnnotatedMember m) { JacksonInject.Value v = findInjectableValue(m); return (v == null) ? null : v.getId(); } @Override public Class<?>[] findViews(Annotated a) { JsonView ann = _findAnnotation(a, JsonView.class); return (ann == null) ? null : ann.value(); } @Override // since 2.7 public AnnotatedMethod resolveSetterConflict(MapperConfig<?> config, AnnotatedMethod setter1, AnnotatedMethod setter2) { Class<?> cls1 = setter1.getRawParameterType(0); Class<?> cls2 = setter2.getRawParameterType(0); // First: prefer primitives over non-primitives // 11-Dec-2015, tatu: TODO, perhaps consider wrappers for primitives too? if (cls1.isPrimitive()) { if (!cls2.isPrimitive()) { return setter1; } } else if (cls2.isPrimitive()) { return setter2; } if (cls1 == String.class) { if (cls2 != String.class) { return setter1; } } else if (cls2 == String.class) { return setter2; } return null; } @Override public TypeResolverBuilder<?> findTypeResolver(MapperConfig<?> config, AnnotatedClass ac, JavaType baseType) { return _findTypeResolver(config, ac, baseType); } @Override public TypeResolverBuilder<?> findPropertyTypeResolver(MapperConfig<?> config, AnnotatedMember am, JavaType baseType) { /* As per definition of @JsonTypeInfo, should only apply to contents of container * (collection, map) types, not container types themselves: */ // 17-Apr-2016, tatu: For 2.7.4 make sure ReferenceType also included if (baseType.isContainerType() || baseType.isReferenceType()) { return null; } // No per-member type overrides (yet) return _findTypeResolver(config, am, baseType); } @Override public TypeResolverBuilder<?> findPropertyContentTypeResolver(MapperConfig<?> config, AnnotatedMember am, JavaType containerType) { /* First: let's ensure property is a container type: caller should have * verified but just to be sure */ if (containerType.getContentType() == null) { throw new IllegalArgumentException("Must call method with a container or reference type (got "+containerType+")"); } return _findTypeResolver(config, am, containerType); } @Override public List<NamedType> findSubtypes(Annotated a) { JsonSubTypes t = _findAnnotation(a, JsonSubTypes.class); if (t == null) return null; JsonSubTypes.Type[] types = t.value(); ArrayList<NamedType> result = new ArrayList<NamedType>(types.length); for (JsonSubTypes.Type type : types) { result.add(new NamedType(type.value(), type.name())); } return result; } @Override public String findTypeName(AnnotatedClass ac) { JsonTypeName tn = _findAnnotation(ac, JsonTypeName.class); return (tn == null) ? null : tn.value(); } @Override public Boolean isTypeId(AnnotatedMember member) { return _hasAnnotation(member, JsonTypeId.class); } @Override public ObjectIdInfo findObjectIdInfo(Annotated ann) { JsonIdentityInfo info = _findAnnotation(ann, JsonIdentityInfo.class); if (info == null || info.generator() == ObjectIdGenerators.None.class) { return null; } // In future may need to allow passing namespace? PropertyName name = PropertyName.construct(info.property()); return new ObjectIdInfo(name, info.scope(), info.generator(), info.resolver()); } @Override public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo) { JsonIdentityReference ref = _findAnnotation(ann, JsonIdentityReference.class); if (ref == null) { return objectIdInfo; } if (objectIdInfo == null) { objectIdInfo = ObjectIdInfo.empty(); } return objectIdInfo.withAlwaysAsId(ref.alwaysAsId()); } @Override public Object findSerializer(Annotated a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); if (ann != null) { @SuppressWarnings("rawtypes") Class<? extends JsonSerializer> serClass = ann.using(); if (serClass != JsonSerializer.None.class) { return serClass; } } /* 18-Oct-2010, tatu: [JACKSON-351] @JsonRawValue handled just here, for now; * if we need to get raw indicator from other sources need to add * separate accessor within {@link AnnotationIntrospector} interface. */ JsonRawValue annRaw = _findAnnotation(a, JsonRawValue.class); if ((annRaw != null) && annRaw.value()) { // let's construct instance with nominal type: Class<?> cls = a.getRawType(); return new RawSerializer<Object>(cls); } return null; } @Override public Object findKeySerializer(Annotated a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); if (ann != null) { @SuppressWarnings("rawtypes") Class<? extends JsonSerializer> serClass = ann.keyUsing(); if (serClass != JsonSerializer.None.class) { return serClass; } } return null; } @Override public Object findContentSerializer(Annotated a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); if (ann != null) { @SuppressWarnings("rawtypes") Class<? extends JsonSerializer> serClass = ann.contentUsing(); if (serClass != JsonSerializer.None.class) { return serClass; } } return null; } @Override public Object findNullSerializer(Annotated a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); if (ann != null) { @SuppressWarnings("rawtypes") Class<? extends JsonSerializer> serClass = ann.nullsUsing(); if (serClass != JsonSerializer.None.class) { return serClass; } } return null; } @Override public JsonInclude.Value findPropertyInclusion(Annotated a) { JsonInclude inc = _findAnnotation(a, JsonInclude.class); JsonInclude.Value value = (inc == null) ? JsonInclude.Value.empty() : JsonInclude.Value.from(inc); // only consider deprecated variant if we didn't have non-deprecated one: if (value.getValueInclusion() == JsonInclude.Include.USE_DEFAULTS) { value = _refinePropertyInclusion(a, value); } return value; } @SuppressWarnings("deprecation") private JsonInclude.Value _refinePropertyInclusion(Annotated a, JsonInclude.Value value) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); if (ann != null) { switch (ann.include()) { case ALWAYS: return value.withValueInclusion(JsonInclude.Include.ALWAYS); case NON_NULL: return value.withValueInclusion(JsonInclude.Include.NON_NULL); case NON_DEFAULT: return value.withValueInclusion(JsonInclude.Include.NON_DEFAULT); case NON_EMPTY: return value.withValueInclusion(JsonInclude.Include.NON_EMPTY); case DEFAULT_INCLUSION: default: } } return value; } @Override public JsonSerialize.Typing findSerializationTyping(Annotated a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); return (ann == null) ? null : ann.typing(); } @Override public Object findSerializationConverter(Annotated a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); return (ann == null) ? null : _classIfExplicit(ann.converter(), Converter.None.class); } @Override public Object findSerializationContentConverter(AnnotatedMember a) { JsonSerialize ann = _findAnnotation(a, JsonSerialize.class); return (ann == null) ? null : _classIfExplicit(ann.contentConverter(), Converter.None.class); } @Override public JavaType refineSerializationType(final MapperConfig<?> config, final Annotated a, final JavaType baseType) throws JsonMappingException { JavaType type = baseType; final TypeFactory tf = config.getTypeFactory(); final JsonSerialize jsonSer = _findAnnotation(a, JsonSerialize.class); // Ok: start by refining the main type itself; common to all types final Class<?> serClass = (jsonSer == null) ? null : _classIfExplicit(jsonSer.as()); if (serClass != null) { if (type.hasRawClass(serClass)) { // 30-Nov-2015, tatu: As per [databind#1023], need to allow forcing of // static typing this way type = type.withStaticTyping(); } else { Class<?> currRaw = type.getRawClass(); try { // 11-Oct-2015, tatu: For deser, we call `TypeFactory.constructSpecializedType()`, // may be needed here too in future? if (serClass.isAssignableFrom(currRaw)) { // common case type = tf.constructGeneralizedType(type, serClass); } else if (currRaw.isAssignableFrom(serClass)) { // specialization, ok as well type = tf.constructSpecializedType(type, serClass); } else if (_primitiveAndWrapper(currRaw, serClass)) { // 27-Apr-2017, tatu: [databind#1592] ignore primitive<->wrapper refinements type = type.withStaticTyping(); } else { throw new JsonMappingException(null, String.format("Cannot refine serialization type %s into %s; types not related", type, serClass.getName())); } } catch (IllegalArgumentException iae) { throw new JsonMappingException(null, String.format("Failed to widen type %s with annotation (value %s), from '%s': %s", type, serClass.getName(), a.getName(), iae.getMessage()), iae); } } } // Then further processing for container types // First, key type (for Maps, Map-like types): if (type.isMapLikeType()) { JavaType keyType = type.getKeyType(); final Class<?> keyClass = (jsonSer == null) ? null : _classIfExplicit(jsonSer.keyAs()); if (keyClass != null) { if (keyType.hasRawClass(keyClass)) { keyType = keyType.withStaticTyping(); } else { Class<?> currRaw = keyType.getRawClass(); try { // 19-May-2016, tatu: As per [databind#1231], [databind#1178] may need to actually // specialize (narrow) type sometimes, even if more commonly opposite // is needed. if (keyClass.isAssignableFrom(currRaw)) { // common case keyType = tf.constructGeneralizedType(keyType, keyClass); } else if (currRaw.isAssignableFrom(keyClass)) { // specialization, ok as well keyType = tf.constructSpecializedType(keyType, keyClass); } else if (_primitiveAndWrapper(currRaw, keyClass)) { // 27-Apr-2017, tatu: [databind#1592] ignore primitive<->wrapper refinements keyType = keyType.withStaticTyping(); } else { throw new JsonMappingException(null, String.format("Cannot refine serialization key type %s into %s; types not related", keyType, keyClass.getName())); } } catch (IllegalArgumentException iae) { throw new JsonMappingException(null, String.format("Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s", type, keyClass.getName(), a.getName(), iae.getMessage()), iae); } } type = ((MapLikeType) type).withKeyType(keyType); } } JavaType contentType = type.getContentType(); if (contentType != null) { // collection[like], map[like], array, reference // And then value types for all containers: final Class<?> contentClass = (jsonSer == null) ? null : _classIfExplicit(jsonSer.contentAs()); if (contentClass != null) { if (contentType.hasRawClass(contentClass)) { contentType = contentType.withStaticTyping(); } else { // 03-Apr-2016, tatu: As per [databind#1178], may need to actually // specialize (narrow) type sometimes, even if more commonly opposite // is needed. Class<?> currRaw = contentType.getRawClass(); try { if (contentClass.isAssignableFrom(currRaw)) { // common case contentType = tf.constructGeneralizedType(contentType, contentClass); } else if (currRaw.isAssignableFrom(contentClass)) { // specialization, ok as well contentType = tf.constructSpecializedType(contentType, contentClass); } else if (_primitiveAndWrapper(currRaw, contentClass)) { // 27-Apr-2017, tatu: [databind#1592] ignore primitive<->wrapper refinements contentType = contentType.withStaticTyping(); } else { throw new JsonMappingException(null, String.format("Cannot refine serialization content type %s into %s; types not related", contentType, contentClass.getName())); } } catch (IllegalArgumentException iae) { // shouldn't really happen throw new JsonMappingException(null, String.format("Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s", type, contentClass.getName(), a.getName(), iae.getMessage()), iae); } } type = type.withContentType(contentType); } } return type; } @Override @Deprecated // since 2.7 public Class<?> findSerializationType(Annotated am) { return null; } @Override @Deprecated // since 2.7 public Class<?> findSerializationKeyType(Annotated am, JavaType baseType) { return null; } @Override @Deprecated // since 2.7 public Class<?> findSerializationContentType(Annotated am, JavaType baseType) { return null; } @Override public String[] findSerializationPropertyOrder(AnnotatedClass ac) { JsonPropertyOrder order = _findAnnotation(ac, JsonPropertyOrder.class); return (order == null) ? null : order.value(); } @Override public Boolean findSerializationSortAlphabetically(Annotated ann) { return _findSortAlpha(ann); } private final Boolean _findSortAlpha(Annotated ann) { JsonPropertyOrder order = _findAnnotation(ann, JsonPropertyOrder.class); // 23-Jun-2015, tatu: as per [databind#840], let's only consider // `true` to have any significance. if ((order != null) && order.alphabetic()) { return Boolean.TRUE; } return null; } @Override public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, List<BeanPropertyWriter> properties) { JsonAppend ann = _findAnnotation(ac, JsonAppend.class); if (ann == null) { return; } final boolean prepend = ann.prepend(); JavaType propType = null; // First: any attribute-backed properties? JsonAppend.Attr[] attrs = ann.attrs(); for (int i = 0, len = attrs.length; i < len; ++i) { if (propType == null) { propType = config.constructType(Object.class); } BeanPropertyWriter bpw = _constructVirtualProperty(attrs[i], config, ac, propType); if (prepend) { properties.add(i, bpw); } else { properties.add(bpw); } } // Then: general-purpose virtual properties? JsonAppend.Prop[] props = ann.props(); for (int i = 0, len = props.length; i < len; ++i) { BeanPropertyWriter bpw = _constructVirtualProperty(props[i], config, ac); if (prepend) { properties.add(i, bpw); } else { properties.add(bpw); } } } protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Attr attr, MapperConfig<?> config, AnnotatedClass ac, JavaType type) { PropertyMetadata metadata = attr.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL; // could add Index, Description in future, if those matter String attrName = attr.value(); // allow explicit renaming; if none, default to attribute name PropertyName propName = _propertyName(attr.propName(), attr.propNamespace()); if (!propName.hasSimpleName()) { propName = PropertyName.construct(attrName); } // now, then, we need a placeholder for member (no real Field/Method): AnnotatedMember member = new VirtualAnnotatedMember(ac, ac.getRawType(), attrName, type); // and with that and property definition SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, attr.include()); // can construct the property writer return AttributePropertyWriter.construct(attrName, propDef, ac.getAnnotations(), type); } protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac) { PropertyMetadata metadata = prop.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL; PropertyName propName = _propertyName(prop.name(), prop.namespace()); JavaType type = config.constructType(prop.type()); // now, then, we need a placeholder for member (no real Field/Method): AnnotatedMember member = new VirtualAnnotatedMember(ac, ac.getRawType(), propName.getSimpleName(), type); // and with that and property definition SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, prop.include()); Class<?> implClass = prop.value(); HandlerInstantiator hi = config.getHandlerInstantiator(); VirtualBeanPropertyWriter bpw = (hi == null) ? null : hi.virtualPropertyWriterInstance(config, implClass); if (bpw == null) { bpw = (VirtualBeanPropertyWriter) ClassUtil.createInstance(implClass, config.canOverrideAccessModifiers()); } // one more thing: give it necessary contextual information return bpw.withConfig(config, ac, propDef, type); } @Override public PropertyName findNameForSerialization(Annotated a) { JsonGetter jg = _findAnnotation(a, JsonGetter.class); if (jg != null) { return PropertyName.construct(jg.value()); } JsonProperty pann = _findAnnotation(a, JsonProperty.class); if (pann != null) { return PropertyName.construct(pann.value()); } if (_hasOneOf(a, ANNOTATIONS_TO_INFER_SER)) { return PropertyName.USE_DEFAULT; } return null; } @Override // since 2.9 public Boolean hasAsValue(Annotated a) { JsonValue ann = _findAnnotation(a, JsonValue.class); if (ann == null) { return null; } return ann.value(); } @Override // since 2.9 public Boolean hasAnyGetter(Annotated a) { JsonAnyGetter ann = _findAnnotation(a, JsonAnyGetter.class); if (ann == null) { return null; } return ann.enabled(); } @Override @Deprecated // since 2.9 public boolean hasAnyGetterAnnotation(AnnotatedMethod am) { // No dedicated disabling; regular @JsonIgnore used if needs to be ignored (handled separately) return _hasAnnotation(am, JsonAnyGetter.class); } @Override @Deprecated // since 2.9 public boolean hasAsValueAnnotation(AnnotatedMethod am) { JsonValue ann = _findAnnotation(am, JsonValue.class); // value of 'false' means disabled... return (ann != null) && ann.value(); } @Override public Object findDeserializer(Annotated a) { JsonDeserialize ann = _findAnnotation(a, JsonDeserialize.class); if (ann != null) { @SuppressWarnings("rawtypes") Class<? extends JsonDeserializer> deserClass = ann.using(); if (deserClass != JsonDeserializer.None.class) { return deserClass; } } return null; } @Override public Object findKeyDeserializer(Annotated a) { JsonDeserialize ann = _findAnnotation(a, JsonDeserialize.class); if (ann != null) { Class<? extends KeyDeserializer> deserClass = ann.keyUsing(); if (deserClass != KeyDeserializer.None.class) { return deserClass; } } return null; } @Override public Object findContentDeserializer(Annotated a) { JsonDeserialize ann = _findAnnotation(a, JsonDeserialize.class); if (ann != null) { @SuppressWarnings("rawtypes") Class<? extends JsonDeserializer> deserClass = ann.contentUsing(); if (deserClass != JsonDeserializer.None.class) { return deserClass; } } return null; } @Override public Object findDeserializationConverter(Annotated a) { JsonDeserialize ann = _findAnnotation(a, JsonDeserialize.class); return (ann == null) ? null : _classIfExplicit(ann.converter(), Converter.None.class); } @Override public Object findDeserializationContentConverter(AnnotatedMember a) { JsonDeserialize ann = _findAnnotation(a, JsonDeserialize.class); return (ann == null) ? null : _classIfExplicit(ann.contentConverter(), Converter.None.class); } @Override public JavaType refineDeserializationType(final MapperConfig<?> config, final Annotated a, final JavaType baseType) throws JsonMappingException { JavaType type = baseType; final TypeFactory tf = config.getTypeFactory(); final JsonDeserialize jsonDeser = _findAnnotation(a, JsonDeserialize.class); // Ok: start by refining the main type itself; common to all types final Class<?> valueClass = (jsonDeser == null) ? null : _classIfExplicit(jsonDeser.as()); if ((valueClass != null) && !type.hasRawClass(valueClass) && !_primitiveAndWrapper(type, valueClass)) { try { type = tf.constructSpecializedType(type, valueClass); } catch (IllegalArgumentException iae) { throw new JsonMappingException(null, String.format("Failed to narrow type %s with annotation (value %s), from '%s': %s", type, valueClass.getName(), a.getName(), iae.getMessage()), iae); } } // Then further processing for container types // First, key type (for Maps, Map-like types): if (type.isMapLikeType()) { JavaType keyType = type.getKeyType(); final Class<?> keyClass = (jsonDeser == null) ? null : _classIfExplicit(jsonDeser.keyAs()); if ((keyClass != null) && !_primitiveAndWrapper(keyType, keyClass)) { try { keyType = tf.constructSpecializedType(keyType, keyClass); type = ((MapLikeType) type).withKeyType(keyType); } catch (IllegalArgumentException iae) { throw new JsonMappingException(null, String.format("Failed to narrow key type of %s with concrete-type annotation (value %s), from '%s': %s", type, keyClass.getName(), a.getName(), iae.getMessage()), iae); } } } JavaType contentType = type.getContentType(); if (contentType != null) { // collection[like], map[like], array, reference // And then value types for all containers: final Class<?> contentClass = (jsonDeser == null) ? null : _classIfExplicit(jsonDeser.contentAs()); if ((contentClass != null) && !_primitiveAndWrapper(contentType, contentClass)) { try { contentType = tf.constructSpecializedType(contentType, contentClass); type = type.withContentType(contentType); } catch (IllegalArgumentException iae) { throw new JsonMappingException(null, String.format("Failed to narrow value type of %s with concrete-type annotation (value %s), from '%s': %s", type, contentClass.getName(), a.getName(), iae.getMessage()), iae); } } } return type; } @Override @Deprecated // since 2.7 public Class<?> findDeserializationContentType(Annotated am, JavaType baseContentType) { return null; } @Override @Deprecated // since 2.7 public Class<?> findDeserializationType(Annotated am, JavaType baseType) { return null; } @Override @Deprecated // since 2.7 public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType) { return null; } @Override public Object findValueInstantiator(AnnotatedClass ac) { JsonValueInstantiator ann = _findAnnotation(ac, JsonValueInstantiator.class); // no 'null' marker yet, so: return (ann == null) ? null : ann.value(); } @Override public Class<?> findPOJOBuilder(AnnotatedClass ac) { JsonDeserialize ann = _findAnnotation(ac, JsonDeserialize.class); return (ann == null) ? null : _classIfExplicit(ann.builder()); } @Override public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac) { JsonPOJOBuilder ann = _findAnnotation(ac, JsonPOJOBuilder.class); return (ann == null) ? null : new JsonPOJOBuilder.Value(ann); } @Override public PropertyName findNameForDeserialization(Annotated a) { // @JsonSetter has precedence over @JsonProperty, being more specific boolean useDefault = false; JsonSetter js = _findAnnotation(a, JsonSetter.class); if (js != null) { String s = js.value(); // 04-May-2018, tatu: Need to allow for "nameless" `@JsonSetter` too if (s.isEmpty()) { useDefault = true; } else { return PropertyName.construct(s); } } JsonProperty pann = _findAnnotation(a, JsonProperty.class); if (pann != null) { return PropertyName.construct(pann.value()); } if (useDefault || _hasOneOf(a, ANNOTATIONS_TO_INFER_DESER)) { return PropertyName.USE_DEFAULT; } return null; } @Override public Boolean hasAnySetter(Annotated a) { JsonAnySetter ann = _findAnnotation(a, JsonAnySetter.class); return (ann == null) ? null : ann.enabled(); } @Override public JsonSetter.Value findSetterInfo(Annotated a) { return JsonSetter.Value.from(_findAnnotation(a, JsonSetter.class)); } @Override // since 2.9 public Boolean findMergeInfo(Annotated a) { JsonMerge ann = _findAnnotation(a, JsonMerge.class); return (ann == null) ? null : ann.value().asBoolean(); } @Override @Deprecated // since 2.9 public boolean hasAnySetterAnnotation(AnnotatedMethod am) { return _hasAnnotation(am, JsonAnySetter.class); } @Override @Deprecated // since 2.9 public boolean hasCreatorAnnotation(Annotated a) { /* No dedicated disabling; regular @JsonIgnore used if needs to be * ignored (and if so, is handled prior to this method getting called) */ JsonCreator ann = _findAnnotation(a, JsonCreator.class); if (ann != null) { return (ann.mode() != JsonCreator.Mode.DISABLED); } // 19-Apr-2016, tatu: As per [databind#1197], [databind#1122] (and some related), // may or may not consider it a creator if (_cfgConstructorPropertiesImpliesCreator ) { if (a instanceof AnnotatedConstructor) { if (_java7Helper != null) { Boolean b = _java7Helper.hasCreatorAnnotation(a); if (b != null) { return b.booleanValue(); } } } } return false; } @Override @Deprecated // since 2.9 public JsonCreator.Mode findCreatorBinding(Annotated a) { JsonCreator ann = _findAnnotation(a, JsonCreator.class); return (ann == null) ? null : ann.mode(); } @Override public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a) { JsonCreator ann = _findAnnotation(a, JsonCreator.class); if (ann != null) { return ann.mode(); } if (_cfgConstructorPropertiesImpliesCreator && config.isEnabled(MapperFeature.INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES) ) { if (a instanceof AnnotatedConstructor) { if (_java7Helper != null) { Boolean b = _java7Helper.hasCreatorAnnotation(a); if ((b != null) && b.booleanValue()) { // 13-Sep-2016, tatu: Judgment call, but I don't think JDK ever implies // use of delegate; assumes as-properties implicitly return JsonCreator.Mode.PROPERTIES; } } } } return null; } protected boolean _isIgnorable(Annotated a) { JsonIgnore ann = _findAnnotation(a, JsonIgnore.class); if (ann != null) { return ann.value(); } if (_java7Helper != null) { Boolean b = _java7Helper.findTransient(a); if (b != null) { return b.booleanValue(); } } return false; } protected Class<?> _classIfExplicit(Class<?> cls) { if (cls == null || ClassUtil.isBogusClass(cls)) { return null; } return cls; } protected Class<?> _classIfExplicit(Class<?> cls, Class<?> implicit) { cls = _classIfExplicit(cls); return (cls == null || cls == implicit) ? null : cls; } protected PropertyName _propertyName(String localName, String namespace) { if (localName.isEmpty()) { return PropertyName.USE_DEFAULT; } if (namespace == null || namespace.isEmpty()) { return PropertyName.construct(localName); } return PropertyName.construct(localName, namespace); } protected PropertyName _findConstructorName(Annotated a) { if (a instanceof AnnotatedParameter) { AnnotatedParameter p = (AnnotatedParameter) a; AnnotatedWithParams ctor = p.getOwner(); if (ctor != null) { if (_java7Helper != null) { PropertyName name = _java7Helper.findConstructorName(p); if (name != null) { return name; } } } } return null; } /** * Helper method called to construct and initialize instance of {@link TypeResolverBuilder} * if given annotated element indicates one is needed. */ @SuppressWarnings("deprecation") protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType) { // First: maybe we have explicit type resolver? TypeResolverBuilder<?> b; JsonTypeInfo info = _findAnnotation(ann, JsonTypeInfo.class); JsonTypeResolver resAnn = _findAnnotation(ann, JsonTypeResolver.class); if (resAnn != null) { if (info == null) { return null; } /* let's not try to force access override (would need to pass * settings through if we did, since that's not doable on some * platforms) */ b = config.typeResolverBuilderInstance(ann, resAnn.value()); } else { // if not, use standard one, if indicated by annotations if (info == null) { return null; } // bit special; must return 'marker' to block use of default typing: if (info.use() == JsonTypeInfo.Id.NONE) { return _constructNoTypeResolverBuilder(); } b = _constructStdTypeResolverBuilder(); } // Does it define a custom type id resolver? JsonTypeIdResolver idResInfo = _findAnnotation(ann, JsonTypeIdResolver.class); TypeIdResolver idRes = (idResInfo == null) ? null : config.typeIdResolverInstance(ann, idResInfo.value()); if (idRes != null) { idRes.init(baseType); } b = b.init(info.use(), idRes); /* 13-Aug-2011, tatu: One complication; external id * only works for properties; so if declared for a Class, we will need * to map it to "PROPERTY" instead of "EXTERNAL_PROPERTY" */ JsonTypeInfo.As inclusion = info.include(); if (inclusion == JsonTypeInfo.As.EXTERNAL_PROPERTY && (ann instanceof AnnotatedClass)) { inclusion = JsonTypeInfo.As.PROPERTY; } b = b.inclusion(inclusion); b = b.typeProperty(info.property()); Class<?> defaultImpl = info.defaultImpl(); // 08-Dec-2014, tatu: To deprecate `JsonTypeInfo.None` we need to use other placeholder(s); // and since `java.util.Void` has other purpose (to indicate "deser as null"), we'll instead // use `JsonTypeInfo.class` itself. But any annotation type will actually do, as they have no // valid use (cannot instantiate as default) if (defaultImpl != JsonTypeInfo.None.class && !defaultImpl.isAnnotation()) { b = b.defaultImpl(defaultImpl); } b = b.typeIdVisibility(info.visible()); return b; } /** * Helper method for constructing standard {@link TypeResolverBuilder} * implementation. */ protected StdTypeResolverBuilder _constructStdTypeResolverBuilder() { return new StdTypeResolverBuilder(); } /** * Helper method for dealing with "no type info" marker; can't be null * (as it'd be replaced by default typing) */ protected StdTypeResolverBuilder _constructNoTypeResolverBuilder() { return StdTypeResolverBuilder.noTypeInfoBuilder(); } private boolean _primitiveAndWrapper(Class<?> baseType, Class<?> refinement) { if (baseType.isPrimitive()) { return baseType == ClassUtil.primitiveType(refinement); } if (refinement.isPrimitive()) { return refinement == ClassUtil.primitiveType(baseType); } return false; } private boolean _primitiveAndWrapper(JavaType baseType, Class<?> refinement) { if (baseType.isPrimitive()) { return baseType.hasRawClass(ClassUtil.primitiveType(refinement)); } if (refinement.isPrimitive()) { return refinement == ClassUtil.primitiveType(baseType.getRawClass()); } return false; } }
// VisBio.java package loci.visbio; import java.awt.Color; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import loci.visbio.util.InstanceServer; import loci.visbio.util.SplashScreen; /** * VisBio is a biological visualization tool designed for easy * visualization and analysis of multidimensional image data. * * This class is the main gateway into the application. It creates and displays * a VisBioFrame via reflection, so that the splash screen appears as quickly * as possible, before the class loader gets too far along. */ public class VisBio { // -- Constants -- /** Application title. */ public static final String TITLE = "VisBio"; /** Application version. */ public static final String VERSION = "v3.00 beta5g"; /** Application author. */ public static final String AUTHOR = "Curtis Rueden, LOCI"; /** Application build date. */ public static final String DATE = "26 May 2005"; /** Port to use for communicating between application instances. */ public static final int INSTANCE_PORT = 0xabcd; // -- Constructor -- /** Ensure this class can't be instantiated. */ private VisBio() { } // -- Main -- /** Launches the VisBio GUI. */ public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // check whether VisBio is already running boolean isRunning = true; try { InstanceServer.sendArguments(args, INSTANCE_PORT); } catch (IOException exc) { isRunning = false; } if (isRunning) System.exit(0); // display splash screen String[] msg = { TITLE + " " + VERSION + " - " + AUTHOR, "VisBio is starting up..." }; SplashScreen ss = new SplashScreen( VisBio.class.getResource("visbio-logo.png"), msg, new Color(255, 255, 220), new Color(255, 50, 50)); ss.show(); // toggle window decoration mode via reflection boolean b = "true".equals(System.getProperty("visbio.decorateWindows")); Class jf = Class.forName("javax.swing.JFrame"); Method m = jf.getMethod("setDefaultLookAndFeelDecorated", new Class[] {boolean.class}); m.invoke(null, new Object[] {new Boolean(b)}); // construct VisBio interface via reflection Class vb = Class.forName("loci.visbio.VisBioFrame"); Constructor con = vb.getConstructor(new Class[] { ss.getClass(), String[].class }); con.newInstance(new Object[] {ss, args}); } }
package com.kryptnostic.kodex.v1.serialization.jackson; import com.fasterxml.jackson.databind.InjectableValues.Std; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.smile.SmileFactory; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import com.kryptnostic.crypto.padding.ZeroPaddingStrategy; import com.kryptnostic.crypto.v1.keys.Kodex; import com.kryptnostic.multivariate.polynomial.BasePolynomialFunction; import com.kryptnostic.multivariate.polynomial.CompoundPolynomialFunctionGF2; import com.kryptnostic.multivariate.polynomial.OptimizedPolynomialFunctionGF2; import com.kryptnostic.multivariate.polynomial.ParameterizedPolynomialFunctionGF2; public final class KodexObjectMapperFactory { private KodexObjectMapperFactory() {}; public static ObjectMapper getObjectMapper( Kodex<String> kodex ) { ObjectMapper mapper = getBaseMapper(); configureMapperInjectables( mapper, kodex ); return mapper; } public static ObjectMapper getObjectMapper() { return getObjectMapper( null ); } public static ObjectMapper getSmileMapper() { ObjectMapper mapper = new ObjectMapper( new SmileFactory() ); configureMapper( mapper ); configureMapperInjectables( mapper, null ); return mapper; } private static ObjectMapper getBaseMapper() { ObjectMapper mapper = new ObjectMapper(); configureMapper( mapper ); return mapper; } private static void configureMapperInjectables( ObjectMapper mapper , Kodex<String> kodex ) { Std injectableValues = new Std(); injectableValues.addValue( Kodex.class, kodex ); mapper.setInjectableValues( injectableValues ); mapper.registerModule( new KodexModule( kodex ) ); } private static void configureMapper(ObjectMapper mapper ) { mapper.registerModule( new KodexModule() ); mapper.registerModule( new GuavaModule() ); mapper.registerModule( new AfterburnerModule() ); mapper.registerSubtypes( CompoundPolynomialFunctionGF2.class, OptimizedPolynomialFunctionGF2.class, BasePolynomialFunction.class, ParameterizedPolynomialFunctionGF2.class, ZeroPaddingStrategy.class ); } }
package com.psddev.dari.db; import java.io.IOException; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.MoreLikeThisParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.psddev.dari.util.Lazy; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import com.psddev.dari.util.Profiler; import com.psddev.dari.util.Settings; import com.psddev.dari.util.SettingsException; import com.psddev.dari.util.Stats; import com.psddev.dari.util.UuidUtils; public class SolrDatabase extends AbstractDatabase<SolrServer> { public static final String DEFAULT_COMMIT_WITHIN_SETTING = "dari/solrDefaultCommitWithin"; public static final String SERVER_URL_SUB_SETTING = "serverUrl"; public static final String READ_SERVER_URL_SUB_SETTING = "readServerUrl"; public static final String TENANT_SUB_SETTING = "tenant"; public static final String COMMIT_WITHIN_SUB_SETTING = "commitWithin"; public static final String VERSION_SUB_SETTING = "version"; public static final String SAVE_DATA_SUB_SETTING = "saveData"; public static final double DEFAULT_COMMIT_WITHIN = 0.0; public static final String TENANT_FIELD = "_s__tenant"; public static final String ID_FIELD = "id"; public static final String TYPE_ID_FIELD = "typeId"; public static final String DATA_FIELD = "data"; public static final String FIELDS_FIELD = "_t__fields"; public static final String ALL_FIELD = "all"; public static final String SCORE_FIELD = "score"; public static final String SUGGESTION_FIELD = "_e_suggestField"; public static final String SCORE_EXTRA = "solr.score"; public static final String NORMALIZED_SCORE_EXTRA = "solr.normalizedScore"; private static final int INITIAL_FETCH_SIZE = 100; private static final Logger LOGGER = LoggerFactory.getLogger(SolrDatabase.class); private static final Pattern UUID_PATTERN = Pattern.compile("([A-Fa-f0-9]{8})-([A-Fa-f0-9]{4})-([A-Fa-f0-9]{4})-([A-Fa-f0-9]{4})-([A-Fa-f0-9]{12})"); private static final String SHORT_NAME = "Solr"; private static final Stats STATS = new Stats(SHORT_NAME); private static final String ADD_STATS_OPERATION = "Add"; private static final String COMMIT_STATS_OPERATION = "Commit"; private static final String DELETE_STATS_OPERATION = "Delete"; private static final String QUERY_STATS_OPERATION = "Query"; private static final String ADD_PROFILER_EVENT = SHORT_NAME + " " + ADD_STATS_OPERATION; private static final String COMMIT_PROFILER_EVENT = SHORT_NAME + " " + COMMIT_STATS_OPERATION; private static final String DELETE_PROFILER_EVENT = SHORT_NAME + " " + DELETE_STATS_OPERATION; private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION; private volatile SolrServer server; private volatile SolrServer readServer; private volatile String tenant; private volatile Double commitWithin; private volatile String version; private volatile boolean saveData = true; /** Returns the underlying Solr server. */ public SolrServer getServer() { return server; } /** Sets the underlying Solr server. */ public void setServer(SolrServer server) { this.server = server; schema.reset(); } /** Returns the underlying Solr read server. */ public SolrServer getReadServer() { return readServer; } /** Sets the underlying Solr read server. */ public void setReadServer(SolrServer readServer) { this.readServer = readServer; schema.reset(); } public String getTenant() { return tenant; } public void setTenant(String tenant) { this.tenant = tenant; } public Double getCommitWithin() { return commitWithin; } public double getEffectiveCommitWithin() { Double commitWithin = getCommitWithin(); if (commitWithin == null) { commitWithin = Settings.get(Double.class, DEFAULT_COMMIT_WITHIN_SETTING); if (commitWithin == null) { commitWithin = DEFAULT_COMMIT_WITHIN; } } return commitWithin; } public void setCommitWithin(Double newCommitWithin) { commitWithin = newCommitWithin; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public boolean isSaveData() { return saveData; } public void setSaveData(boolean saveData) { this.saveData = saveData; } private static class SolrSchema { public final int version; private SolrField defaultType; private final Map<String, SolrField> types = new HashMap<String, SolrField>(); public SolrSchema(int version) { this.version = version; } public void setDefaultField(SolrField defaultType) { this.defaultType = defaultType; } public void mapFields(SolrField type, String... internalTypes) { if (internalTypes != null) { for (String internalType : internalTypes) { types.put(internalType, type); } } } public SolrField getField(String internalType) { SolrField type = types.get(internalType); return type != null ? type : defaultType; } } private static class SolrField { public final String facetPrefix; public final String searchPrefix; public final String sortPrefix; public final Set<String> addPrefixes; public final Set<String> setPrefixes; public SolrField(String facetPrefix, String searchPrefix, String sortPrefix, boolean allMultiValued) { this.facetPrefix = facetPrefix; this.searchPrefix = searchPrefix; this.sortPrefix = sortPrefix; Set<String> addPrefixes = new HashSet<String>(); addPrefixes.add(facetPrefix); addPrefixes.add(searchPrefix); Set<String> setPrefixes = new HashSet<String>(); setPrefixes.add(sortPrefix); if (allMultiValued) { setPrefixes.removeAll(addPrefixes); } else { addPrefixes.removeAll(setPrefixes); } this.addPrefixes = Collections.unmodifiableSet(addPrefixes); this.setPrefixes = Collections.unmodifiableSet(setPrefixes); } public SolrField(String facetPrefix, String searchPrefix, String sortPrefix) { this(facetPrefix, searchPrefix, sortPrefix, false); } } private final transient Lazy<SolrSchema> schema = new Lazy<SolrSchema>() { @Override protected SolrSchema create() { Exception error = query("*:*"); if (error != null) { throw new IllegalStateException("Solr server isn't available!", error); } SolrSchema schema; if (query("_e_test:1") == null) { schema = new SolrSchema(10); schema.setDefaultField(new SolrField("_sl_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); schema.mapFields(new SolrField("_g_", "_g_", "_g_"), ObjectField.LOCATION_TYPE); } else if (query("_query_:\"{!geofilt pt=0.0,0.0 sfield=_g_test d=1}\"") == null) { schema = new SolrSchema(9); schema.setDefaultField(new SolrField("_sl_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); schema.mapFields(new SolrField("_g_", "_g_", "_g_"), ObjectField.LOCATION_TYPE); } else if (query("_sl_test:1") == null) { schema = new SolrSchema(8); schema.setDefaultField(new SolrField("_sl_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); } else if (query("_ss_test:1") == null) { schema = new SolrSchema(7); schema.setDefaultField(new SolrField("_s_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); } else { schema = new SolrSchema(6); schema.setDefaultField(new SolrField("_s_", "_t_", "_s_")); schema.mapFields(new SolrField("_b_", "_b_", "_b_", true), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_d_", true), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_l_", true), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_u_", true), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); } LOGGER.info("Using Solr schema version [{}]", schema.version); return schema; } private Exception query(String query) { SolrServer server = openReadConnection(); SolrQuery solrQuery = new SolrQuery(query); solrQuery.setRows(0); try { server.query(solrQuery); return null; } catch (SolrServerException error) { return error; } } }; private SolrField getSolrField(String internalType) { return schema.get().getField(internalType); } private Query.MappedKey mapFullyDenormalizedKey(Query<?> query, String key) { Query.MappedKey mappedKey = query.mapDenormalizedKey(getEnvironment(), key); if (mappedKey.hasSubQuery()) { throw new Query.NoFieldException(query.getGroup(), key); } else { return mappedKey; } } public SolrQuery buildQueryFacetByField(Query<?> query, String field) { SolrQuery solrQuery = buildQuery(query); Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, field); String solrField = SPECIAL_FIELDS.get(mappedKey); if (solrField == null) { String internalType = mappedKey.getInternalType(); if (internalType != null) { solrField = getSolrField(internalType).searchPrefix + mappedKey.getIndexKey(null); } } if (solrField == null) { throw new UnsupportedIndexException(this, field); } solrQuery.setFacet(true); solrQuery.addFacetField(solrField); return solrQuery; } /** Builds a Solr query based on the given {@code query}. */ public SolrQuery buildQuery(Query<?> query) { SolrQuery solrQuery = new SolrQuery(); StringBuilder queryBuilder = new StringBuilder(); Predicate predicate = query.getPredicate(); if (predicate != null) { appendPredicate(query, queryBuilder, predicate); } Query<?> facetedQuery = query.getFacetQuery(); if (facetedQuery != null) { StringBuilder fq = new StringBuilder(); appendPredicate(facetedQuery, fq, query.getPredicate()); solrQuery.addFacetQuery(fq.toString()); solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); } Map<String, Object> facetedFields = query.getFacetedFields(); if (!facetedFields.isEmpty()) { boolean facet = false; for (Map.Entry<String, Object> entry : facetedFields.entrySet()) { String field = entry.getKey(); Object value = entry.getValue(); if (value != null) { Predicate p = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, field, ObjectUtils.to(Iterable.class, value)); StringBuilder filter = new StringBuilder(); appendPredicate(query, filter, p); solrQuery.addFilterQuery(filter.toString()); } else { Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, field); solrQuery.addFacetField(getSolrField(mappedKey.getInternalType()).facetPrefix + mappedKey.getIndexKey(null)); facet = true; } } if (facet) { solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); } } if (!query.isFromAll()) { Set<ObjectType> types = query.getConcreteTypes(getEnvironment()); if (!isAllTypes(types)) { if (types.isEmpty()) { if (queryBuilder.length() > 0) { queryBuilder.insert(0, '('); queryBuilder.append(") && "); } queryBuilder.append("-*:*"); } else { if (queryBuilder.length() > 0) { queryBuilder.insert(0, '('); queryBuilder.append(") && "); } queryBuilder.append("typeId:("); for (UUID typeId : query.getConcreteTypeIds(this)) { queryBuilder.append(Static.escapeValue(typeId)); queryBuilder.append(" || "); } queryBuilder.setLength(queryBuilder.length() - 4); queryBuilder.append(')'); } } } if (queryBuilder.length() < 1) { queryBuilder.append("*:*"); } StringBuilder sortBuilder = new StringBuilder(); for (Sorter sorter : query.getSorters()) { String operator = sorter.getOperator(); boolean isAscending = Sorter.ASCENDING_OPERATOR.equals(operator); if (isAscending || Sorter.DESCENDING_OPERATOR.equals(operator)) { String queryKey = (String) sorter.getOptions().get(0); Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, queryKey); String solrField = SPECIAL_FIELDS.get(mappedKey); if (solrField == null) { String internalType = mappedKey.getInternalType(); if (internalType != null) { solrField = getSolrField(internalType).sortPrefix + mappedKey.getIndexKey(null); } } if (solrField == null) { throw new UnsupportedIndexException(this, queryKey); } solrQuery.addSortField(solrField, isAscending ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc); continue; } else if (Sorter.RELEVANT_OPERATOR.equals(operator)) { Predicate sortPredicate = (Predicate) sorter.getOptions().get(1); double boost = ObjectUtils.to(double.class, sorter.getOptions().get(0)); if (boost < 0.0) { boost = -boost; sortPredicate = new CompoundPredicate(PredicateParser.NOT_OPERATOR, Arrays.asList(sortPredicate)); } solrQuery.addSortField(SCORE_FIELD, SolrQuery.ORDER.desc); sortBuilder.append('('); appendPredicate(query, sortBuilder, sortPredicate); sortBuilder.append(")^"); sortBuilder.append(boost); sortBuilder.append(" || "); continue; } else if (schema.get().version >= 9) { boolean closest = Sorter.CLOSEST_OPERATOR.equals(operator); if (closest || Sorter.FARTHEST_OPERATOR.equals(operator)) { Location location = (Location) sorter.getOptions().get(1); Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, (String) sorter.getOptions().get(0)); String internalType = mappedKey.getInternalType(); String oldField = solrQuery.get("sfield"); String newField = getSolrField(internalType).sortPrefix + mappedKey.getIndexKey(null); if (oldField == null) { solrQuery.set("sfield", newField); } else if (!oldField.equals(newField)) { throw new IllegalArgumentException("Can't query against more than one location at a time!"); } StringBuilder geoBuilder = new StringBuilder(); geoBuilder.append("geodist("); geoBuilder.append(location.getX()); geoBuilder.append(','); geoBuilder.append(location.getY()); geoBuilder.append(')'); solrQuery.setSortField(geoBuilder.toString(), closest ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc); continue; } } throw new UnsupportedSorterException(this, sorter); } if (sortBuilder.length() > 0) { queryBuilder.insert(0, "("); queryBuilder.append(") && ("); queryBuilder.append(sortBuilder); queryBuilder.append("*:*)"); } String tenant = getTenant(); if (tenant != null) { queryBuilder.insert(0, '('); queryBuilder.append(") && "); queryBuilder.append(TENANT_FIELD); queryBuilder.append(':'); queryBuilder.append(tenant); } solrQuery.setQuery(queryBuilder.toString()); return solrQuery; } /** * Transforms and appends the given {@code predicate} to the given * {@code queryBuilder}. */ private void appendPredicate(Query<?> query, StringBuilder queryBuilder, Predicate predicate) { if (predicate instanceof CompoundPredicate) { CompoundPredicate compoundPredicate = (CompoundPredicate) predicate; String operator = compoundPredicate.getOperator(); CompoundOperator solrOperator = COMPOUND_OPERATORS.get(operator); if (solrOperator != null) { List<Predicate> children = compoundPredicate.getChildren(); if (children.isEmpty()) { queryBuilder.append("*:*"); } else { solrOperator.appendCompound(this, query, queryBuilder, children); } return; } } else if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate; String queryKey = comparisonPredicate.getKey(); Query.MappedKey mappedKey = query.mapDenormalizedKey(getEnvironment(), queryKey); String solrField = SPECIAL_FIELDS.get(mappedKey); if (solrField == null) { String internalType = mappedKey.getInternalType(); if (internalType != null) { solrField = getSolrField(internalType).searchPrefix + mappedKey.getIndexKey(null); } } if (solrField == null) { throw new UnsupportedIndexException(this, queryKey); } String operator = comparisonPredicate.getOperator(); ComparisonOperator solrOperator = COMPARISON_OPERATORS.get(operator); if (solrOperator != null) { List<Object> values; Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate); if (valueQuery == null) { values = comparisonPredicate.resolveValues(this); } else { values = new ArrayList<Object>(); for (Object item : readPartial( valueQuery, 0, Settings.getOrDefault(int.class, "dari/subQueryResolveLimit", 100)). getItems()) { values.add(State.getInstance(item).getId()); } } solrOperator.appendComparison(queryBuilder, solrField, values); return; } } throw new UnsupportedPredicateException(this, predicate); } private final Map<String, CompoundOperator> COMPOUND_OPERATORS; { Map<String, CompoundOperator> m = new HashMap<String, CompoundOperator>(); m.put(PredicateParser.AND_OPERATOR, new StandardCompoundOperator("&&")); m.put(PredicateParser.OR_OPERATOR, new StandardCompoundOperator("||")); m.put(PredicateParser.NOT_OPERATOR, new CompoundOperator() { @Override protected void appendCompound( SolrDatabase database, Query<?> query, StringBuilder queryBuilder, List<Predicate> children) { queryBuilder.append("(*:*"); for (Predicate child : children) { queryBuilder.append(" && -("); database.appendPredicate(query, queryBuilder, child); queryBuilder.append(')'); } queryBuilder.append(')'); } }); COMPOUND_OPERATORS = m; } private abstract class CompoundOperator { protected abstract void appendCompound( SolrDatabase database, Query<?> query, StringBuilder queryBuilder, List<Predicate> children); } private class StandardCompoundOperator extends CompoundOperator { private final String join; public StandardCompoundOperator(String join) { this.join = join; } protected void appendCompound( SolrDatabase database, Query<?> query, StringBuilder queryBuilder, List<Predicate> children) { for (Predicate child : children) { queryBuilder.append('('); database.appendPredicate(query, queryBuilder, child); queryBuilder.append(") "); queryBuilder.append(join); queryBuilder.append(' '); } queryBuilder.setLength(queryBuilder.length() - join.length() - 2); } } private final Map<Query.MappedKey, String> SPECIAL_FIELDS; { Map<Query.MappedKey, String> m = new HashMap<Query.MappedKey, String>(); m.put(Query.MappedKey.ID, ID_FIELD); m.put(Query.MappedKey.TYPE, TYPE_ID_FIELD); m.put(Query.MappedKey.ANY, ALL_FIELD); SPECIAL_FIELDS = m; } private final Map<String, ComparisonOperator> COMPARISON_OPERATORS; { Map<String, ComparisonOperator> m = new HashMap<String, ComparisonOperator>(); m.put(PredicateParser.EQUALS_ANY_OPERATOR, new ExactMatchOperator(false, true)); m.put(PredicateParser.NOT_EQUALS_ALL_OPERATOR, new ExactMatchOperator(true, false)); m.put(PredicateParser.MATCHES_ANY_OPERATOR, new FullTextMatchOperator(false, true, false)); m.put(PredicateParser.MATCHES_ALL_OPERATOR, new FullTextMatchOperator(false, false, false)); m.put(PredicateParser.MATCHES_EXACT_ANY_OPERATOR, new FullTextMatchOperator(false, true, true)); m.put(PredicateParser.MATCHES_EXACT_ALL_OPERATOR, new FullTextMatchOperator(false, false, true)); m.put(PredicateParser.STARTS_WITH_OPERATOR, new MatchOperator(false, true) { @Override protected void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value) { comparisonBuilder.append(escapeValue(value)); comparisonBuilder.append('*'); } }); m.put(PredicateParser.LESS_THAN_OPERATOR, new RangeOperator("{* TO ", "}")); m.put(PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR, new RangeOperator("[* TO ", "]")); m.put(PredicateParser.GREATER_THAN_OPERATOR, new RangeOperator("{", " TO *}")); m.put(PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR, new RangeOperator("[", " TO *]")); COMPARISON_OPERATORS = m; } private abstract class ComparisonOperator { private final boolean isNegate; private final boolean isAny; private final String join; public ComparisonOperator(boolean isNegate, boolean isAny, String join) { this.isNegate = isNegate; this.isAny = isAny; this.join = join; } public void appendComparison( StringBuilder queryBuilder, String solrField, List<Object> values) { StringBuilder comparisonBuilder = new StringBuilder(); for (Object value : values) { if (ObjectUtils.isBlank(value)) { comparisonBuilder.append("(*:* && -*:*)"); } else { addValue(comparisonBuilder, solrField, value); } comparisonBuilder.append(join); } if (comparisonBuilder.length() > 0) { comparisonBuilder.setLength(comparisonBuilder.length() - 4); if (isNegate) { queryBuilder.append("(*:* && -"); } // field:(...) queryBuilder.append(changeSolrField(solrField)); queryBuilder.append(":("); queryBuilder.append(comparisonBuilder); queryBuilder.append(')'); if (isNegate) { queryBuilder.append(')'); } } else if (isAny) { queryBuilder.append("(*:* && -*:*)"); } else { queryBuilder.append("*:*"); } } protected abstract void addValue(StringBuilder comparisonBuilder, String solrField, Object value); protected String changeSolrField(String solrField) { return solrField.startsWith("_t_") ? (schema.get().version >= 8 ? "_sl_" : "_s_") + solrField.substring(3) : solrField; } protected String escapeValue(Object value) { String escaped = Static.escapeValue(value); if (escaped != null && schema.get().version >= 8) { escaped = escaped.trim().toLowerCase(Locale.ENGLISH); } return escaped; } } private abstract class MatchOperator extends ComparisonOperator { public MatchOperator(boolean isNegate, boolean isAny) { super(isNegate, isAny, isNegate ? (isAny ? " && " : " || ") : (isAny ? " || " : " && ")); } @Override protected void addValue(StringBuilder comparisonBuilder, String solrField, Object value) { if (value == Query.MISSING_VALUE) { if (solrField.startsWith("_g_")) { comparisonBuilder.append("(*:* && -[-90,-180 TO 90,180])"); } else { comparisonBuilder.append("(*:* && -[* TO *])"); } } else { addNonMissingValue(comparisonBuilder, solrField, value); } } protected abstract void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value); } private class ExactMatchOperator extends MatchOperator { public ExactMatchOperator(boolean isNegate, boolean isAny) { super(isNegate, isAny); } @Override protected void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value) { if (value instanceof Region) { List<Location> locations = ((Region) value).getLocations(); double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; for (Location location : locations) { double x = location.getX(); double y = location.getY(); if (minX > x) { minX = x; } else if (maxX < x) { maxX = x; } if (minY > y) { minY = y; } else if (maxY < y) { maxY = y; } } comparisonBuilder.append('['); comparisonBuilder.append(minX); comparisonBuilder.append(','); comparisonBuilder.append(minY); comparisonBuilder.append(" TO "); comparisonBuilder.append(maxX); comparisonBuilder.append(','); comparisonBuilder.append(maxY); comparisonBuilder.append(']'); } else { comparisonBuilder.append(escapeValue(value)); } } } private final static char[] UUID_WORD_CHARS = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static String uuidToWord(UUID uuid) { if (uuid == null) { return null; } byte[] bytes = UuidUtils.toBytes(uuid); int bytesLength = bytes.length; int wordLast = bytesLength * 2; byte currentByte; char[] word = new char[wordLast + 1]; for (int byteIndex = 0, hexIndex = 0; byteIndex < bytesLength; ++ byteIndex, ++ hexIndex) { currentByte = bytes[byteIndex]; word[hexIndex] = UUID_WORD_CHARS[(currentByte & 0xf0) >> 4]; ++ hexIndex; word[hexIndex] = UUID_WORD_CHARS[(currentByte & 0x0f)]; } word[wordLast] = 'z'; return new String(word); } private class FullTextMatchOperator extends MatchOperator { private final boolean isExact; public FullTextMatchOperator(boolean isNegate, boolean isAny, boolean isExact) { super(isNegate, isAny); this.isExact = isExact; } @Override protected void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value) { if (ALL_FIELD.equals(solrField)) { if ("*".equals(value)) { comparisonBuilder.append("*:*"); return; } else { UUID valueUuid = ObjectUtils.to(UUID.class, value); if (valueUuid != null) { comparisonBuilder.append(uuidToWord(valueUuid)); return; } } } String valueString = value.toString(); int valueStringLength = valueString.length(); if (valueStringLength == 0) { comparisonBuilder.append("(*:* && -*:*)"); } else { String escapedValue = escapeValue(valueString).toLowerCase(Locale.ENGLISH); if (valueString.length() == 1) { comparisonBuilder.append(escapedValue); } else { comparisonBuilder.append('('); comparisonBuilder.append(escapedValue); if (!isExact) { comparisonBuilder.append(" || "); comparisonBuilder.append(escapedValue); comparisonBuilder.append("*"); } comparisonBuilder.append(")"); } } } @Override protected String changeSolrField(String solrField) { return solrField; } } private class RangeOperator extends ComparisonOperator { private final String prefix; private final String suffix; public RangeOperator(String prefix, String suffix) { super(false, true, " || "); this.prefix = prefix; this.suffix = suffix; } @Override protected void addValue(StringBuilder comparisonBuilder, String solrField, Object value) { String valueString = value.toString(); if (schema.get().version >= 8) { valueString = valueString.trim().toLowerCase(Locale.ENGLISH); } comparisonBuilder.append(prefix); comparisonBuilder.append('"'); comparisonBuilder.append(valueString.replaceAll("([\\\\\"])", "\\\\$1")); comparisonBuilder.append('"'); comparisonBuilder.append(suffix); } } public SolrQuery buildSimilarQuery(Object object) { State state = State.getInstance(object); SolrQuery solrQuery = new SolrQuery(); solrQuery.setQueryType("/mlt"); solrQuery.set(MoreLikeThisParams.SIMILARITY_FIELDS, ALL_FIELD); solrQuery.set(MoreLikeThisParams.MIN_WORD_LEN, 2); solrQuery.set(MoreLikeThisParams.BOOST, true); StringBuilder streamBody = new StringBuilder(); addToStreamBody(streamBody, state.getSimpleValues()); solrQuery.set(CommonParams.STREAM_BODY, streamBody.toString()); solrQuery.add(CommonParams.FQ, "-id:" + state.getId()); return solrQuery; } private void addToStreamBody(StringBuilder streamBody, Object value) { if (value == null || value instanceof Boolean) { } else if (value instanceof Iterable) { for (Object item : (Iterable<?>) value) { addToStreamBody(streamBody, item); } } else if (value instanceof Map) { for (Object item : ((Map<?, ?>) value).values()) { addToStreamBody(streamBody, item); } } else { streamBody.append(value); streamBody.append(' '); } } /** * Queries the underlying Solr server with the given {@code query} * and options from the given {@code query}. */ public QueryResponse queryWithOptions(SolrQuery solrQuery, Query<?> query) { if (query != null && query.isReferenceOnly()) { solrQuery.setFields(ID_FIELD, TYPE_ID_FIELD); } else { solrQuery.setFields("*", SCORE_FIELD); } Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT); try { return openQueryConnection(query).query(solrQuery, SolrRequest.METHOD.POST); } catch (SolrServerException ex) { throw new DatabaseException(this, String.format( "Unable to read from the Solr server using [%s]!", solrQuery), ex); } finally { double duration = timer.stop(QUERY_STATS_OPERATION); Profiler.Static.stopThreadEvent(solrQuery); LOGGER.debug( "Read from the Solr server using [{}] in [{}]ms", solrQuery, duration); } } /** * Queries the underlying Solr server with the given * {@code solrQuery}. */ public QueryResponse query(SolrQuery solrQuery) { return queryWithOptions(solrQuery, null); } /** * Queries the underlying Solr server for a partial list of objects * that match the given {@code solrQuery} with the options from * the given {@code query}. */ public <T> SolrPaginatedResult<T> queryPartialWithOptions(SolrQuery solrQuery, Query<T> query) { QueryResponse response = queryWithOptions(solrQuery, query); SolrDocumentList documents = response.getResults(); long count = 0; List<T> objects = new ArrayList<T>(); if (documents != null) { count = documents.getNumFound(); for (SolrDocument document : documents) { objects.add(createSavedObjectWithDocument(document, documents, query)); } } return new SolrPaginatedResult<T>( solrQuery.getStart(), solrQuery.getRows(), count, objects, response.getLimitingFacets(), query != null ? query.getClass() : null, Settings.isDebug() ? solrQuery : null); } /** * Queries the underlying Solr server for a partial list of objects * that match the given {@code solrQuery}. */ public SolrPaginatedResult<Object> queryPartial(SolrQuery solrQuery) { return queryPartialWithOptions(solrQuery, null); } /** * Creates a previously saved object using the given {@code document}. */ private <T> T createSavedObjectWithDocument( SolrDocument document, SolrDocumentList documents, Query<T> query) { T object = createSavedObject(document.get(TYPE_ID_FIELD), document.get(ID_FIELD), query); State objectState = State.getInstance(object); if (!objectState.isReferenceOnly()) { String data = (String) document.get(DATA_FIELD); if (ObjectUtils.isBlank(data)) { Object original = objectState.getDatabase().readFirst(Query.from(Object.class).where("_id = ?", objectState.getId())); if (original != null) { objectState.setValues(State.getInstance(original).getSimpleValues()); } } else { @SuppressWarnings("unchecked") Map<String, Object> values = (Map<String, Object>) ObjectUtils.fromJson(data); objectState.setValues(values); } } Map<String, Object> extras = objectState.getExtras(); Object score = document.get(SCORE_FIELD); extras.put(SCORE_EXTRA, score); Float maxScore = documents.getMaxScore(); if (maxScore != null && score instanceof Number) { extras.put(NORMALIZED_SCORE_EXTRA, ((Number) score).floatValue() / maxScore); } return swapObjectType(query, object); } /** Commits all pending writes in the underlying Solr server. */ public void commit() { doCommit(openConnection()); } private void doCommit(SolrServer server) { Throwable error = null; try { Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(COMMIT_PROFILER_EVENT); try { server.commit(); } finally { double duration = timer.stop(COMMIT_STATS_OPERATION); Profiler.Static.stopThreadEvent(); LOGGER.debug("Solr commit time: [{}]ms", duration); } } catch (IOException e) { error = e; } catch (SolrServerException e) { error = e; } if (error != null) { throw new DatabaseException(this, "Can't commit to Solr!", error); } } @Override protected void doInitialize(String settingsKey, Map<String, Object> settings) { String url = ObjectUtils.to(String.class, settings.get(SERVER_URL_SUB_SETTING)); if (ObjectUtils.isBlank(url)) { throw new SettingsException( settingsKey + "/" + SERVER_URL_SUB_SETTING, "No Solr server URL!"); } try { setServer(new CommonsHttpSolrServer(url)); String readUrl = ObjectUtils.to(String.class, settings.get(READ_SERVER_URL_SUB_SETTING)); if (!ObjectUtils.isBlank(readUrl)) { setReadServer(new CommonsHttpSolrServer(readUrl)); } } catch (MalformedURLException ex) { throw new SettingsException( settingsKey + "/" + SERVER_URL_SUB_SETTING, String.format("[%s] is not a valid URL!", url)); } setTenant(ObjectUtils.to(String.class, settings.get(TENANT_SUB_SETTING))); setCommitWithin(ObjectUtils.to(Double.class, settings.get(COMMIT_WITHIN_SUB_SETTING))); setVersion(ObjectUtils.to(String.class, settings.get(VERSION_SUB_SETTING))); Boolean saveData = ObjectUtils.to(Boolean.class, settings.get(SAVE_DATA_SUB_SETTING)); if (saveData != null) { setSaveData(saveData); } } @Override public SolrServer openConnection() { return getServer(); } @Override protected SolrServer doOpenReadConnection() { SolrServer server = getReadServer(); return server != null ? server : getServer(); } @Override public void closeConnection(SolrServer server) { } @Override public <T> List<T> readAll(Query<T> query) { // Solr sometimes throws an OutOfMemoryError when the limit // is too large, so read all using 2 separate queries. SolrQuery solrQuery = buildQuery(query); solrQuery.setStart(0); solrQuery.setRows(INITIAL_FETCH_SIZE); PaginatedResult<T> result = queryPartialWithOptions(solrQuery, query); int count = (int) result.getCount(); List<T> all = new ArrayList<T>(count); all.addAll(result.getItems()); if (count > INITIAL_FETCH_SIZE) { solrQuery.setStart(INITIAL_FETCH_SIZE); solrQuery.setRows(count - INITIAL_FETCH_SIZE); all.addAll(queryPartialWithOptions(solrQuery, query).getItems()); } return all; } @Override public long readCount(Query<?> query) { SolrQuery solrQuery = buildQuery(query); solrQuery.setStart(0); solrQuery.setRows(0); SolrDocumentList documents = queryWithOptions(solrQuery, query).getResults(); return documents != null ? documents.getNumFound() : 0L; } @Override public <T> T readFirst(Query<T> query) { SolrQuery solrQuery = buildQuery(query); solrQuery.setStart(0); solrQuery.setRows(1); SolrDocumentList documents = queryWithOptions(solrQuery, query).getResults(); if (documents != null) { for (SolrDocument document : documents) { return createSavedObjectWithDocument(document, documents, query); } } return null; } @Override public Date readLastUpdate(Query<?> query) { throw new UnsupportedOperationException(); } @Override public <T> PaginatedResult<T> readPartial(Query<T> query, long offset, int limit) { SolrQuery solrQuery = buildQuery(query); solrQuery.setStart((int) offset); solrQuery.setRows(limit); return queryPartialWithOptions(solrQuery, query); } @Override public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) { if (fields == null || fields.length != 1) { return super.readPartialGrouped(query, offset, limit, fields); } SolrQuery solrQuery = buildQueryFacetByField(query, fields[0]); solrQuery.setStart(0); solrQuery.setRows(0); solrQuery.setFacetMinCount(1); List<Grouping<T>> groupings = new ArrayList<Grouping<T>>(); QueryResponse response = queryWithOptions(solrQuery, query); for (FacetField facetField : response.getFacetFields()) { List<FacetField.Count> values = facetField.getValues(); if (values == null) { continue; } for (FacetField.Count value : facetField.getValues()) { Object key = value.getName(); ObjectField field = mapFullyDenormalizedKey(query, fields[0]).getField(); if (field != null) { key = StateValueUtils.toJavaValue(query.getDatabase(), null, field, field.getInternalItemType(), key); } groupings.add(new SolrGrouping<T>(Arrays.asList(key), query, fields, value.getCount())); } } return new PaginatedResult<Grouping<T>>(offset, limit, groupings); } /** Solr-specific implementation of {@link Grouping}. */ private static class SolrGrouping<T> extends AbstractGrouping<T> { private final long count; public SolrGrouping(List<Object> keys, Query<T> query, String[] fields, long count) { super(keys, query, fields); this.count = count; } @Override protected Aggregate createAggregate(String field) { throw new UnsupportedOperationException(); } @Override public long getCount() { return count; } } @Override public void deleteByQuery(Query<?> query) { Throwable error = null; try { SolrServer server = openConnection(); server.deleteByQuery(buildQuery(query).getQuery()); doCommit(server); } catch (IOException e) { error = e; } catch (SolrServerException e) { error = e; } if (error != null) { throw new DatabaseException(this, String.format( "Can't delete documents matching [%s] from Solr!", query), error); } } @Override protected void commitTransaction(SolrServer server, boolean isImmediate) { if (isImmediate && getEffectiveCommitWithin() <= 0.0) { doCommit(openConnection()); } } private void processUpdate( SolrServer server, UpdateRequest update, boolean isImmediate) throws IOException, SolrServerException { if (isImmediate) { double commitWithin = getEffectiveCommitWithin(); if (commitWithin > 0.0) { update.setCommitWithin((int) (commitWithin * 1000)); } } update.process(server); } @Override protected void doSaves(SolrServer server, boolean isImmediate, List<State> states) { Set<String> databaseGroups = getGroups(); List<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(); String tenant = getTenant(); for (State state : states) { ObjectType type = state.getType(); if (type != null) { boolean savable = false; for (String typeGroup : type.getGroups()) { if (databaseGroups.contains(typeGroup)) { savable = true; break; } } if (!savable) { continue; } } else { // skip processing States with no typeId continue; } Map<String, Object> stateValues = state.getSimpleValues(); SolrInputDocument document = new SolrInputDocument(); StringBuilder allBuilder = new StringBuilder(); documents.add(document); document.setField(ID_FIELD, state.getId()); document.setField(TYPE_ID_FIELD, state.getVisibilityAwareTypeId()); if (isSaveData()) { document.setField(DATA_FIELD, ObjectUtils.toJson(stateValues)); } if (schema.get().version >= 10) { Set<String> typeAheadFields = type.as(TypeModification.class).getTypeAheadFields(); Map<String, List<String>> typeAheadFieldsMap = type.as(TypeModification.class).getTypeAheadFieldsMap(); if (!typeAheadFields.isEmpty()) { for (String typeAheadField : typeAheadFields) { String value = ObjectUtils.to(String.class, state.getByPath(typeAheadField)); // Hack for a client. if (!ObjectUtils.isBlank(value)) { value = value.replaceAll("\\{", "").replaceAll("\\}", ""); document.setField(SUGGESTION_FIELD, value); } } } if (!typeAheadFieldsMap.isEmpty()) { for (Map.Entry<String, List<String>> entry : typeAheadFieldsMap.entrySet()) { String typeAheadField = entry.getKey(); List<String> targetFields = entry.getValue(); String value = ObjectUtils.to(String.class, state.getByPath(typeAheadField)); if (!ObjectUtils.isBlank(targetFields)) { for (String targetField : targetFields) { if (!ObjectUtils.isBlank(value)) { value = value.replaceAll("\\{", "").replaceAll("\\}", ""); document.setField("_e_" + targetField, value); } } } } } } for (Map.Entry<String, Object> entry : stateValues.entrySet()) { String fieldName = entry.getKey(); ObjectField field = state.getField(fieldName); if (field == null) { continue; } String uniqueName = field.getUniqueName(); addDocumentValues( document, allBuilder, true, field, uniqueName, entry.getValue()); } document.setField(ALL_FIELD, allBuilder.toString()); SolrField labelField = schema.get().getField(ObjectField.TEXT_TYPE); String label = state.getLabel().trim().toLowerCase(Locale.ENGLISH); for (String prefix : labelField.addPrefixes) { document.addField(prefix + Query.LABEL_KEY, label); } for (String prefix : labelField.setPrefixes) { document.setField(prefix + Query.LABEL_KEY, label); } if (tenant != null) { document.setField(TENANT_FIELD, tenant); } } int documentsSize = documents.size(); if (documentsSize == 0) { return; } Throwable error = null; try { Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(ADD_PROFILER_EVENT, documentsSize); try { UpdateRequest update = new UpdateRequest(); update.add(documents); processUpdate(server, update, isImmediate); } finally { double duration = timer.stop(ADD_STATS_OPERATION); Profiler.Static.stopThreadEvent(); LOGGER.debug("Solr add: [{}], Time: [{}]ms", documentsSize, duration); } } catch (IOException e) { error = e; } catch (SolrServerException e) { error = e; } if (error != null) { throw new DatabaseException(this, String.format( "Can't add [%s] documents to Solr!", documentsSize), error); } } // Adds all items within the given {@code value} to the given // {@code document} at the given {@code name}. private void addDocumentValues( SolrInputDocument document, StringBuilder allBuilder, boolean includeInAny, ObjectField field, String name, Object value) { if (value == null) { return; } if (value instanceof List) { for (Object item : (List<?>) value) { addDocumentValues(document, allBuilder, includeInAny, field, name, item); } return; } if (includeInAny) { includeInAny = field == null || !field.as(FieldData.class).isExcludeFromAny(); } if (value instanceof Recordable) { value = ((Recordable) value).getState().getSimpleValues(); } if (value instanceof Map) { Map<?, ?> valueMap = (Map<?, ?>) value; if (schema.get().version >= 9 && field.getInternalItemType().equals(ObjectField.LOCATION_TYPE)) { if (valueMap.containsKey("x") && valueMap.containsKey("y")) { value = valueMap.get("x") + "," + valueMap.get("y"); } else { return; } } else { UUID valueTypeId = ObjectUtils.to(UUID.class, valueMap.get(StateValueUtils.TYPE_KEY)); if (valueTypeId == null) { for (Object item : valueMap.values()) { addDocumentValues(document, allBuilder, includeInAny, field, name, item); } return; } else { UUID valueId = ObjectUtils.to(UUID.class, valueMap.get(StateValueUtils.REFERENCE_KEY)); if (valueId == null) { if (includeInAny) { allBuilder.append(valueTypeId).append(' '); } ObjectType valueType = getEnvironment().getTypeById(valueTypeId); if (valueType != null) { for (Map.Entry<?, ?> entry : valueMap.entrySet()) { String subName = entry.getKey().toString(); ObjectField subField = valueType.getField(subName); if (subField != null) { addDocumentValues( document, allBuilder, includeInAny, subField, name + "/" + subName, entry.getValue()); } } } return; } else { value = valueId; Set<ObjectField> denormFields = field.getEffectiveDenormalizedFields(getEnvironment().getTypeById(valueTypeId)); if (denormFields != null) { State valueState = State.getInstance(Query.from(Object.class).where("_id = ?", valueId).first()); if (valueState != null) { Map<String, Object> valueValues = valueState.getSimpleValues(); for (ObjectField denormField : denormFields) { String denormFieldName = denormField.getInternalName(); addDocumentValues( document, allBuilder, includeInAny, denormField, name + "/" + denormFieldName, valueValues.get(denormFieldName)); } } } } } } } String trimmed = value.toString().trim(); Matcher uuidMatcher = UUID_PATTERN.matcher(trimmed); int uuidLast = 0; while (uuidMatcher.find()) { if (includeInAny) { allBuilder.append(trimmed.substring(uuidLast, uuidMatcher.start())); } uuidLast = uuidMatcher.end(); String word = uuidToWord(ObjectUtils.to(UUID.class, uuidMatcher.group(0))); if (includeInAny && word != null) { allBuilder.append(word); } } if (includeInAny) { allBuilder.append(trimmed.substring(uuidLast)); allBuilder.append(' '); } if (value instanceof String && schema.get().version >= 8) { value = ((String) value).trim().toLowerCase(Locale.ENGLISH); } SolrField solrField = getSolrField(field.getInternalItemType()); for (String prefix : solrField.addPrefixes) { document.addField(prefix + name, value); } for (String prefix : solrField.setPrefixes) { document.setField(prefix + name, value); } } @Override protected void doDeletes(SolrServer server, boolean isImmediate, List<State> states) { List<String> idStrings = new ArrayList<String>(); for (State state : states) { idStrings.add(state.getId().toString()); } int statesSize = states.size(); Throwable error = null; try { Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(DELETE_PROFILER_EVENT, statesSize); try { UpdateRequest update = new UpdateRequest(); update.deleteById(idStrings); processUpdate(openConnection(), update, isImmediate); } finally { double duration = timer.stop(DELETE_STATS_OPERATION); Profiler.Static.stopThreadEvent(); LOGGER.debug("Solr delete: [{}], Time: [{}]ms", statesSize, duration); } } catch (IOException e) { error = e; } catch (SolrServerException e) { error = e; } if (error != null) { throw new DatabaseException(this, String.format( "Can't delete [%s] documents from Solr!", statesSize), error); } } /** {@link SolrDatabase} utility methods. */ public static final class Static { private static final Pattern ESCAPE_PATTERN = Pattern.compile("([-+&|!(){}\\[\\]^\"~*?:\\\\\\s])"); /** * Escapes the given {@code value} so that it's safe to use * in a Solr query. * * @param value If {@code null}, returns {@code null}. */ public static final String escapeValue(Object value) { return value != null ? ESCAPE_PATTERN.matcher(value.toString()).replaceAll("\\\\$1") : null; } /** * Returns the Solr search result score associated with the given * {@code object}. * * @return May be {@code null} if the score isn't available. */ public static Float getScore(Object object) { return (Float) State.getInstance(object).getExtra(SCORE_EXTRA); } /** * Returns the normalized Solr search result score, in a scale of * {@code 0.0} to {@code 1.0}, associated with the given * {@code object}. * * @return May be {@code null} if the score isn't available. */ public static Float getNormalizedScore(Object object) { return (Float) State.getInstance(object).getExtra(NORMALIZED_SCORE_EXTRA); } } /** * Specifies all fields that are stored for type-ahead from an * instance of the target type. */ @Documented @Inherited @ObjectType.AnnotationProcessorClass(TypeAheadFieldsProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface TypeAheadFields { String[] value() default { }; TypeAheadFieldsMapping[] mappings() default { }; } public @interface TypeAheadFieldsMapping { String field(); String[] solrFields(); } private static class TypeAheadFieldsProcessor implements ObjectType.AnnotationProcessor<TypeAheadFields> { @Override public void process(ObjectType type, TypeAheadFields annotation) { Map <String, List<String>> typeAheadFieldsMap = new HashMap<String, List<String>>(); for (TypeAheadFieldsMapping mapping : annotation.mappings()) { List<String> fields = Arrays.asList(mapping.solrFields()); typeAheadFieldsMap.put(mapping.field(), fields); } Collections.addAll(type.as(TypeModification.class).getTypeAheadFields(), annotation.value()); type.as(TypeModification.class).setTypeAheadFieldsMap(typeAheadFieldsMap); } } @Documented @Inherited @ObjectField.AnnotationProcessorClass(ExcludeFromAnyProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ExcludeFromAny { boolean value() default true; } private static class ExcludeFromAnyProcessor implements ObjectField.AnnotationProcessor<ExcludeFromAny> { @Override public void process(ObjectType type, ObjectField field, ExcludeFromAny annotation) { field.as(FieldData.class).setExcludeFromAny(annotation.value()); } } @TypeModification.FieldInternalNamePrefix("solr.") public static class TypeModification extends Modification<ObjectType> { private Set<String> typeAheadFields; private Map<String, List<String>> typeAheadFieldsMap; public Set<String> getTypeAheadFields() { if (typeAheadFields == null) { typeAheadFields = new HashSet<String>(); } return typeAheadFields; } public void setTypeAheadFields(Set<String> typeAheadFields) { this.typeAheadFields = typeAheadFields; } public Map<String, List<String>> getTypeAheadFieldsMap() { if (null == typeAheadFieldsMap) { typeAheadFieldsMap = new HashMap<String, List<String>>(); } return typeAheadFieldsMap; } public void setTypeAheadFieldsMap(Map<String, List<String>> typeAheadFieldsMap) { this.typeAheadFieldsMap = typeAheadFieldsMap; } } @Modification.FieldInternalNamePrefix("solr.") public static class FieldData extends Modification<ObjectField> { private boolean excludeFromAny; public boolean isExcludeFromAny() { return excludeFromAny; } public void setExcludeFromAny(boolean excludeFromAny) { this.excludeFromAny = excludeFromAny; } } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public static final String MAXIMUM_DOCUMENTS_SETTING = "maximumDocuments"; /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public static final String MAXIMUM_TIME_SETTING = "maximumTime"; /** @deprecated Use {@link #SERVER_URL_SUB_SETTING} instead. */ @Deprecated public static final String SERVER_URL_SETTING = SERVER_URL_SUB_SETTING; /** @deprecated Use {@link #READ_SERVER_URL_SUB_SETTING} instead. */ @Deprecated public static final String READ_SERVER_URL_SETTING = READ_SERVER_URL_SUB_SETTING; /** @deprecated Use {@link Static#escapeValue} instead. */ @Deprecated public static final String quoteValue(Object value) { return Static.escapeValue(String.valueOf(value)); } /** @deprecated Use {@link Static#getScore} instead. */ @Deprecated public static Float getScore(Object object) { return (Float) State.getInstance(object).getExtra(SCORE_EXTRA); } /** @deprecated Use {@link Static#getNormalizedScore} instead. */ @Deprecated public static Float getNormalizedScore(Object object) { return (Float) State.getInstance(object).getExtra(NORMALIZED_SCORE_EXTRA); } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public Long getMaximumDocuments() { return null; } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public void setMaximumDocuments(Long maximumDocuments) { } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public Long getMaximumTime() { return null; } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public void setMaximumTime(Long maximumTime) { } /** @deprecated Use {@link #buildQuery} instead. */ @Deprecated public SolrQuery buildSolrQuery(Query<?> query) { return buildQuery(query); } /** @deprecated Use {@link #commit} instead. */ @Deprecated public void commitImmediately() { commit(); } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public void commitEventually() { } }
package jlibs.core.lang; import jlibs.core.io.ByteArrayOutputStream2; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; /** * @author Santhosh Kumar T */ public class Util{ /** * Returns first non null element in <code>values</code>. * If all elements are null, it returns null. */ public static <T> T notNull(T... values){ for(T value: values){ if(value!=null) return value; } return null; } /** * Returns true if given two objects are same. * * null values are handled as follows: * null != non-null * null == null * * Arrays are handled using Arrays.equals(...) */ public static boolean equals(Object obj1, Object obj2){ if(obj1==obj2) return true; else if(obj1==null || obj2==null) return false; else if(obj1.getClass().isArray()){ if(obj2.getClass().isArray()){ if(obj1 instanceof Object[] && obj2 instanceof Object[]) return Arrays.deepEquals((Object[])obj1, (Object[])obj2); else if(obj1 instanceof boolean[] && obj2 instanceof boolean[]) return Arrays.equals((boolean[])obj1, (boolean[])obj2); else if(obj1 instanceof char[] && obj2 instanceof char[]) return Arrays.equals((char[])obj1, (char[])obj2); else if(obj1 instanceof byte[] && obj2 instanceof byte[]) return Arrays.equals((byte[])obj1, (byte[])obj2); else if(obj1 instanceof short[] && obj2 instanceof short[]) return Arrays.equals((short[])obj1, (short[])obj2); else if(obj1 instanceof int[] && obj2 instanceof int[]) return Arrays.equals((int[])obj1, (int[])obj2); else if(obj1 instanceof long[] && obj2 instanceof long[]) return Arrays.equals((long[])obj1, (long[])obj2); else if(obj1 instanceof float[] && obj2 instanceof float[]) return Arrays.equals((float[])obj1, (float[])obj2); else if(obj1 instanceof double[] && obj2 instanceof double[]) return Arrays.equals((double[])obj1, (double[])obj2); else throw new ImpossibleException("couldn't do equals for"+obj1.getClass().getComponentType().getSimpleName()+"[]"); }else return false; }else return obj1.equals(obj2); } /** * returns hashCode of given argument. * if argument is null, returns 0 */ public static int hashCode(Object obj){ if(obj==null) return 0; else if(obj.getClass().isArray()){ if(obj instanceof Object[]) return Arrays.deepHashCode((Object[])obj); else if(obj instanceof boolean[]) return Arrays.hashCode((boolean[])obj); else if(obj instanceof char[]) return Arrays.hashCode((char[])obj); else if(obj instanceof byte[]) return Arrays.hashCode((byte[])obj); else if(obj instanceof short[]) return Arrays.hashCode((short[])obj); else if(obj instanceof int[]) return Arrays.hashCode((int[])obj); else if(obj instanceof long[]) return Arrays.hashCode((long[])obj); else if(obj instanceof float[]) return Arrays.hashCode((float[])obj); else if(obj instanceof double[]) return Arrays.hashCode((double[])obj); else throw new ImpossibleException("couldn't find hascode for"+obj.getClass().getComponentType().getSimpleName()+"[]"); }else return obj.hashCode(); } /** * returns hashCode of given arguments. * if any argument is null, then it considers * its hashCode as zero */ public static int hashCode(Object... objects){ int hashCode = 0; for(Object obj: objects) hashCode = 31*hashCode + hashCode(obj); return hashCode; } @SuppressWarnings({"ThrowableInstanceNeverThrown", "unchecked"}) public static <T> T clone(T obj) throws CloneNotSupportedException{ if(obj==null) return null; try{ if(obj instanceof Cloneable){ Method method = obj.getClass().getMethod("clone"); if(!Modifier.isPublic(method.getModifiers())) method.setAccessible(true); return (T)method.invoke(obj); }else if(obj instanceof Serializable){ ByteArrayOutputStream2 bout = new ByteArrayOutputStream2(); ObjectOutputStream objOut = new ObjectOutputStream(bout); objOut.writeObject(obj); objOut.close(); ObjectInputStream objIn = new ObjectInputStream(bout.toByteSequence().asInputStream()); return (T)objIn.readObject(); }else throw new CloneNotSupportedException(obj.getClass().getName()); }catch(Exception ex){ if(ex instanceof CloneNotSupportedException) throw (CloneNotSupportedException)ex; else throw (CloneNotSupportedException)new CloneNotSupportedException().initCause(ex); } } public static long parseLong(String value){ int len = value.length(); if(len==0) throw new NumberFormatException("empty string"); int i = 0; boolean negative = false; char firstChar = value.charAt(0); if(firstChar<'0'){ if(firstChar=='-') negative = true; else if(firstChar!='+') throw new NumberFormatException("for input string \""+value+"\""); if(len==1) throw new NumberFormatException("cannot have lone + or -"); ++i; } int result = 0; while(i<len){ char ch = value.charAt(i++); if(ch>='0' && ch<='9') result = result*10 + (ch-'0'); else throw new NumberFormatException("for input string \""+value+"\""); } return negative ? -result : result; } }
package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_EXTENDED = 0x40; private static final int LABEL_LOCAL_COMPRESSION = 0x80; private static final int LABEL_MASK = 0xC0; private static final int EXT_LABEL_COMPRESSION = 0; private static final int EXT_LABEL_BITSTRING = 1; private static final int EXT_LABEL_LOCAL_COMPRESSION = 2; private Object [] name; private byte labels; private boolean qualified; /** The root name */ public static Name root = new Name("."); /** The maximum number of labels in a Name */ static final int MAXLABELS = 256; /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is unqalified, the origin to be appended */ public Name(String s, Name origin) { labels = 0; name = new Object[MAXLABELS]; if (s.equals("@") && origin != null) { append(origin); qualified = true; return; } try { MyStringTokenizer st = new MyStringTokenizer(s, "."); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.charAt(0) == '[') name[labels++] = new BitString(token); else name[labels++] = token; } if (st.hasMoreDelimiters()) qualified = true; else { if (origin != null) { append(origin); qualified = true; } else { /* This isn't exactly right, but it's close. * Partially qualified names are evil. */ if (Options.check("pqdn")) qualified = false; else qualified = (labels > 1); } } } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append(s); if (origin != null) { sb.append("."); sb.append(origin); } if (e instanceof ArrayIndexOutOfBoundsException) sb.append(" has too many labels"); else if (e instanceof IOException) sb.append(" contains an invalid binary label"); else sb.append(" is invalid"); System.err.println(sb.toString()); name = null; labels = 0; } } /** * Create a new name from a string * @param s The string to be converted */ public Name(String s) { this (s, null); } /** * Create a new name from DNS wire format * @param in A stream containing the input data * @param c The compression context. This should be null unless a full * message is being parsed. */ public Name(DataByteInputStream in, Compression c) throws IOException { int len, start, pos, count = 0; Name name2; labels = 0; name = new Object[MAXLABELS]; start = in.getPos(); loop: while ((len = in.readUnsignedByte()) != 0) { switch(len & LABEL_MASK) { case LABEL_NORMAL: byte [] b = new byte[len]; in.read(b); name[labels++] = new String(b); count++; break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException("bad compression"); else { System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case LABEL_EXTENDED: int type = len & ~LABEL_MASK; switch (type) { case EXT_LABEL_COMPRESSION: pos = in.readUnsignedShort(); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException( "bad compression"); else { System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case EXT_LABEL_BITSTRING: int bits = in.readUnsignedByte(); if (bits == 0) bits = 256; int bytes = (bits + 7) / 8; byte [] data = new byte[bytes]; in.read(data); name[labels++] = new BitString(bits, data); count++; break; case EXT_LABEL_LOCAL_COMPRESSION: throw new WireParseException( "Long local compression"); default: throw new WireParseException( "Unknown name format"); } /* switch */ break; case LABEL_LOCAL_COMPRESSION: throw new WireParseException("Local compression"); } /* switch */ } if (c != null) { pos = start; if (Options.check("verbosecompression")) System.out.println("name = " + this + ", count = " + count); for (int i = 0; i < count; i++) { Name tname = new Name(this, i); c.add(pos, tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + pos); if (name[i] instanceof String) pos += (((String)name[i]).length() + 1); else pos += (((BitString)name[i]).bytes() + 2); } } qualified = true; } /** * Create a new name by removing labels from the beginning of an existing Name * @param d An existing Name * @param n The number of labels to remove from the beginning in the copy */ /* Skips n labels and creates a new name */ public Name(Name d, int n) { name = new Object[MAXLABELS]; labels = (byte) (d.labels - n); System.arraycopy(d.name, n, name, 0, labels); qualified = d.qualified; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { Name wild = new Name(this, n - 1); wild.name[0] = "*"; return wild; } /** * Is this name a wildcard? */ public boolean isWild() { return (labels > 0 && name[0].equals("*")); } /** * Is this name fully qualified? */ public boolean isQualified() { return qualified; } /** * Appends the specified name to the end of the current Name */ public void append(Name d) { System.arraycopy(d.name, 0, name, labels, d.labels); labels += d.labels; } /** * The length */ public short length() { short total = 0; for (int i = 0; i < labels; i++) { if (name[i] instanceof String) total += (((String)name[i]).length() + 1); else total += (((BitString)name[i]).bytes() + 2); } return ++total; } /** * The number of labels */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; int i = labels, j = domain.labels; while (j > 0) if (!name[--i].equals(domain.name[--j])) return false; return true; } /** * Convert Name to a String */ public String toString() { StringBuffer sb = new StringBuffer(); if (labels == 0) sb.append("."); for (int i = 0; i < labels; i++) { sb.append(name[i]); if (qualified || i < labels - 1) sb.append("."); } return sb.toString(); } /** * Convert Name to DNS wire format */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { for (int i = 0; i < labels; i++) { Name tname = new Name(this, i); int pos = -1; if (c != null) { pos = c.get(tname); if (Options.check("verbosecompression")) System.err.println("Looking for " + tname + ", found " + pos); } if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) { c.add(out.getPos(), tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + out.getPos()); } if (name[i] instanceof String) out.writeString((String)name[i]); else { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public void toWireCanonical(DataByteOutputStream out) throws IOException { for (int i = 0; i < labels; i++) { if (name[i] instanceof String) out.writeStringCanonical((String)name[i]); else { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } } out.writeByte(0); } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.labels != labels) return false; for (int i = 0; i < labels; i++) { if (name[i].getClass() != d.name[i].getClass()) return false; if (name[i] instanceof String) { String s1 = (String) name[i]; String s2 = (String) d.name[i]; if (!s1.equalsIgnoreCase(s2)) return false; } else { /* BitString */ if (!name[i].equals(d.name[i])) return false; } } return true; } /** * Computes a hashcode based on the value */ public int hashCode() { int code = labels; for (int i = 0; i < labels; i++) { if (name[i] instanceof String) { String s = (String) name[i]; for (int j = 0; j < s.length(); j++) code += Character.toLowerCase(s.charAt(j)); } else { BitString b = (BitString) name[i]; for (int j = 0; j < b.bytes(); j++) code += b.data[i]; } } return code; } }
package com.michelin.cio.hudson.plugins.maskpasswords; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.console.ConsoleLogFilter; import hudson.model.AbstractBuild; import hudson.model.AbstractDescribableImpl; import hudson.model.AbstractProject; import hudson.model.Descriptor; import hudson.model.ParameterValue; import hudson.model.ParametersAction; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildWrapperDescriptor; import hudson.util.Secret; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import jenkins.tasks.SimpleBuildWrapper; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.structs.describable.CustomDescribableModel; import org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable; import org.jvnet.localizer.Localizable; import org.jvnet.localizer.ResourceBundleHolder; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; public final class MaskPasswordsBuildWrapper extends SimpleBuildWrapper { private final List<VarPasswordPair> varPasswordPairs; private final List<VarMaskRegex> varMaskRegexes; @DataBoundConstructor public MaskPasswordsBuildWrapper(List<VarPasswordPair> varPasswordPairs, List<VarMaskRegex> varMaskRegexes) { this.varPasswordPairs = varPasswordPairs; this.varMaskRegexes = varMaskRegexes; } public MaskPasswordsBuildWrapper(List<VarPasswordPair> varPasswordPairs) { this.varPasswordPairs = varPasswordPairs; this.varMaskRegexes = new ArrayList<VarMaskRegex>(); } @Override public ConsoleLogFilter createLoggerDecorator(Run<?, ?> build) { List<String> allPasswords = new ArrayList<String>(); // all passwords to be masked List<String> allRegexes = new ArrayList<String>(); // all regexes to be masked MaskPasswordsConfig config = MaskPasswordsConfig.getInstance(); // global passwords List<VarPasswordPair> globalVarPasswordPairs = config.getGlobalVarPasswordPairs(); for(VarPasswordPair globalVarPasswordPair: globalVarPasswordPairs) { allPasswords.add(globalVarPasswordPair.getPlainTextPassword()); } // global regexes List<VarMaskRegex> globalVarMaskRegexes = config.getGlobalVarMaskRegexes(); for(VarMaskRegex globalVarMaskRegex: globalVarMaskRegexes) { allRegexes.add(globalVarMaskRegex.getRegex()); } // job's passwords if(varPasswordPairs != null) { for(VarPasswordPair varPasswordPair: varPasswordPairs) { String password = varPasswordPair.getPlainTextPassword(); if(StringUtils.isNotBlank(password)) { allPasswords.add(password); } } } // job's regexes if(varMaskRegexes != null) { for(VarMaskRegex varMaskRegex: varMaskRegexes) { String regex = varMaskRegex.getRegex(); if(StringUtils.isNotBlank(regex)) { allRegexes.add(regex); } } } // find build parameters which are passwords (PasswordParameterValue) ParametersAction params = build.getAction(ParametersAction.class); if(params != null) { for(ParameterValue param : params) { if(config.isMasked(param, param.getClass().getName())) { EnvVars env = new EnvVars(); param.buildEnvironment(build, env); String password = env.get(param.getName()); if(StringUtils.isNotBlank(password)) { allPasswords.add(password); } } } } return new FilterImpl(allPasswords, allRegexes); } @Override public boolean requiresWorkspace() { return false; } private static final class FilterImpl extends ConsoleLogFilter implements Serializable { private static final long serialVersionUID = 1L; private final List<Secret> allPasswords; private final List<String> allRegexes; FilterImpl(List<String> allPasswords, List<String> allRegexes) { this.allPasswords = new ArrayList<Secret>(); this.allRegexes = new ArrayList<String>(); for (String password : allPasswords) { this.allPasswords.add(Secret.fromString(password)); } for (String regex : allRegexes) { this.allRegexes.add(regex); } } @SuppressWarnings("rawtypes") @Override public OutputStream decorateLogger(AbstractBuild _ignore, OutputStream logger) throws IOException, InterruptedException { List<String> passwords = new ArrayList<String>(); List<String> regexes = new ArrayList<String>(); for (Secret password : allPasswords) { passwords.add(password.getPlainText()); } for (String regex : allRegexes) { regexes.add(regex); } return new MaskPasswordsOutputStream(logger, passwords, regexes); } } /** * Contributes the passwords defined by the user as variables that can be reused * from build steps (and other places). */ @Override public void makeBuildVariables(AbstractBuild build, Map<String, String> variables) { // global var/password pairs MaskPasswordsConfig config = MaskPasswordsConfig.getInstance(); List<VarPasswordPair> globalVarPasswordPairs = config.getGlobalVarPasswordPairs(); // we can't use variables.putAll() since passwords are ciphered when in varPasswordPairs for(VarPasswordPair globalVarPasswordPair: globalVarPasswordPairs) { variables.put(globalVarPasswordPair.getVar(), globalVarPasswordPair.getPlainTextPassword()); } // job's var/password pairs if(varPasswordPairs != null) { // cf. comment above for(VarPasswordPair varPasswordPair: varPasswordPairs) { if(StringUtils.isNotBlank(varPasswordPair.getVar())) { variables.put(varPasswordPair.getVar(), varPasswordPair.getPlainTextPassword()); } } } } @Override public void makeSensitiveBuildVariables(AbstractBuild build, Set<String> sensitiveVariables) { final Map<String, String> variables = new TreeMap<String, String>(); makeBuildVariables(build, variables); sensitiveVariables.addAll(variables.keySet()); } @Override public void setUp(Context context, Run<?, ?> build, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException { // nothing to do here } public List<VarPasswordPair> getVarPasswordPairs() { return varPasswordPairs; } public List<VarMaskRegex> getVarMaskRegexes() { return varMaskRegexes; } /** * Represents name/password entries defined by users in their jobs. * Equality and hashcode are based on {@code var} only, not {@code password}. * If the class gets extended, a <code>clone()</code> method must be implemented without <code>super.clone()</code> calls. */ public static class VarPasswordPair extends AbstractDescribableImpl<VarPasswordPair> implements Cloneable { private final String var; private final Secret password; @DataBoundConstructor public VarPasswordPair(String var, Secret password) { this.var = var; this.password = password; } @Override @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL", justification = "We do not expect anybody to use this class." + "If they do, they must override clone() as well") public Object clone() { return new VarPasswordPair(getVar(), password); } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } final VarPasswordPair other = (VarPasswordPair) obj; return Objects.equals(this.var, other.var); } public String getVar() { return var; } public Secret getPassword() { return password; } public String getPlainTextPassword() { if (password == null || StringUtils.isBlank(password.getPlainText())) { return null; } return password.getPlainText(); } @Override public int hashCode() { int hash = 3; hash = 67 * hash + (this.var != null ? this.var.hashCode() : 0); return hash; } @Extension /** * {@link CustomDescribableModel} is needed because pipeline doesn't natively support the {@link Secret} class * but we need Secret so that data-binding works correctly. */ public static class DescriptorImpl extends Descriptor<VarPasswordPair> implements CustomDescribableModel { @Nonnull @Override public UninstantiatedDescribable customUninstantiate(@Nonnull UninstantiatedDescribable step) { Map<String, ?> arguments = step.getArguments(); Map<String, Object> newMap1 = new HashMap<>(); newMap1.put("var", arguments.get("var")); newMap1.put("password", ((Secret) arguments.get("password")).getPlainText()); return step.withArguments(newMap1); } @Nonnull @Override public Map<String, Object> customInstantiate(@Nonnull Map<String, Object> arguments) { Map<String, Object> newMap = new HashMap<>(); newMap.put("var", arguments.get("var")); Object password = arguments.get("password"); if (password instanceof String) { password = Secret.fromString((String) password); } newMap.put("password", password); return newMap; } } } /** * Represents regexes defined by users in their jobs. * If the class gets extended, a <code>clone()</code> method must be implemented without <code>super.clone()</code> calls. */ public static class VarMaskRegex extends AbstractDescribableImpl<VarMaskRegex> implements Cloneable { private final String regex; @DataBoundConstructor public VarMaskRegex(String regex) { this.regex = regex; } @Override @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL", justification = "We do not expect anybody to use this class." + "If they do, they must override clone() as well") public Object clone() { return new VarMaskRegex(getRegex()); } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } final VarMaskRegex other = (VarMaskRegex) obj; return Objects.equals(this.regex, other.regex); } @CheckForNull public String getRegex() { return regex; } @Override public int hashCode() { int hash = 3; hash = 67 * hash + (this.regex != null ? this.regex.hashCode() : 0); return hash; } @Extension public static class DescriptorImpl extends Descriptor<VarMaskRegex> {} } @Symbol("maskPasswords") @Extension(ordinal = 100) // JENKINS-12161, was previously 1000 but that made the system configuration page look weird public static final class DescriptorImpl extends BuildWrapperDescriptor { public DescriptorImpl() { super(MaskPasswordsBuildWrapper.class); } /** * @since 2.5 */ @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { try { getConfig().clear(); LOGGER.fine("Processing the maskedParamDefs and selectedMaskedParamDefs JSON objects"); JSONObject submittedForm = req.getSubmittedForm(); // parameter definitions to be automatically masked JSONArray paramDefinitions = submittedForm.getJSONArray("maskedParamDefs"); JSONArray selectedParamDefinitions = submittedForm.getJSONArray("selectedMaskedParamDefs"); for(int i = 0; i < selectedParamDefinitions.size(); i++) { if(selectedParamDefinitions.getBoolean(i)) { getConfig().addMaskedPasswordParameterDefinition(paramDefinitions.getString(i)); } } // global var/password pairs if(submittedForm.has("globalVarPasswordPairs")) { Object o = submittedForm.get("globalVarPasswordPairs"); if(o instanceof JSONArray) { JSONArray jsonArray = submittedForm.getJSONArray("globalVarPasswordPairs"); for(int i = 0; i < jsonArray.size(); i++) { getConfig().addGlobalVarPasswordPair(new VarPasswordPair( jsonArray.getJSONObject(i).getString("var"), Secret.fromString(jsonArray.getJSONObject(i).getString("password")))); } } else if(o instanceof JSONObject) { JSONObject jsonObject = submittedForm.getJSONObject("globalVarPasswordPairs"); getConfig().addGlobalVarPasswordPair(new VarPasswordPair( jsonObject.getString("var"), Secret.fromString(jsonObject.getString("password")))); } } // global regexes if(submittedForm.has("globalVarMaskRegexes")) { Object o = submittedForm.get("globalVarMaskRegexes"); if(o instanceof JSONArray) { JSONArray jsonArray = submittedForm.getJSONArray("globalVarMaskRegexes"); for(int i = 0; i < jsonArray.size(); i++) { getConfig().addGlobalVarMaskRegex(new VarMaskRegex( jsonArray.getJSONObject(i).getString("regex"))); } } else if(o instanceof JSONObject) { JSONObject jsonObject = submittedForm.getJSONObject("globalVarMaskRegexes"); getConfig().addGlobalVarMaskRegex(new VarMaskRegex( jsonObject.getString("regex"))); } } // global enable if(submittedForm.has("globalVarMaskEnabledGlobally")) { boolean b = submittedForm.getBoolean("globalVarMaskEnabledGlobally"); if(b) { getConfig().setGlobalVarEnabledGlobally(true); } } MaskPasswordsConfig.save(getConfig()); return true; } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failed to save Mask Passwords plugin configuration", e); return false; } } public List<VarPasswordPair> getGlobalVarPasswordPairs() { return getConfig().getGlobalVarPasswordPairs(); } public List<VarMaskRegex> getGlobalVarMaskRegexes() { return getConfig().getGlobalVarMaskRegexes(); } /** * @since 2.5 */ public MaskPasswordsConfig getConfig() { return MaskPasswordsConfig.getInstance(); } @Override public String getDisplayName() { return new Localizable(ResourceBundleHolder.get(MaskPasswordsBuildWrapper.class), "DisplayName").toString(); } @Override public boolean isApplicable(AbstractProject<?, ?> item) { return true; } } /** * We need this converter to handle marshalling/unmarshalling of the build * wrapper data: Relying on the default mechanism doesn't make it (because * {@link Secret} doesn't have the {@code DataBoundConstructor} annotation). */ public static final class ConverterImpl implements Converter { private final static String VAR_PASSWORD_PAIRS_NODE = "varPasswordPairs"; private final static String VAR_PASSWORD_PAIR_NODE = "varPasswordPair"; private final static String VAR_MASK_REGEXES_NODE = "varMaskRegexes"; private final static String VAR_MASK_REGEX_NODE = "varMaskRegex"; private final static String VAR_ATT = "var"; private final static String PASSWORD_ATT = "password"; private final static String REGEX_ATT = "regex"; public boolean canConvert(Class clazz) { return clazz.equals(MaskPasswordsBuildWrapper.class); } public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext mc) { MaskPasswordsBuildWrapper maskPasswordsBuildWrapper = (MaskPasswordsBuildWrapper) o; // varPasswordPairs if(maskPasswordsBuildWrapper.getVarPasswordPairs() != null) { writer.startNode(VAR_PASSWORD_PAIRS_NODE); for(VarPasswordPair varPasswordPair: maskPasswordsBuildWrapper.getVarPasswordPairs()) { // blank passwords are skipped if(varPasswordPair.getPlainTextPassword() == null) { continue; } writer.startNode(VAR_PASSWORD_PAIR_NODE); writer.addAttribute(VAR_ATT, varPasswordPair.getVar()); writer.addAttribute(PASSWORD_ATT, varPasswordPair.getPassword().getEncryptedValue()); writer.endNode(); } writer.endNode(); } // varMaskRegexes if(maskPasswordsBuildWrapper.getVarMaskRegexes() != null) { writer.startNode(VAR_MASK_REGEXES_NODE); for(VarMaskRegex varMaskRegex: maskPasswordsBuildWrapper.getVarMaskRegexes()) { // blank passwords are skipped if(StringUtils.isBlank(varMaskRegex.getRegex())) { continue; } writer.startNode(VAR_MASK_REGEX_NODE); writer.addAttribute(REGEX_ATT, varMaskRegex.getRegex()); writer.endNode(); } writer.endNode(); } } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) { List<VarPasswordPair> varPasswordPairs = new ArrayList<VarPasswordPair>(); List<VarMaskRegex> varMaskRegexes = new ArrayList<VarMaskRegex>(); while(reader.hasMoreChildren()) { reader.moveDown(); if(reader.getNodeName().equals(VAR_PASSWORD_PAIRS_NODE)) { while(reader.hasMoreChildren()) { reader.moveDown(); if(reader.getNodeName().equals(VAR_PASSWORD_PAIR_NODE)) { varPasswordPairs.add(new VarPasswordPair( reader.getAttribute(VAR_ATT), Secret.fromString(reader.getAttribute(PASSWORD_ATT)))); } else { LOGGER.log(Level.WARNING, "Encountered incorrect node name: Expected \"" + VAR_PASSWORD_PAIR_NODE + "\", got \"{0}\"", reader.getNodeName()); } reader.moveUp(); } reader.moveUp(); } else if(reader.getNodeName().equals(VAR_MASK_REGEXES_NODE)) { while(reader.hasMoreChildren()) { reader.moveDown(); if(reader.getNodeName().equals(VAR_MASK_REGEX_NODE)) { varMaskRegexes.add(new VarMaskRegex( reader.getAttribute(REGEX_ATT))); } else { LOGGER.log(Level.WARNING, "Encountered incorrect node name: Expected \"" + VAR_MASK_REGEX_NODE + "\", got \"{0}\"", reader.getNodeName()); } reader.moveUp(); } reader.moveUp(); } else { LOGGER.log(Level.WARNING, "Encountered incorrect node name: \"{0}\"", reader.getNodeName()); } } return new MaskPasswordsBuildWrapper(varPasswordPairs, varMaskRegexes); } } private static final Logger LOGGER = Logger.getLogger(MaskPasswordsBuildWrapper.class.getName()); }
package org.xbill.DNS; import java.io.*; import java.util.*; /** * A DNS Zone. This encapsulates all data related to a Zone, and provides * convienient lookup methods. * * @author Brian Wellington */ public class Zone extends NameSet { class AXFREnumeration implements Enumeration { private Enumeration znames; private Name currentName; private Object [] current; int count; boolean sentFirstSOA, sentNS, sentOrigin, sentLastSOA; AXFREnumeration() { znames = names(); } public boolean hasMoreElements() { return (!sentLastSOA); } public Object nextElement() { if (sentLastSOA) return null; if (!sentFirstSOA) { sentFirstSOA = true; RRset rrset = new RRset(); rrset.addRR(getSOA()); return rrset; } if (!sentNS) { sentNS = true; return getNS(); } if (!sentOrigin) { if (currentName == null) { currentName = getOrigin(); TypeClassMap tcm = findName(currentName); current = (Object []) tcm.getMultiple(Type.ANY, dclass); count = 0; } while (count < current.length) { RRset rrset = (RRset) current[count]; if (rrset.getType() != Type.SOA && rrset.getType() != Type.NS) return current[count++]; count++; } current = null; sentOrigin = true; } if (current != null && count < current.length) return current[count++]; while (znames.hasMoreElements()) { Name currentName = (Name) znames.nextElement(); if (currentName.equals(getOrigin())) continue; TypeClassMap tcm = findName(currentName); current = (Object []) tcm.getMultiple(Type.ANY, dclass); count = 0; if (count < current.length) return current[count++]; } sentLastSOA = true; RRset rrset = new RRset(); rrset.addRR(getSOA()); return rrset; } } /** A primary zone */ public static final int PRIMARY = 1; /** A secondary zone (unimplemented) */ public static final int SECONDARY = 2; private int type; private Name origin; private short dclass = DClass.IN; /** * Creates a Zone from the records in the specified master file. All * records that do not belong in the Zone are added to the specified Cache. * @see Cache * @see Master */ public Zone(String file, Cache cache) throws IOException { super(); type = PRIMARY; Master m = new Master(file); Record record; while ((record = m.nextRecord()) != null) { if (origin == null || record.getName().subdomain(origin)) { addRecord(record); if (origin == null && record.getType() == Type.SOA) origin = record.getName(); } else cache.addRecord(record, Credibility.ZONE_GLUE, m); } } /** Returns the Zone's origin */ public Name getOrigin() { return origin; } /** Returns the Zone origin's NS records */ public RRset getNS() { return (RRset) findExactSet(origin, Type.NS, dclass); } /** Returns the Zone's SOA record */ public SOARecord getSOA() { RRset rrset = (RRset) findExactSet(origin, Type.SOA, dclass); if (rrset == null) return null; Enumeration e = rrset.rrs(); return (SOARecord) e.nextElement(); } /** Returns the Zone's class */ public short getDClass() { return dclass; } /** * Looks up Records in the Zone. This follows CNAMEs and wildcards. * @param name The name to look up * @param type The type to look up * @return A SetResponse object * @see SetResponse */ public SetResponse findRecords(Name name, short type) { SetResponse zr = null; if (findName(name) == null) { if (name.isWild()) return new SetResponse(SetResponse.NXDOMAIN); else return findRecords(name.wild(1), type); } Object [] objects = findSets(name, type, dclass); if (objects == null) return new SetResponse(SetResponse.NODATA); RRset [] rrsets = new RRset[objects.length]; System.arraycopy(objects, 0, rrsets, 0, objects.length); for (int i = 0; i < rrsets.length; i++) { RRset rrset = rrsets[i]; if (type != Type.CNAME && type != Type.ANY && rrset.getType() == Type.CNAME) { CNAMERecord cname = (CNAMERecord) rrset.first(); zr = findRecords(cname.getTarget(), type); if (zr.isNODATA()) zr.set(SetResponse.PARTIAL, cname); else if (zr.isNXDOMAIN() && !cname.getTarget().subdomain(origin)) zr.set(SetResponse.PARTIAL, cname); zr.addCNAME(cname); return zr; } if (zr == null) zr = new SetResponse(SetResponse.SUCCESSFUL); zr.addRRset(rrset); } return zr; } /** * Looks up Records in the zone, finding exact matches only. * @param name The name to look up * @param type The type to look up * @return The matching RRset * @see RRset */ public RRset findExactMatch(Name name, short type) { return (RRset) findExactSet(name, type, dclass); } /** * Adds a record to the Zone * @param r The record to be added * @see Record */ public void addRecord(Record r) { Name name = r.getName(); short type = r.getType(); RRset rrset = (RRset) findExactSet (name, type, dclass); if (rrset == null) addSet(name, type, dclass, rrset = new RRset()); rrset.addRR(r); } public Enumeration AXFR() { return new AXFREnumeration(); } }
package net.finmath.montecarlo.assetderivativevaluation.products; import net.finmath.exception.CalculationException; import net.finmath.montecarlo.RandomVariable; import net.finmath.montecarlo.assetderivativevaluation.AssetModelMonteCarloSimulationInterface; import net.finmath.montecarlo.conditionalexpectation.MonteCarloConditionalExpectation; import net.finmath.montecarlo.conditionalexpectation.MonteCarloConditionalExpectationRegression; import net.finmath.optimizer.GoldenSectionSearch; import net.finmath.stochastic.RandomVariableInterface; /** * This class implements the valuation of a Bermudan option paying * <br> * <i> N(i) * (S(T(i)) - K(i)) </i> at <i>T(i)</i>, * <br> * when exercised in T(i), where N(i) is the notional, S is the underlying, K(i) is the strike * and T(i) the exercise date. * * The code "demos" the two prominent methods for the valuation of Bermudan (American) products: * <ul> * <li> * The valuation may be performed using an estimation of the conditional expectation to determine the * exercise criteria. Apart from a possible foresight bias induced by the Monte-Carlo errors, this give a lower bound * for the Bermudan value. * <li> * The valuation may be performed using the dual method based on a minimization problem, which gives an upper bound. * </ul> * * * @author Christian Fries * @version 1.4 */ public class BermudanOption extends AbstractAssetMonteCarloProduct { public enum ExerciseMethod { ESTIMATE_COND_EXPECTATION, UPPER_BOUND_METHOD } private final double[] exerciseDates; private final double[] notionals; private final double[] strikes; private final int orderOfRegressionPolynomial = 4; private final boolean intrinsicValueAsBasisFunction = true; private ExerciseMethod exerciseMethod = ExerciseMethod.UPPER_BOUND_METHOD; /** * Create a Bermudan option paying * N(i) * (S(T(i)) - K(i)) at T(i), * when exercised in T(i), where N(i) is the notional, S is the underlying, K(i) is the strike * and T(i) the exercise date. * * @param exerciseDates The exercise dates (T(i)), given as doubles. * @param notionals The notionals (N(i)) for each exercise date. * @param strikes The strikes (K(i)) for each exercise date. */ public BermudanOption( double[] exerciseDates, double[] notionals, double[] strikes) { super(); this.exerciseDates = exerciseDates; this.notionals = notionals; this.strikes = strikes; } /** * Create a Bermudan option paying * N(i) * (S(T(i)) - K(i)) at T(i), * when exercised in T(i), where N(i) is the notional, S is the underlying, K(i) is the strike * and T(i) the exercise date. * * @param exerciseDates The exercise dates (T(i)), given as doubles. * @param notionals The notionals (N(i)) for each exercise date. * @param strikes The strikes (K(i)) for each exercise date. * @param exerciseMethod The exercise method to be used for the estimation of the exercise boundary. */ public BermudanOption( double[] exerciseDates, double[] notionals, double[] strikes, ExerciseMethod exerciseMethod) { super(); this.exerciseDates = exerciseDates; this.notionals = notionals; this.strikes = strikes; this.exerciseMethod = exerciseMethod; } /** * This method returns the value random variable of the product within the specified model, * evaluated at a given evalutationTime. * Cash-flows prior evaluationTime are not considered. * * @param evaluationTime The time on which this products value should be observed. * @param model The model used to price the product. * @return The random variable representing the value of the product discounted to evaluation time. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. * */ @Override public RandomVariableInterface getValue(double evaluationTime, AssetModelMonteCarloSimulationInterface model) throws CalculationException { if(this.exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) { // Find optimal lambda GoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0); while(!optimizer.isDone()) { double lambda = optimizer.getNextPoint(); double value = this.getValues(evaluationTime, model, lambda).getAverage(); optimizer.setValue(value); } return getValues(evaluationTime, model, optimizer.getBestPoint()); } else { return getValues(evaluationTime, model, 0.0); } } private RandomVariableInterface getValues(double evaluationTime, AssetModelMonteCarloSimulationInterface model, double lambda) throws CalculationException { /* * We are going backward in time (note that this bears the risk of an foresight bias). * We store the value of the option, if not exercised in a vector. Is is not allowed to used the specific entry in this vector * in the exercise decision (perfect foresight). Instead some exercise strategy / estimate has to be used. */ // Initialize our value random variable: the value of the option if we never exercise is zero RandomVariableInterface value = model.getRandomVariableForConstant(0.0); RandomVariableInterface exerciseTime = model.getRandomVariableForConstant(exerciseDates[exerciseDates.length-1]+1); for(int exerciseDateIndex=exerciseDates.length-1; exerciseDateIndex>=0; exerciseDateIndex { double exerciseDate = exerciseDates[exerciseDateIndex]; double notional = notionals[exerciseDateIndex]; double strike = strikes[exerciseDateIndex]; // Get some model values upon exercise date RandomVariableInterface underlyingAtExercise = model.getAssetValue(exerciseDate,0); RandomVariableInterface numeraireAtPayment = model.getNumeraire(exerciseDate); RandomVariableInterface monteCarloWeights = model.getMonteCarloWeights(exerciseDate); // Value received if exercised at current time RandomVariableInterface valueOfPaymentsIfExercised = underlyingAtExercise.sub(strike).mult(notional).div(numeraireAtPayment).mult(monteCarloWeights); // Create a conditional expectation estimator with some basis functions (predictor variables) for conditional expectation estimation. MonteCarloConditionalExpectation condExpEstimator; if(intrinsicValueAsBasisFunction) condExpEstimator = new MonteCarloConditionalExpectationRegression(getRegressionBasisFunctions(underlyingAtExercise.sub(strike).floor(0.0))); else condExpEstimator = new MonteCarloConditionalExpectationRegression(getRegressionBasisFunctions(underlyingAtExercise)); RandomVariableInterface underlying = null; RandomVariableInterface trigger = null; // Calculate the exercise criteria (exercise if the following trigger is negative) switch(exerciseMethod) { case ESTIMATE_COND_EXPECTATION: // Calculate conditional expectation on numeraire relative quantity. RandomVariableInterface valueIfNotExcercisedEstimated = condExpEstimator.getConditionalExpectation(value); underlying = valueOfPaymentsIfExercised; trigger = valueIfNotExcercisedEstimated.sub(underlying); break; case UPPER_BOUND_METHOD: RandomVariableInterface martingale = model.getAssetValue(exerciseDates[exerciseDateIndex], 0).div(model.getNumeraire(exerciseDates[exerciseDateIndex])); martingale = martingale.sub(martingale.getAverage()).mult(lambda); underlying = valueOfPaymentsIfExercised.sub(martingale); if(exerciseDateIndex==exerciseDates.length-1) value = value.sub(martingale); trigger = value.sub(underlying); break; } // If trigger is positive keep value, otherwise take underlying value = value.barrier(trigger, value, underlying); exerciseTime = exerciseTime.barrier(trigger, exerciseTime, exerciseDate); } // Uncomment the following if you like to check exercise probabilities /* double[] probabilities = exerciseTime.getHistogram(exerciseDates); for(int exerciseDateIndex=0; exerciseDateIndex<exerciseDates.length; exerciseDateIndex++) { double time = exerciseDates[exerciseDateIndex]; System.out.println(time + "\t" + probabilities[exerciseDateIndex]); } System.out.println("NEVER" + "\t" + probabilities[exerciseDates.length]); */ // Note that values is a relative price - no numeraire division is required RandomVariableInterface numeraireAtZero = model.getNumeraire(evaluationTime); RandomVariableInterface monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime); value = value.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero); return value; } private RandomVariableInterface[] getRegressionBasisFunctions(RandomVariableInterface underlying) { RandomVariableInterface[] basisFunctions; // Create basis functions - here: 1, S, S^2, S^3, S^4 basisFunctions = new RandomVariableInterface[orderOfRegressionPolynomial+1]; basisFunctions[0] = new RandomVariable(1.0); // Random variable = 1 basisFunctions[1] = underlying; // Random variable = S for(int powerOfRegressionMonomial=2; powerOfRegressionMonomial<=orderOfRegressionPolynomial; powerOfRegressionMonomial++) { basisFunctions[powerOfRegressionMonomial] = underlying.pow(powerOfRegressionMonomial); } return basisFunctions; } }
package wge3.entity.character; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.MathUtils; import static com.badlogic.gdx.math.MathUtils.PI; import static com.badlogic.gdx.math.MathUtils.PI2; import static com.badlogic.gdx.math.MathUtils.radiansToDegrees; import static com.badlogic.gdx.math.MathUtils.random; import com.badlogic.gdx.math.Rectangle; import static com.badlogic.gdx.utils.TimeUtils.millis; import static java.lang.Math.max; import java.util.LinkedList; import java.util.List; import static wge3.entity.ground.Direction.*; import wge3.entity.ground.OneWayTile; import wge3.entity.terrainelements.Item; import static wge3.game.PlayState.mStream; import wge3.interfaces.Drawable; import wge3.world.Area; import wge3.world.Tile; public abstract class Creature implements Drawable { protected Area area; protected float x; protected float y; protected Rectangle bounds; protected int team; // 0 = player team // 1 = monster team protected int size; protected int defaultSpeed; protected int currentSpeed; protected float direction; protected float turningSpeed; protected int sight; protected float FOV; protected String name; protected int maxHP; protected int HP; protected int HPRegenRate; /* per second */ protected long timeOfLastRegen; protected int strength; protected int defense; protected int unarmedAttackSize; /* radius */ protected boolean picksUpItems; protected boolean canSeeEverything; protected boolean walksThroughWalls; protected Inventory inventory; protected Item selectedItem; protected Texture texture; protected Sprite sprite; protected boolean goingForward; protected boolean goingBackward; protected boolean turningLeft; protected boolean turningRight; public Creature() { texture = new Texture(Gdx.files.internal("graphics/graphics.png")); size = Tile.size / 3; defaultSpeed = 100; currentSpeed = defaultSpeed; direction = random() * PI2; turningSpeed = 3.5f; sight = 12; FOV = PI; unarmedAttackSize = Tile.size/2; HPRegenRate = 1; timeOfLastRegen = millis(); canSeeEverything = false; walksThroughWalls = false; bounds = new Rectangle(); bounds.height = 0.75f*Tile.size; bounds.width = 0.75f*Tile.size; inventory = new Inventory(); inventory.setOwner(this); selectedItem = null; goingForward = false; goingBackward = false; turningLeft = false; turningRight = false; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public void setPosition(int x, int y) { this.x = x; this.y = y; } public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public int getDefaultSpeed() { return defaultSpeed; } public void setDefaultSpeed(int defaultSpeed) { this.defaultSpeed = defaultSpeed; } public float getDirection() { return direction; } public float getTurningSpeed() { return turningSpeed; } public void setTurningSpeed(float turningSpeed) { this.turningSpeed = turningSpeed; } public int getMaxHP() { return maxHP; } public void setMaxHP(int newMaxHP) { this.maxHP = newMaxHP; } public int getHP() { return HP; } public void setHP(int newHP) { this.HP = newHP; } public int getSize() { return size; } public int getCurrentSpeed() { return currentSpeed; } public Inventory getInventory() { return inventory; } @Override public void draw(Batch batch) { sprite.draw(batch); } public void turnLeft(float delta) { direction += turningSpeed * delta; if (direction >= PI2) direction -= PI2; updateSpriteRotation(); } public void turnRight(float delta) { direction -= turningSpeed * delta; if (direction < 0) direction += PI2; updateSpriteRotation(); } public void move(float dx, float dy) { // Apply movement modifiers: float movementModifier = area.getTileAt(getX(), getY()).getMovementModifier(); dx *= movementModifier; dy *= movementModifier; // Calculate actual movement: float destX = getX() + dx; float destY = getY() + dy; if (canMoveTo(destX, destY)) { setX(destX); setY(destY); updateSpritePosition(); } else if (canMoveTo(getX(), destY)) { setY(destY); updateSpritePosition(); } else if (canMoveTo(destX, getY())) { setX(destX); updateSpritePosition(); } // Should be optimized to pick up items only when current tile != previous tile. if (picksUpItems()) pickUpItems(); } public void pickUpItems() { Tile currentTile = getTile(); if (currentTile.hasItem()) { inventory.addItem((Item) currentTile.getObject()); currentTile.removeObject(); } } public boolean canMoveTo(float x, float y) { if (!area.hasLocation(x, y)) { return false; } if (this.walksThroughWalls()) { return true; } if (area.getTileAt(x, y).isOneWay()) { OneWayTile oneWayTile = (OneWayTile) area.getTileAt(x, y).getGround(); if (oneWayTile.getDirection() == LEFT && x - getX() > 0) { return false; } if (oneWayTile.getDirection() == RIGHT && x - getX() < 0) { return false; } if (oneWayTile.getDirection() == UP && y - getY() < 0) { return false; } if (oneWayTile.getDirection() == DOWN && y - getY() > 0) { return false; } } return (area.getTileAt(x, y).isPassable()); } public void useItem() { if (selectedItem == null) attackUnarmed(); else selectedItem.use(this); } public void changeItem() { setSelectedItem(inventory.getNextItem()); } public void setSelectedItem(Item selectedItem) { this.selectedItem = selectedItem; } public Item getSelectedItem() { return selectedItem; } public int getSight() { return sight; } public float getFOV() { return FOV; } public boolean canSeeEverything() { return canSeeEverything; } public void toggleCanSeeEverything() { canSeeEverything = canSeeEverything == false; } public boolean walksThroughWalls() { return walksThroughWalls; } public void toggleWalksThroughWalls() { walksThroughWalls = walksThroughWalls == false; if (walksThroughWalls()) mStream.addMessage("Ghost Mode On"); else mStream.addMessage("Ghost Mode Off"); } private boolean isInCenterOfATile() { float x = (getX() % Tile.size) / Tile.size; float y = (getY() % Tile.size) / Tile.size; return (x >= 0.25f && x <= 0.75f) && (y >= 0.25f && y <= 0.75f); } public void dealDamage(int amount) { HP -= max(amount - defense, 1); } public boolean isDead() { return HP <= 0; } public void regenerateHP(long currentTime) { if (currentTime - timeOfLastRegen > 1000) { if (HP < maxHP) { HP += HPRegenRate; if (HP > maxHP) HP = maxHP; } timeOfLastRegen = currentTime; } } public void updateSpritePosition() { sprite.setPosition(getX() - Tile.size/2, getY() - Tile.size/2); } public void updateSpriteRotation() { sprite.setRotation(direction * radiansToDegrees); } public void attackUnarmed() { float destX = getX() + MathUtils.cos(direction) * Tile.size; float destY = getY() + MathUtils.sin(direction) * Tile.size; Circle dest = new Circle(destX, destY, getUnarmedAttackSize()); for (Creature creature : area.getCreatures()) { if (dest.contains(creature.getX(), creature.getY())) { creature.dealDamage(this.strength); } } } public boolean isPlayer() { return this.getClass() == Player.class; } public void doMovement(float delta) { if (goingForward) { goingForward = false; float dx = MathUtils.cos(direction) * currentSpeed * delta; float dy = MathUtils.sin(direction) * currentSpeed * delta; move(dx, dy); } else if (goingBackward) { goingBackward = false; float dx = -(MathUtils.cos(direction) * currentSpeed/1.5f * delta); float dy = -(MathUtils.sin(direction) * currentSpeed/1.5f * delta); move(dx, dy); } if (turningLeft) { turningLeft = false; turnLeft(delta); } else if (turningRight) { turningRight = false; turnRight(delta); } } public void goForward() { goingForward = true; } public void goBackward() { goingBackward = true; } public void turnLeft() { turningLeft = true; } public void turnRight() { turningRight = true; } public boolean canBeSeenBy(Creature creature) { return area.getTileAt(getX(), getY()).canBeSeenBy(creature); } public void setLighting(Color color) { sprite.setColor(color); } public Tile getTile() { return area.getTileAt(getX(), getY()); } public int getTeam() { return team; } public List<Tile> getPossibleMovementDestinations() { List<Tile> tiles = new LinkedList<Tile>(); for (Tile tile : area.getTiles()) { if (tile.canBeSeenBy(this) && tile.isAnOKMoveDestinationFor(this)) tiles.add(tile); } return tiles; } public Tile getNewMovementDestination() { // Returns a random tile from all the tiles that are // ok move destinations and can be seen by creature. List<Tile> tiles = getPossibleMovementDestinations(); return tiles.get(random(tiles.size() - 1)); } public String getName() { return name; } public int getUnarmedAttackSize() { return unarmedAttackSize; } public boolean isEnemyOf(Creature other) { return this.getTeam() != other.getTeam(); } public boolean picksUpItems() { return picksUpItems; } public List<Creature> getEnemiesWithinFOV() { List<Creature> enemiesWithinFOV = new LinkedList<Creature>(); for (Creature creature : getArea().getCreatures()) { if (creature.isEnemyOf(this) && creature.canBeSeenBy(this)) { enemiesWithinFOV.add(creature); } } return enemiesWithinFOV; } }
package com.gpgex; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.app.Activity; import org.haxe.extension.Extension; import org.haxe.lime.HaxeObject; import android.os.AsyncTask; import java.io.IOException; import java.io.FileOutputStream; import java.io.File; import java.security.MessageDigest; import com.google.android.gms.games.Games; import com.google.android.gms.games.Players; import com.google.android.gms.games.Player; import com.google.android.gms.games.PlayerBuffer; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.images.ImageManager; import com.google.android.gms.games.leaderboard.Leaderboards; import com.google.android.gms.games.leaderboard.LeaderboardVariant; import com.google.android.gms.games.leaderboard.LeaderboardScore; import com.google.android.gms.games.GamesStatusCodes; import com.google.android.gms.games.achievement.Achievements; import com.google.android.gms.games.achievement.Achievement; import com.google.android.gms.games.snapshot.Snapshot; import com.google.android.gms.games.snapshot.Snapshots; import com.google.android.gms.games.snapshot.SnapshotMetadataChange; import com.google.android.gms.games.snapshot.SnapshotMetadataChange.Builder; public class GooglePlayGames extends Extension implements GameHelper.GameHelperListener { private static GooglePlayGames instance=null; private static GameHelper mHelper=null; public static final String TAG = "EXTENSION-GOOGLEPLAYGAMES"; private static boolean userRequiresLogin=false; private static SecureHaxeObject callbackObject = null; private static boolean enableCloudStorage=false; public static void init(boolean cloudStorage, HaxeObject callbackObj){ if(callbackObj!=null) GooglePlayGames.callbackObject = new SecureHaxeObject(callbackObj, mainActivity, TAG); if(mHelper!=null){ if(mHelper.isConnecting() || mHelper.isSignedIn()) return; mHelper=null; } enableCloudStorage=cloudStorage; final int maxAutoSignInAttempts = userRequiresLogin?1:0; userRequiresLogin=false; mainActivity.runOnUiThread(new Runnable() { public void run() { try{ mHelper = new GameHelper(mainActivity, GameHelper.CLIENT_GAMES | (enableCloudStorage?GameHelper.CLIENT_CLOUD_STORAGE:0)); mHelper.enableDebugLog(true); mHelper.setup(GooglePlayGames.getInstance()); mHelper.setMaxAutoSignInAttempts(maxAutoSignInAttempts); mHelper.onStart(mainActivity); Log.i(TAG, "PlayGames: INIT COMPLETE"); }catch(Exception e) { Log.i(TAG, "PlayGames: INIT Exception"); Log.i(TAG, e.toString()); } } }); } public static void login(){ Log.i(TAG, "PlayGames: Forcing Login"); userRequiresLogin=true; mHelper=null; init(enableCloudStorage,null); } public static boolean setScore(String id, int high_score, int low_score){ try { long score = (((long)high_score << 32) | ((long)low_score & 0xFFFFFFFF)); Games.Leaderboards.submitScore(mHelper.mGoogleApiClient, id, score); } catch (Exception e) { Log.i(TAG, "PlayGames: setScore Exception"); Log.i(TAG, e.toString()); return false; } Log.i(TAG, "PlayGames: setScore complete"); return true; } public static boolean displayScoreboard(String id){ try { mainActivity.startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mHelper.mGoogleApiClient, id), 0); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: displayScoreboard Exception"); Log.i(TAG, e.toString()); login(); return false; } return true; } public static boolean displayAllScoreboards(){ try { mainActivity.startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mHelper.mGoogleApiClient), 0); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: displayAllScoreboards Exception"); Log.i(TAG, e.toString()); login(); return false; } return true; } public static GooglePlayGames getInstance(){ if(instance==null) instance=new GooglePlayGames(); return instance; } @Override public void onSignInFailed() { callbackObject.call1("loginResultCallback",-1); Log.i(TAG, "PlayGames: onSignInFailed"); } @Override public void onSignInSucceeded() { callbackObject.call1("loginResultCallback",1); Log.i(TAG, "PlayGames: onSignInSucceeded"); } @Override public void onSignInStart() { callbackObject.call1("loginResultCallback",0); Log.i(TAG, "PlayGames: onSignInStart"); } public static boolean unlock(String id){ try{ Games.Achievements.unlock(mHelper.mGoogleApiClient, id); }catch (Exception e) { Log.i(TAG, "PlayGames: unlock Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean reveal(String id){ try{ Games.Achievements.reveal(mHelper.mGoogleApiClient, id); }catch (Exception e) { Log.i(TAG, "PlayGames: reveal Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean increment(String id, int step){ try{ Games.Achievements.increment(mHelper.mGoogleApiClient, id, step); }catch (Exception e) { Log.i(TAG, "PlayGames: increment Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean setSteps(String id, int steps){ try{ Games.Achievements.setSteps(mHelper.mGoogleApiClient, id, steps); }catch (Exception e) { Log.i(TAG, "PlayGames: setSteps Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean displayAchievements(){ try{ mainActivity.startActivityForResult(Games.Achievements.getAchievementsIntent(mHelper.mGoogleApiClient), 0); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: displayAchievements Exception"); Log.i(TAG, e.toString()); login(); return false; } return true; } public static String getPlayerId() { try { Log.i(TAG, "PlayGames: getPlayerId BEGIN"); return Games.Players.getCurrentPlayerId(mHelper.mGoogleApiClient); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: getPlayerId Exception"); Log.i(TAG, e.toString()); } return null; } public static String getPlayerDisplayName() { try { Log.i(TAG, "PlayGames: getPlayerDisplayName BEGIN"); Player p = Games.Players.getCurrentPlayer(mHelper.mGoogleApiClient); return p.getDisplayName(); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: getPlayerDisplayName Exception"); Log.i(TAG, e.toString()); } return null; } public static void getPlayerImage(final String playerID) { mainActivity.runOnUiThread(new Runnable() { public void run() { try{ Log.i(TAG, "PlayGames: getPlayerImage BEGIN "); if(playerID==null || playerID=="null" || playerID.isEmpty()){ Player p = Games.Players.getCurrentPlayer(mHelper.mGoogleApiClient); final String url = p.getIconImageUri().toString(); loadImage(getPlayerId(), p.getIconImageUri(), url); } else { Games.Players.loadPlayer(mHelper.mGoogleApiClient, playerID).setResultCallback(new ResultCallback<Players.LoadPlayersResult>() { @Override public void onResult(Players.LoadPlayersResult loadPlayersResult) { Log.i(TAG, "PlayGames: getPlayerImage load players on result "); if(loadPlayersResult.getStatus().getStatusCode() == GamesStatusCodes.STATUS_OK){ PlayerBuffer buffer = loadPlayersResult.getPlayers(); if(buffer.getCount()>0){ Player p = buffer.get(0); if(p.getIconImageUri()!=null){ final String url = p.getIconImageUri().toString(); loadImage(playerID, p.getIconImageUri(), url); } } buffer.release(); } } }); } }catch(Exception e) { Log.i(TAG, "PlayGames: getPlayerImage Exception"); Log.i(TAG, e.toString()); } } }); } private static void loadImage(final String playerID, Uri uri, final String url){ ImageManager im = ImageManager.create(mHelper.mAppContext); im.loadImage(new ImageManager.OnImageLoadedListener() { @Override public void onImageLoaded(Uri uri, Drawable drawable, boolean isRequestedDrawable) { Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); try { String cache = Extension.mainContext.getCacheDir().getAbsolutePath(); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = md.digest(url.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } String md5 = sb.toString(); String path = cache+"/cache/"+md5+".png"; File file = new File(path); file.getParentFile().mkdirs(); // Will create parent directories if not exists file.createNewFile(); FileOutputStream fos = new FileOutputStream(file,false); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); Log.i(TAG, "PlayGames: "+playerID+"'s saved in "+path); callbackObject.call2("onGetPlayerImage", playerID, path); } catch (Exception e) { Log.i(TAG, "PlayGames: getPlayerImage exception trying to save: "); Log.i(TAG, e.toString()); //TODO: Handle exception } } }, uri); } public static boolean getPlayerScore(final String idScoreboard) { try { Games.Leaderboards.loadCurrentPlayerLeaderboardScore(mHelper.mGoogleApiClient, idScoreboard, LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(new ResultCallback<Leaderboards.LoadPlayerScoreResult>() { @Override public void onResult(final Leaderboards.LoadPlayerScoreResult playerScore) { if ((playerScore != null) && (playerScore.getStatus().getStatusCode() == GamesStatusCodes.STATUS_OK) && (playerScore.getScore() != null)) { long score = playerScore.getScore().getRawScore(); int high_score = (int) (score >>> 32); int low_score = (int) (score & 0xFFFFFFFF); callbackObject.call3("onGetScoreboard", idScoreboard, high_score, low_score); } } }); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: getPlayerScore Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean loadInvitablePlayers(boolean clearCache) { return loadAllPlayers(false, clearCache, 0); } public static boolean loadConnectedPlayers(boolean clearCache) { return loadAllPlayers(true, clearCache, 0); } private static boolean loadAllPlayers(final boolean getConnectedPlayers, boolean clearCache, final int resultsCount) { try{ final int FRIENDS_PER_PAGE = 25; final ResultCallback<Players.LoadPlayersResult> resultCallback = new ResultCallback<Players.LoadPlayersResult>(){ @Override public void onResult(Players.LoadPlayersResult result) { PlayerBuffer playerBuffer = result.getPlayers(); Log.w(TAG, "loadAllFriends: onResult... got " + playerBuffer.getCount()); if (!getConnectedPlayers && playerBuffer.getCount() >= resultsCount+FRIENDS_PER_PAGE) { Log.w(TAG, "loadAllFriends: Maybe there're more players... calling loadMoreInvitablePlayers."); loadAllPlayers(false, false, playerBuffer.getCount()); return; } String friends = ""; for (Player player : playerBuffer) { friends+=player.getPlayerId()+"\1"+player.getDisplayName()+"\2"; //Log.i(TAG, String.format("Found player with id [%s] and display name [%s]", player.getPlayerId(), player.getDisplayName())); } Log.w(TAG, "loadAllFriends: Done! Now sending serialized friends to HAXE"); callbackObject.call2("onLoadPlayers",friends,getConnectedPlayers); } }; if(getConnectedPlayers) { Games.Players.loadConnectedPlayers(mHelper.mGoogleApiClient, clearCache).setResultCallback(resultCallback); }else{ if (resultsCount == 0){ Games.Players.loadInvitablePlayers(mHelper.mGoogleApiClient, FRIENDS_PER_PAGE, clearCache).setResultCallback(resultCallback); }else{ Games.Players.loadMoreInvitablePlayers(mHelper.mGoogleApiClient, FRIENDS_PER_PAGE).setResultCallback(resultCallback); } } } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: loadAllFriends Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean getAchievementStatus(final String idAchievement) { try { Games.Achievements.load(mHelper.mGoogleApiClient, false).setResultCallback(new ResultCallback<Achievements.LoadAchievementsResult>() { @Override public void onResult(Achievements.LoadAchievementsResult loadAchievementsResult) { for (Achievement ach: loadAchievementsResult.getAchievements()) { if (ach.getAchievementId().equals(idAchievement)) { if (ach.getState() == Achievement.STATE_UNLOCKED) callbackObject.call2("onGetAchievementStatus", idAchievement, 1); else callbackObject.call2("onGetAchievementStatus", idAchievement, 0); } } } }); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: getAchievementStatus Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean getCurrentAchievementSteps(final String idAchievement) { try { Games.Achievements.load(mHelper.mGoogleApiClient, false).setResultCallback(new ResultCallback<Achievements.LoadAchievementsResult>() { @Override public void onResult(Achievements.LoadAchievementsResult loadAchievementsResult) { for (Achievement ach: loadAchievementsResult.getAchievements()) { if (ach.getAchievementId().equals(idAchievement)) { if (ach.getType() == Achievement.TYPE_INCREMENTAL) callbackObject.call2("onGetAchievementSteps", idAchievement, ach.getCurrentSteps()); } } } }); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: getCurrentAchievementSteps Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static void openGame(String name){ } private static final int RC_SAVED_GAMES = 9009; public static void displaySavedGames(String title, boolean allowAddButton, boolean allowDelete, int maxNumberOfSavedGamesToShow ) { try { if(title == null || title.compareTo("")==0) title = " "; mainActivity.startActivityForResult(Games.Snapshots.getSelectSnapshotIntent(mHelper.mGoogleApiClient, title, allowAddButton, allowDelete, maxNumberOfSavedGamesToShow), RC_SAVED_GAMES); } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: displaySavedGames Exception"); Log.i(TAG, e.toString()); login(); } } private static Snapshot snapshot = null; private static boolean savedGamesWorking = false; public static void loadSavedGame(final String savedName) { if(savedGamesWorking) { Log.i(TAG, "PlayGames: loadSavedGame (still opening game... won't do anything)."); return; } if ( snapshot != null ) discardAndCloseGame(); AsyncTask<Void, Void, Integer> task = new AsyncTask<Void, Void, Integer>() { @Override protected Integer doInBackground(Void... params) { int statusCode = 0; try{ String name = new String(savedName); byte[] mSaveGameData = null; byte[] mConfictSaveGameData = null; Snapshot conflictSnapshot = null; // Open the saved game using its name. Snapshots.OpenSnapshotResult result = Games.Snapshots.open(mHelper.mGoogleApiClient, name, true).await(); statusCode = result.getStatus().getStatusCode(); boolean hadConflict = false; if(statusCode == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT){ hadConflict = true; while(statusCode == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT){ conflictSnapshot = result.getConflictingSnapshot(); Games.Snapshots.resolveConflict(mHelper.mGoogleApiClient, result.getConflictId(), result.getSnapshot()).await(); result = Games.Snapshots.open(mHelper.mGoogleApiClient, name, true).await(); statusCode = result.getStatus().getStatusCode(); } } // Check the result of the open operation if (result.getStatus().isSuccess()) { snapshot = result.getSnapshot(); // Read the byte content of the saved game. try { mSaveGameData = snapshot.getSnapshotContents().readFully(); } catch (IOException e) { Log.e(TAG, "Error while reading Snapshot.", e); } } else { Log.e(TAG, "Error while loading: " + result.getStatus().getStatusCode()); } savedGamesWorking=false; if(hadConflict){ try { mConfictSaveGameData = conflictSnapshot.getSnapshotContents().readFully(); } catch (IOException e) { Log.e(TAG, "Error while reading Snapshot.", e); } callbackObject.call3("onLoadSavedGameConflict", name, mSaveGameData==null?null:new String(mSaveGameData), mConfictSaveGameData==null?null:new String(mConfictSaveGameData)); } else { callbackObject.call3("onLoadSavedGameComplete", name, result.getStatus().getStatusCode(), mSaveGameData==null?null:new String(mSaveGameData)); } } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: loadSavedGame / doInBackground Exception"); Log.i(TAG, e.toString()); savedGamesWorking=false; } return statusCode; } }; savedGamesWorking = true; task.execute(); } public static boolean discardAndCloseGame(){ if(savedGamesWorking) { Log.i(TAG, "PlayGames: discardAndCloseGame (still opening game... won't do anything)."); return false; } try { if(snapshot == null) return true; Games.Snapshots.discardAndClose(mHelper.mGoogleApiClient, snapshot); snapshot = null; } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: discardAndCloseGame Exception"); Log.i(TAG, e.toString()); return false; } return true; } public static boolean commitAndCloseGame(String data, String description) { if(savedGamesWorking) { Log.i(TAG, "PlayGames: commitAndCloseGame (still opening game... won't do anything)."); return false; } try{ if(snapshot == null) { Log.i(TAG, "PlayGames: commitAndCloseGame (trying to save unopened game!)"); return true; } snapshot.getSnapshotContents().writeBytes(data.getBytes()); // Create the change operation SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder() //.setCoverImage(coverImage) .setDescription(description) .build(); Games.Snapshots.commitAndClose(mHelper.mGoogleApiClient, snapshot, metadataChange); snapshot = null; } catch (Exception e) { // Try connecting again Log.i(TAG, "PlayGames: commitAndCloseGame Exception"); Log.i(TAG, e.toString()); return false; } return true; } }
package org.spongepowered.common.mixin.core.item.inventory; import net.minecraft.inventory.ContainerPlayer; import org.spongepowered.api.item.inventory.equipment.EquipmentTypes; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.interfaces.inventory.IMixinContainerPlayer; import org.spongepowered.common.item.inventory.adapter.InventoryAdapter; import org.spongepowered.common.item.inventory.adapter.impl.slots.CraftingOutputAdapter; import org.spongepowered.common.item.inventory.adapter.impl.slots.EquipmentSlotAdapter; import org.spongepowered.common.item.inventory.lens.Fabric; import org.spongepowered.common.item.inventory.lens.Lens; import org.spongepowered.common.item.inventory.lens.LensProvider; import org.spongepowered.common.item.inventory.lens.SlotProvider; import org.spongepowered.common.item.inventory.lens.impl.collections.SlotCollection; import org.spongepowered.common.item.inventory.lens.impl.minecraft.container.ContainerPlayerInventoryLens; import org.spongepowered.common.item.inventory.lens.impl.slots.CraftingOutputSlotLensImpl; import org.spongepowered.common.item.inventory.lens.impl.slots.EquipmentSlotLensImpl; @Mixin(ContainerPlayer.class) public abstract class MixinContainerPlayer extends MixinContainer implements IMixinContainerPlayer, LensProvider { @Override public Lens rootLens(Fabric fabric, InventoryAdapter adapter) { return new ContainerPlayerInventoryLens(adapter, inventory$getSlotProvider()); } private int offHandSlot = -1; @Override public int getOffHandSlot() { return this.offHandSlot; } @SuppressWarnings("unchecked") @Override public SlotProvider slotProvider(Fabric fabric, InventoryAdapter adapter) { SlotCollection.Builder builder = new SlotCollection.Builder() .add(1, CraftingOutputAdapter.class, (i) -> new CraftingOutputSlotLensImpl(i, (t) -> false, (t) -> false)) .add(4) // TODO predicates for ItemStack/ItemType? // order for equipment is reversed in containers .add(EquipmentSlotAdapter.class, index -> new EquipmentSlotLensImpl(index, i -> true, t -> true, e -> e == EquipmentTypes.HEADWEAR)) .add(EquipmentSlotAdapter.class, index -> new EquipmentSlotLensImpl(index, i -> true, t -> true, e -> e == EquipmentTypes.CHESTPLATE)) .add(EquipmentSlotAdapter.class, index -> new EquipmentSlotLensImpl(index, i -> true, t -> true, e -> e == EquipmentTypes.LEGGINGS)) .add(EquipmentSlotAdapter.class, index -> new EquipmentSlotLensImpl(index, i -> true, t -> true, e -> e == EquipmentTypes.BOOTS)) .add(36) .add(EquipmentSlotAdapter.class, index -> new EquipmentSlotLensImpl(index, i -> true, t -> true, e -> e == EquipmentTypes.OFF_HAND)); if (this.offHandSlot == -1) { this.offHandSlot = builder.size() - 1; } builder.add(this.inventorySlots.size() - 46); // Add additional slots (e.g. from mods) return builder.build(); } }
package com.fasterxml.jackson.core.json.async; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.async.AsyncTestBase; import com.fasterxml.jackson.core.exc.StreamReadException; import com.fasterxml.jackson.core.testsupport.AsyncReaderWrapper; import java.io.IOException; public class AsyncNonStandardNumberParsingTest extends AsyncTestBase { private final JsonFactory DEFAULT_F = new JsonFactory(); public void testHexadecimal() throws Exception { final String JSON = "[ 0xc0ffee ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (StreamReadException e) { verifyException(e, "Unexpected character ('x'"); } finally { p.close(); } } public void testHexadecimalBigX() throws Exception { final String JSON = "[ 0XC0FFEE ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (StreamReadException e) { verifyException(e, "Unexpected character ('X'"); } finally { p.close(); } } public void testNegativeHexadecimal() throws Exception { final String JSON = "[ -0xc0ffee ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { verifyException(e, "Unexpected character ('x'"); } finally { p.close(); } } public void testFloatMarker() throws Exception { final String JSON = "[ -0.123f ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { verifyException(e, "Unexpected character ('f'"); } finally { p.close(); } } public void testDoubleMarker() throws Exception { final String JSON = "[ -0.123d ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { verifyException(e, "Unexpected character ('d'"); } finally { p.close(); } } public void test2DecimalPoints() throws Exception { final String JSON = "[ -0.123.456 ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { verifyException(e, "Unexpected character ('.'"); } finally { p.close(); } } /** * The format ".NNN" (as opposed to "0.NNN") is not valid JSON, so this should fail */ public void testLeadingDotInDecimal() throws Exception { final String JSON = "[ .123 ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { verifyException(e, "Unexpected character ('.'"); } finally { p.close(); } } /* * The format "+NNN" (as opposed to "NNN") is not valid JSON, so this should fail */ public void testLeadingPlusSignInDecimalDefaultFail() throws Exception { final String JSON = "[ +123 ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { //the message does not match non-async parsers verifyException(e, "Unrecognized token '+123'"); } finally { p.close(); } } /** * The format "NNN." (as opposed to "NNN") is not valid JSON, so this should fail */ public void testTrailingDotInDecimal() throws Exception { final String JSON = "[ 123. ]"; // without enabling, should get an exception AsyncReaderWrapper p = createParser(DEFAULT_F, JSON, 1); assertToken(JsonToken.START_ARRAY, p.nextToken()); try { p.nextToken(); fail("Expected exception"); } catch (Exception e) { //the message does not match non-async parsers verifyException(e, "Unexpected character (' '"); } finally { p.close(); } } private AsyncReaderWrapper createParser(JsonFactory f, String doc, int readBytes) throws IOException { return asyncForBytes(f, readBytes, _jsonDoc(doc), 1); } }
// checkstyle: Checks Java source code for adherence to a set of rules. // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.puppycrawl.tools.checkstyle.checks.indentation; import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_CHILD_ERROR; import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_CHILD_ERROR_MULTI; import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_ERROR; import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_ERROR_MULTI; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; /** * * @author jrichard */ public class IndentationCheckTest extends BaseCheckTestSupport { private static final Pattern NONEMPTY_LINE_REGEX = Pattern.compile(".*?\\S+.*?"); private static final Pattern LINE_WITH_COMMENT_REGEX = Pattern.compile(".*?\\S+.*?(//indent:(\\d+) exp:((>=\\d+)|(\\d+(,\\d+)*?))( warn)?)"); private static final Pattern GET_INDENT_FROM_COMMENT_REGEX = Pattern.compile("//indent:(\\d+).*?"); private static final Pattern MULTILEVEL_COMMENT_REGEX = Pattern.compile("//indent:\\d+ exp:(\\d+(,\\d+)+?)( warn)?"); private static final Pattern SINGLELEVEL_COMMENT_REGEX = Pattern.compile("//indent:\\d+ exp:(\\d+)( warn)?"); private static final Pattern NONSTRICT_LEVEL_COMMENT_REGEX = Pattern.compile("//indent:\\d+ exp:>=(\\d+)( warn)?"); protected static Integer[] getLinesWithWarnAndCheckComments(String aFileName, final int tabWidth) throws IOException { List<Integer> result = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) { int lineNumber = 1; for (String line = br.readLine(); line != null; line = br.readLine()) { Matcher match = LINE_WITH_COMMENT_REGEX.matcher(line); if (match.matches()) { final String comment = match.group(1); final int indentInComment = getIndentFromComment(comment); final int actualIndent = getLineStart(line, tabWidth); if (actualIndent != indentInComment) { throw new IllegalStateException(String.format( "File \"%1$s\" has incorrect indentation in comment." + "Line %2$d: comment:%3$d, actual:%4$d.", aFileName, lineNumber, indentInComment, actualIndent)); } if (isWarnComment(comment)) { result.add(lineNumber); } if (!isCommentConsistent(comment)) { throw new IllegalStateException(String.format( "File \"%1$s\" has inconsistent comment on line %2$d", aFileName, lineNumber)); } } else if (NONEMPTY_LINE_REGEX.matcher(line).matches()) { throw new IllegalStateException(String.format( "File \"%1$s\" has no indentation comment or its format " + "malformed. Error on line: %2$d", aFileName, lineNumber)); } lineNumber++; } } return result.toArray(new Integer[result.size()]); } private static int getIndentFromComment(String comment) { final Matcher match = GET_INDENT_FROM_COMMENT_REGEX.matcher(comment); match.matches(); return Integer.parseInt(match.group(1)); } private static boolean isWarnComment(String comment) { return comment.endsWith(" warn"); } private static boolean isCommentConsistent(String comment) { final int indentInComment = getIndentFromComment(comment); final boolean isWarnComment = isWarnComment(comment); Matcher match = MULTILEVEL_COMMENT_REGEX.matcher(comment); if (match.matches()) { final String[] levels = match.group(1).split(","); final String indentInCommentStr = String.valueOf(indentInComment); final boolean containsActualLevel = Arrays.asList(levels).contains(indentInCommentStr); return containsActualLevel && !isWarnComment || !containsActualLevel && isWarnComment; } match = SINGLELEVEL_COMMENT_REGEX.matcher(comment); if (match.matches()) { final int expectedLevel = Integer.parseInt(match.group(1)); return expectedLevel == indentInComment && !isWarnComment || expectedLevel != indentInComment && isWarnComment; } match = NONSTRICT_LEVEL_COMMENT_REGEX.matcher(comment); if (match.matches()) { final int expectedMinimalIndent = Integer.parseInt(match.group(1)); return indentInComment >= expectedMinimalIndent && !isWarnComment || indentInComment < expectedMinimalIndent && isWarnComment; } throw new IllegalStateException("Comments are not consistent"); } private static int getLineStart(String line, final int tabWidth) { for (int index = 0; index < line.length(); ++index) { if (!Character.isWhitespace(line.charAt(index))) { return CommonUtils.lengthExpandedTabs(line, index, tabWidth); } } return 0; } private void verifyWarns(Configuration config, String filePath, String[] expected, int warnCountCorrection) throws Exception { final int tabWidth = Integer.parseInt(config.getAttribute("tabWidth")); Integer[] linesWithWarn = getLinesWithWarnAndCheckComments(filePath, tabWidth); assertEquals("Expected warning count in UT does not match warn" + " comment count in input file", linesWithWarn.length + warnCountCorrection, expected.length); verify(config, filePath, expected); } private void verifyWarns(Configuration config, String filePath, String... expected) throws Exception { verifyWarns(config, filePath, expected, 0); } @Test public void testGetRequiredTokens() { IndentationCheck checkObj = new IndentationCheck(); final HandlerFactory handlerFactory = new HandlerFactory(); int[] expected = handlerFactory.getHandledTypes(); assertArrayEquals(expected, checkObj.getRequiredTokens()); } @Test public void testGetAcceptableTokens() { IndentationCheck checkObj = new IndentationCheck(); final HandlerFactory handlerFactory = new HandlerFactory(); int[] expected = handlerFactory.getHandledTypes(); assertArrayEquals(expected, checkObj.getAcceptableTokens()); } @Test public void testThrowsIndentProperty() { IndentationCheck indentationCheck = new IndentationCheck(); indentationCheck.setThrowsIndent(1); assertEquals(1, indentationCheck.getThrowsIndent()); } @Test public void forbidCStyle() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "true"); checkConfig.addAttribute("lineWrappingIndentation", "8"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "8"); final String[] expected = { "20: " + getCheckMessage(MSG_ERROR, "int", 29, 12), "21: " + getCheckMessage(MSG_ERROR, "int", 29, 12), }; verifyWarns(checkConfig, getPath("indentation/InputMethodCStyle.java"), expected); } @Test public void testZeroCaseLevel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "0"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputZeroCaseLevel.java"), expected); } @Test public void testAndroidStyle() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "8"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "8"); final String[] expected = { "42: " + getCheckMessage(MSG_ERROR, "extends", 3, 8), "44: " + getCheckMessage(MSG_ERROR, "member def type", 3, 4), "47: " + getCheckMessage(MSG_ERROR, "foo", 8, 12), "50: " + getCheckMessage(MSG_ERROR, "int", 8, 12), "53: " + getCheckMessage(MSG_ERROR, "true", 13, 16), "56: " + getCheckMessage(MSG_ERROR, "+", 16, 20), "57: " + getCheckMessage(MSG_ERROR, "if", 8, 12), "60: " + getCheckMessage(MSG_ERROR, "if rcurly", 11, 12), "62: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 7, 8), }; verifyWarns(checkConfig, getPath("indentation/InputAndroidStyle.java"), expected); } @Test public void testMethodCallLineWrap() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "51: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 18, 20), "52: " + getCheckMessage(MSG_ERROR, "method call rparen", 14, 16), }; verifyWarns(checkConfig, getPath("indentation/InputMethodCallLineWrap.java"), expected); } @Test public void testDifficultAnnotations() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "40: " + getCheckMessage(MSG_ERROR, "@", 0, 4), "41: " + getCheckMessage(MSG_ERROR, "@", 0, 4), "50: " + getCheckMessage(MSG_ERROR, "@", 6, 8), }; verifyWarns(checkConfig, getPath("indentation/InputDifficultAnnotations.java"), expected); } @Test public void testAnonClassesFromGuava() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/FromGuava2.java"), expected); } @Test public void testAnnotations() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/FromGuava.java"), expected); } @Test public void testCorrectIfAndParameters() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/IndentationCorrectIfAndParameterInput.java"), expected); } @Test public void testAnonymousClasses() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputAnonymousClasses.java"), expected); } @Test public void testArrays() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "2"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputArrays.java"), expected); } @Test public void testLabels() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputLabels.java"), expected); } @Test public void testClassesAndMethods() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputClassesMethods.java"), expected); } @Test public void testMembers() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "22: " + getCheckMessage(MSG_ERROR, "=", 5, 6), "57: " + getCheckMessage(MSG_ERROR, "class def rcurly", 3, 2), }; verifyWarns(checkConfig, getPath("indentation/InputMembers.java"), expected); } @Test public void testInvalidLabel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "24: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 10, "8, 12"), "33: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 2, "4, 8"), "36: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 18, "8, 12"), "37: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 18, 8), "39: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 6, "8, 12"), "41: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 6, "8, 12"), }; verifyWarns(checkConfig, getPath("indentation/InputInvalidLabelIndent.java"), expected); } @Test public void testInvalidLabelWithWhileLoop() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "18: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 9, "4, 8"), "19: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 9, "8, 12"), "19: " + getCheckMessage(MSG_ERROR_MULTI, "while", 9, "8, 12"), }; verifyWarns(checkConfig, getPath("indentation/InputInvalidLabelWithWhileLoopIndent.java"), expected); } @Test public void testValidLabel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputValidLabelIndent.java"), expected); } @Test public void testValidIfWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidIfIndent.java"); final String[] expected = { "231: " + getCheckMessage(MSG_ERROR, "(", 8, 12), }; verifyWarns(checkConfig, fname, expected); } @Test public void testValidDotWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidDotIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidMethodWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidMethodIndent.java"); final String[] expected = { "129: " + getCheckMessage(MSG_ERROR, "void", 4, 8), "130: " + getCheckMessage(MSG_ERROR, "method5", 4, 8), }; verifyWarns(checkConfig, fname, expected); } @Test public void testInvalidMethodWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidMethodIndent.java"); final String[] expected = { "23: " + getCheckMessage(MSG_ERROR, "ctor def rcurly", 6, 4), "26: " + getCheckMessage(MSG_ERROR, "ctor def modifier", 6, 4), "27: " + getCheckMessage(MSG_ERROR, "ctor def lcurly", 2, 4), "28: " + getCheckMessage(MSG_ERROR, "ctor def rcurly", 6, 4), "31: " + getCheckMessage(MSG_ERROR, "method def modifier", 2, 4), "32: " + getCheckMessage(MSG_ERROR, "method def rcurly", 6, 4), "69: " + getCheckMessage(MSG_ERROR, "method def modifier", 5, 4), "70: " + getCheckMessage(MSG_ERROR, "final", 5, 9), "71: " + getCheckMessage(MSG_ERROR, "void", 5, 9), "72: " + getCheckMessage(MSG_ERROR, "method5", 4, 9), "80: " + getCheckMessage(MSG_ERROR, "method def modifier", 3, 4), "81: " + getCheckMessage(MSG_ERROR, "final", 3, 7), "82: " + getCheckMessage(MSG_ERROR, "void", 3, 7), "83: " + getCheckMessage(MSG_ERROR, "method6", 5, 7), "93: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 4, 8), "93: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 4, 8), "98: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), "98: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 6, 8), "99: " + getCheckMessage(MSG_ERROR, "if", 6, 8), "100: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), "100: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "101: " + getCheckMessage(MSG_ERROR, "if rcurly", 6, 8), "104: " + getCheckMessage(MSG_ERROR, "Arrays", 10, 12), "113: " + getCheckMessage(MSG_ERROR, "+", 10, 12), "113: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "122: " + getCheckMessage(MSG_ERROR, "new", 10, 12), "126: " + getCheckMessage(MSG_ERROR, "new", 10, 12), "127: " + getCheckMessage(MSG_ERROR, ")", 6, 8), "131: " + getCheckMessage(MSG_ERROR, "method call rparen", 6, 8), "145: " + getCheckMessage(MSG_ERROR, "6", 10, 12), "145: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "148: " + getCheckMessage(MSG_ERROR, "6", 10, 12), "148: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "158: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 6, 12), "170: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 4, 8), "175: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 4, 8), "179: " + getCheckMessage(MSG_ERROR, "int", 0, 8), "180: " + getCheckMessage(MSG_ERROR, "method9", 4, 8), "190: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 12, 8), }; verifyWarns(checkConfig, fname, expected, 6); } @Test public void testInvalidSwitchWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidSwitchIndent.java"); final String[] expected = { "30: " + getCheckMessage(MSG_ERROR, "switch", 6, 8), "32: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), "33: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), "33: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), "37: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), "39: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 12), "40: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), "43: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), "44: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), "44: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), "45: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), "53: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), "53: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), "54: " + getCheckMessage(MSG_CHILD_ERROR, "block", 18, 16), "55: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), "59: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), "62: " + getCheckMessage(MSG_ERROR, "block rcurly", 14, 12), "66: " + getCheckMessage(MSG_ERROR, "block lcurly", 14, 12), "69: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), "76: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 16), "81: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 16), "89: " + getCheckMessage(MSG_ERROR, "switch rcurly", 6, 8), "92: " + getCheckMessage(MSG_ERROR, "switch lcurly", 6, 8), "93: " + getCheckMessage(MSG_ERROR, "switch rcurly", 10, 8), "95: " + getCheckMessage(MSG_ERROR, "switch lcurly", 10, 8), "96: " + getCheckMessage(MSG_ERROR, "switch rcurly", 6, 8), }; verifyWarns(checkConfig, fname, expected, 3); } @Test public void testValidSwitchWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidSwitchIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidArrayInitDefaultIndentWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidArrayInitDefaultIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidArrayInitWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "8"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidArrayInitIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testInvalidArrayInitWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidArrayInitIndent.java"); final String[] expected = { "21: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), "22: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), "24: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), "28: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), "29: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 8, 10), "30: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 4, "6, 10"), "33: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 9, 8), "34: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 7, 8), "35: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 9, 8), "40: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 2, 4), "44: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "4, 8"), "48: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 2, 4), "52: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "array initialization", 20, "8, 31, 33"), "53: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "array initialization", 4, "8, 31, 33"), "58: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 6, 8), "63: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), "65: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), "66: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 2, "6, 10"), "69: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 6, 8), "76: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), "89: " + getCheckMessage(MSG_ERROR, "1", 8, 12), "89: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 8, 12), "100: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), "101: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), "104: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), "105: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), "106: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"), "109: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 6, 8), "110: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), "111: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), "112: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"), }; //Test input for this test case is not checked due to issue #693. verify(checkConfig, fname, expected); } @Test public void testValidTryWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidTryIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testInvalidTryWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidTryIndent.java"); final String[] expected = { "25: " + getCheckMessage(MSG_ERROR, "try", 9, 8), "26: " + getCheckMessage(MSG_ERROR, "try rcurly", 7, 8), "28: " + getCheckMessage(MSG_ERROR, "catch rcurly", 7, 8), "30: " + getCheckMessage(MSG_ERROR, "try", 4, 8), "31: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), "31: " + getCheckMessage(MSG_CHILD_ERROR, "try", 8, 12), "32: " + getCheckMessage(MSG_ERROR, "try rcurly", 4, 8), "33: " + getCheckMessage(MSG_CHILD_ERROR, "finally", 8, 12), "33: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), "38: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 8, 12), "38: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), "43: " + getCheckMessage(MSG_ERROR, "try rcurly", 10, 8), "45: " + getCheckMessage(MSG_ERROR, "catch rcurly", 6, 8), "52: " + getCheckMessage(MSG_ERROR, "catch rcurly", 5, 8), "59: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), "59: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "60: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 14, 12), "61: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), "61: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "63: " + getCheckMessage(MSG_ERROR, "catch", 6, 8), "70: " + getCheckMessage(MSG_ERROR, "try lcurly", 10, 8), "72: " + getCheckMessage(MSG_ERROR, "try rcurly", 10, 8), "74: " + getCheckMessage(MSG_ERROR, "catch lcurly", 6, 8), "77: " + getCheckMessage(MSG_ERROR, "catch rcurly", 10, 8), "80: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), "80: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), }; verifyWarns(checkConfig, fname, expected, 6); } @Test public void testInvalidClassDefWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidClassDefIndent.java"); final String[] expected = { "22: " + getCheckMessage(MSG_ERROR, "class def modifier", 2, 0), "28: " + getCheckMessage(MSG_ERROR, "class def lcurly", 2, 0), "31: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), "34: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 0), "38: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), "43: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), "44: " + getCheckMessage(MSG_ERROR, "implements", 2, 4), "50: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), "58: " + getCheckMessage(MSG_ERROR, "implements", 2, 4), "59: " + getCheckMessage(MSG_ERROR, "java", 2, 4), "64: " + getCheckMessage(MSG_ERROR, "class def modifier", 2, 0), "65: " + getCheckMessage(MSG_ERROR, "class def lcurly", 2, 0), "73: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), "77: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), "86: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 4), "88: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 4), "91: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 4), "95: " + getCheckMessage(MSG_ERROR, "member def modifier", 6, 8), "101: " + getCheckMessage(MSG_ERROR, "int", 10, 12), "106: " + getCheckMessage(MSG_ERROR, "member def modifier", 6, 8), "111: " + getCheckMessage(MSG_ERROR, "class def rcurly", 6, 4), "113: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 4), "119: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 8), "122: " + getCheckMessage(MSG_ERROR, "class def ident", 10, 8), "124: " + getCheckMessage(MSG_ERROR, "class def rcurly", 10, 8), "127: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), "132: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 10, 8), "133: " + getCheckMessage(MSG_ERROR_MULTI, "object def lcurly", 8, "10, 14"), "137: " + getCheckMessage(MSG_ERROR_MULTI, "object def rcurly", 8, "10, 14"), "141: " + getCheckMessage(MSG_ERROR_MULTI, "object def lcurly", 6, "8, 12"), "142: " + getCheckMessage(MSG_ERROR, "method def modifier", 12, 10), "144: " + getCheckMessage(MSG_ERROR, "method def rcurly", 12, 10), "145: " + getCheckMessage(MSG_ERROR_MULTI, "object def rcurly", 6, "8, 12"), "150: " + getCheckMessage(MSG_ERROR, "method def modifier", 10, 12), "152: " + getCheckMessage(MSG_ERROR, "method def rcurly", 10, 12), "188: " + getCheckMessage(MSG_ERROR, "class", 0, 4), }; verifyWarns(checkConfig, fname, expected); } @Test public void testInvalidBlockWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidBlockIndent.java"); final String[] expected = { "26: " + getCheckMessage(MSG_ERROR, "block lcurly", 7, 8), "27: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), "29: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), "30: " + getCheckMessage(MSG_ERROR, "block rcurly", 7, 8), "32: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), "34: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 8), "35: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), "38: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), "39: " + getCheckMessage(MSG_CHILD_ERROR, "block", 13, 12), "39: " + getCheckMessage(MSG_ERROR, "member def type", 13, 12), "41: " + getCheckMessage(MSG_CHILD_ERROR, "block", 13, 12), "42: " + getCheckMessage(MSG_ERROR, "block rcurly", 9, 8), "45: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), "46: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), "46: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), "48: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), "49: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 8), "52: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), "55: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), "55: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), "59: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), "63: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), "68: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), "70: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), "71: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), "71: " + getCheckMessage(MSG_ERROR, "member def type", 14, 16), "86: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), "95: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), "96: " + getCheckMessage(MSG_ERROR, "static initialization", 6, 4), "100: " + getCheckMessage(MSG_ERROR, "member def type", 7, 8), "100: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 7, 8), "103: " + getCheckMessage(MSG_ERROR, "static initialization", 6, 4), "105: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 2, 4), "107: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), "109: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), "111: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), "113: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), "113: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), "116: " + getCheckMessage(MSG_ERROR, "static initialization lcurly", 2, 4), "117: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), "117: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), "118: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), "123: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), "123: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), "128: " + getCheckMessage(MSG_ERROR, "member def type", 4, 8), "128: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 4, 8), "129: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 2, 4), "134: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), "137: " + getCheckMessage(MSG_ERROR, "block lcurly", 2, 4), "138: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 4), "141: " + getCheckMessage(MSG_ERROR, "block lcurly", 2, 4), "143: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 4), "145: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 4), "147: " + getCheckMessage(MSG_ERROR, "block rcurly", 2, 4), "150: " + getCheckMessage(MSG_CHILD_ERROR, "block", 6, 8), "150: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), }; verifyWarns(checkConfig, fname, expected, 10); } @Test public void testInvalidIfWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidIfIndent.java"); final String[] expected = { "55: " + getCheckMessage(MSG_ERROR, "if", 1, 8), "60: " + getCheckMessage(MSG_ERROR, "if", 9, 8), "61: " + getCheckMessage(MSG_ERROR, "if lcurly", 9, 8), "62: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), "64: " + getCheckMessage(MSG_ERROR, "if", 6, 8), "65: " + getCheckMessage(MSG_ERROR, "if lcurly", 5, 8), "66: " + getCheckMessage(MSG_ERROR, "if rcurly", 5, 8), "70: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), "71: " + getCheckMessage(MSG_ERROR, "else rcurly", 7, 8), "74: " + getCheckMessage(MSG_ERROR, "if", 9, 8), "75: " + getCheckMessage(MSG_ERROR, "if lcurly", 7, 8), "77: " + getCheckMessage(MSG_ERROR, "else", 9, 8), "79: " + getCheckMessage(MSG_ERROR, "else rcurly", 9, 8), "82: " + getCheckMessage(MSG_ERROR, "if", 10, 8), "83: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), "84: " + getCheckMessage(MSG_ERROR, "else", 9, 8), "85: " + getCheckMessage(MSG_ERROR, "else lcurly", 7, 8), "86: " + getCheckMessage(MSG_ERROR, "else rcurly", 9, 8), "90: " + getCheckMessage(MSG_ERROR, "if", 9, 8), "91: " + getCheckMessage(MSG_ERROR, "if lcurly", 9, 8), "92: " + getCheckMessage(MSG_ERROR, "if rcurly", 9, 8), "93: " + getCheckMessage(MSG_ERROR, "else lcurly", 7, 8), "94: " + getCheckMessage(MSG_ERROR, "else rcurly", 10, 8), "97: " + getCheckMessage(MSG_ERROR, "if", 6, 8), "98: " + getCheckMessage(MSG_ERROR, "if lcurly", 10, 8), "99: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), "100: " + getCheckMessage(MSG_ERROR, "else rcurly", 7, 8), "103: " + getCheckMessage(MSG_ERROR, "if", 5, 8), "104: " + getCheckMessage(MSG_ERROR, "if rcurly", 11, 8), "105: " + getCheckMessage(MSG_ERROR, "else", 5, 8), "106: " + getCheckMessage(MSG_ERROR, "else rcurly", 11, 8), "126: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), "131: " + getCheckMessage(MSG_ERROR, "if lcurly", 10, 8), "132: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), "132: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "137: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), "138: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "140: " + getCheckMessage(MSG_CHILD_ERROR, "else", 10, 12), "140: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "141: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), "148: " + getCheckMessage(MSG_CHILD_ERROR, "if", 16, 12), "149: " + getCheckMessage(MSG_ERROR, "if rcurly", 9, 8), "152: " + getCheckMessage(MSG_CHILD_ERROR, "else", 16, 12), "158: " + getCheckMessage(MSG_CHILD_ERROR, "if", 0, 12), "158: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 0, 12), "162: " + getCheckMessage(MSG_CHILD_ERROR, "else", 40, 12), "169: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), "172: " + getCheckMessage(MSG_CHILD_ERROR, "else", 14, 12), "178: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), "178: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "180: " + getCheckMessage(MSG_CHILD_ERROR, "else", 10, 12), "180: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "184: " + getCheckMessage(MSG_ERROR, "if", 10, 8), "185: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), "186: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), "187: " + getCheckMessage(MSG_ERROR, "else", 10, 8), "188: " + getCheckMessage(MSG_CHILD_ERROR, "else", 14, 12), "189: " + getCheckMessage(MSG_ERROR, "else rcurly", 10, 8), "192: " + getCheckMessage(MSG_ERROR, "&&", 9, 12), "192: " + getCheckMessage(MSG_CHILD_ERROR, "if", 9, 12), "193: " + getCheckMessage(MSG_ERROR, "&&", 11, 12), "193: " + getCheckMessage(MSG_CHILD_ERROR, "if", 11, 12), "197: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), "200: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), "207: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), "207: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "209: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), "209: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "225: " + getCheckMessage(MSG_ERROR, "if", 10, 12), "229: " + getCheckMessage(MSG_CHILD_ERROR, "if", 18, 20), "229: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 18, 20), "233: " + getCheckMessage(MSG_ERROR, "if rcurly", 40, 8), "240: " + getCheckMessage(MSG_ERROR, "if rparen", 10, 8), "245: " + getCheckMessage(MSG_ERROR, "if rparen", 6, 8), "251: " + getCheckMessage(MSG_ERROR, "(", 6, 12), "251: " + getCheckMessage(MSG_ERROR, "if lparen", 6, 8), "253: " + getCheckMessage(MSG_ERROR, "if rparen", 6, 8), }; verifyWarns(checkConfig, fname, expected, 11); } @Test public void testInvalidWhileWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidWhileIndent.java"); final String[] expected = { "25: " + getCheckMessage(MSG_ERROR, "while", 9, 8), "26: " + getCheckMessage(MSG_ERROR, "while rcurly", 7, 8), "28: " + getCheckMessage(MSG_ERROR, "while", 7, 8), "29: " + getCheckMessage(MSG_ERROR, "while lcurly", 9, 8), "30: " + getCheckMessage(MSG_ERROR, "while rcurly", 9, 8), "32: " + getCheckMessage(MSG_ERROR, "while", 9, 8), "33: " + getCheckMessage(MSG_ERROR, "while lcurly", 6, 8), "34: " + getCheckMessage(MSG_CHILD_ERROR, "while", 14, 12), "35: " + getCheckMessage(MSG_ERROR, "while rcurly", 6, 8), "37: " + getCheckMessage(MSG_ERROR, "while", 10, 8), "39: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), "41: " + getCheckMessage(MSG_ERROR, "while", 10, 8), "44: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), "46: " + getCheckMessage(MSG_ERROR, "while", 6, 8), "47: " + getCheckMessage(MSG_ERROR, "while lcurly", 10, 8), "50: " + getCheckMessage(MSG_ERROR, "while rcurly", 6, 8), "53: " + getCheckMessage(MSG_ERROR, "if", 14, 12), "54: " + getCheckMessage(MSG_CHILD_ERROR, "if", 18, 16), "55: " + getCheckMessage(MSG_ERROR, "if rcurly", 14, 12), "56: " + getCheckMessage(MSG_CHILD_ERROR, "while", 14, 12), "57: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), "60: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), "66: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), "71: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), "78: " + getCheckMessage(MSG_ERROR, "while rparen", 5, 8), "85: " + getCheckMessage(MSG_ERROR, "while rparen", 10, 8), "92: " + getCheckMessage(MSG_ERROR, "while rparen", 10, 8), "99: " + getCheckMessage(MSG_CHILD_ERROR, "while", 8, 12), }; verifyWarns(checkConfig, fname, expected); } @Test public void testInvalidInvalidAnonymousClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidAnonymousClassIndent.java"); final String[] expected = { "28: " + getCheckMessage(MSG_ERROR_MULTI, "method def rcurly", 17, "12, 16"), }; verifyWarns(checkConfig, fname, expected); } @Test public void testInvalidForWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputInvalidForIndent.java"); final String[] expected = { "26: " + getCheckMessage(MSG_ERROR, "for", 6, 8), "27: " + getCheckMessage(MSG_ERROR, "for rcurly", 10, 8), "29: " + getCheckMessage(MSG_ERROR, "for", 9, 8), "30: " + getCheckMessage(MSG_ERROR, "for lcurly", 6, 8), "31: " + getCheckMessage(MSG_ERROR, "for rcurly", 6, 8), "35: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), "35: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), "36: " + getCheckMessage(MSG_ERROR, "for rcurly", 10, 8), "39: " + getCheckMessage(MSG_ERROR, "for lcurly", 10, 8), "40: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), "40: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), "48: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), "48: " + getCheckMessage(MSG_ERROR, "i", 10, 12), "54: " + getCheckMessage(MSG_ERROR, "for", 7, 8), "55: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), "55: " + getCheckMessage(MSG_ERROR, "int", 10, 11), "55: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), "64: " + getCheckMessage(MSG_CHILD_ERROR, "for", 7, 12), "64: " + getCheckMessage(MSG_ERROR, "i", 7, 12), "69: " + getCheckMessage(MSG_ERROR, "for", 6, 8), "70: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), "71: " + getCheckMessage(MSG_CHILD_ERROR, "for", 14, 16), "72: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), "77: " + getCheckMessage(MSG_ERROR, "for rcurly", 39, 8), "81: " + getCheckMessage(MSG_ERROR, "for rparen", 12, 8), }; verifyWarns(checkConfig, fname, expected, 6); } @Test public void testValidForWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidForIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidDoWhileWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidDoWhileIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidBlockWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidBlockIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidWhileWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidWhileIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidClassDefWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidClassDefIndent.java"); final String[] expected = { "49: " + getCheckMessage(MSG_ERROR, "class", 0, 4), "71: " + getCheckMessage(MSG_ERROR, "int", 8, 12), }; verifyWarns(checkConfig, fname, expected); } @Test public void testValidInterfaceDefWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidInterfaceDefIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testValidCommaWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String fname = getPath("indentation/InputValidCommaIndent.java"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, fname, expected); } @Test public void testTabs() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "29: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 9, 8), }; verifyWarns(checkConfig, getPath("indentation/InputUseTabs.java"), expected); } @Test public void testIndentationLevel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "2"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "29: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 5, 4), }; verifyWarns(checkConfig, getPath("indentation/InputUseTwoSpaces.java"), expected); } @Test public void testThrowsIndentationLevel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "8"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InvalidInputThrowsIndent.java"), expected); } @Test public void testCaseLevel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "0"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "27: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 8), }; verifyWarns(checkConfig, getPath("indentation/InputCaseLevel.java"), expected); } @Test public void testBraceAdjustment() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "2"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "28: " + getCheckMessage(MSG_ERROR, "if rcurly", 8, 10), }; verifyWarns(checkConfig, getPath("indentation/InputBraceAdjustment.java"), expected); } @Test public void testInvalidAssignWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = { "22: " + getCheckMessage(MSG_ERROR, "getLineNo", 10, 12), "24: " + getCheckMessage(MSG_ERROR, "getLine", 10, 12), "28: " + getCheckMessage(MSG_ERROR, "=", 9, 12), "29: " + getCheckMessage(MSG_ERROR, "1", 10, 12), }; verifyWarns(checkConfig, getPath("indentation/InputInvalidAssignIndent.java"), expected); } @Test public void testInvalidImportIndent() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("basicOffset", "8"); checkConfig.addAttribute("tabWidth", "4"); final String[] expected = { "4: " + getCheckMessage(MSG_CHILD_ERROR, "import", 2, 8), }; verifyWarns(checkConfig, getPath("indentation/InputInvalidImportIndent.java"), expected); } @Test public void testValidAssignWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputValidAssignIndent.java"), expected); } @Test public void test15Extensions() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/Input15Extensions.java"), expected); } @Test public void testTryResources() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputValidTryResourcesIndent.java"), expected); } @Test public void testSwitchCustom() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "8"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "8"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputSwitchCustom.java"), expected); } @Test public void testSynchronizedStatement() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "8"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "8"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputSynchronizedStatement.java"), expected); } @Test public void testSynchronizedMethod() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("arrayInitIndent", "4"); checkConfig.addAttribute("basicOffset", "4"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "4"); checkConfig.addAttribute("forceStrictCondition", "false"); checkConfig.addAttribute("lineWrappingIndentation", "8"); checkConfig.addAttribute("tabWidth", "4"); checkConfig.addAttribute("throwsIndent", "8"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputSynchronizedMethod.java"), expected); } @Test public void testAnonymousClassInMethod() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("tabWidth", "8"); checkConfig.addAttribute("basicOffset", "2"); checkConfig.addAttribute("braceAdjustment", "0"); checkConfig.addAttribute("caseIndent", "2"); checkConfig.addAttribute("lineWrappingIndentation", "4"); checkConfig.addAttribute("throwsIndent", "4"); checkConfig.addAttribute("arrayInitIndent", "2"); final String[] expected = { "19: " + getCheckMessage(MSG_ERROR, "method def modifier", 8, 2), "20: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 16, 4), "21: " + getCheckMessage(MSG_ERROR_MULTI, "method def modifier", 24, "18, 20, 22"), "23: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "method def", 32, "20, 22, 24"), "24: " + getCheckMessage(MSG_ERROR_MULTI, "method def rcurly", 24, "18, 20, 22"), "26: " + getCheckMessage(MSG_ERROR, "method def rcurly", 8, 2), }; verifyWarns(checkConfig, getPath("indentation/InputAnonymousClassInMethod.java"), expected); } @Test public void testAnnotationDefinition() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("tabWidth", "4"); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verifyWarns(checkConfig, getPath("indentation/InputAnnotationDefinition.java"), expected); } @Test public void testPackageDeclaration() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("tabWidth", "4"); final String[] expected = { "1: " + getCheckMessage(MSG_ERROR, "package def", 1, 0), }; verifyWarns(checkConfig, getPath("indentation/InputPackageDeclaration.java"), expected); } }
package org.csanchez.jenkins.plugins.kubernetes.pipeline; import static org.csanchez.jenkins.plugins.kubernetes.KubernetesTestUtil.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.junit.Assume.*; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import hudson.model.Computer; import com.gargoylesoftware.htmlunit.html.DomNodeUtil; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.slaves.SlaveComputer; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.client.KubernetesClientException; import jenkins.model.Jenkins; import org.csanchez.jenkins.plugins.kubernetes.KubernetesSlave; import org.csanchez.jenkins.plugins.kubernetes.PodAnnotation; import org.csanchez.jenkins.plugins.kubernetes.PodTemplate; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRuleNonLocalhost; import org.jvnet.hudson.test.LoggerRule; import hudson.model.Result; import java.util.Locale; import org.junit.Ignore; import org.jvnet.hudson.test.MockAuthorizationStrategy; /** * @author Carlos Sanchez */ public class KubernetesPipelineTest extends AbstractKubernetesPipelineTest { private static final Logger LOGGER = Logger.getLogger(KubernetesPipelineTest.class.getName()); @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Rule public LoggerRule warnings = new LoggerRule(); @Before public void setUp() throws Exception { deletePods(cloud.connect(), getLabels(cloud, this, name), false); warnings.record("", Level.WARNING).capture(1000); assertNotNull(createJobThenScheduleRun()); } @Issue("JENKINS-57993") @Test public void runInPod() throws Exception { SemaphoreStep.waitForStart("podTemplate/1", b); List<PodTemplate> templates = podTemplatesWithLabel(name.getMethodName(), cloud.getAllTemplates()); assertThat(templates, hasSize(1)); SemaphoreStep.success("podTemplate/1", null); // check if build failed assertTrue("Build has failed early: " + b.getResult(), b.isBuilding() || Result.SUCCESS.equals(b.getResult())); LOGGER.log(Level.INFO, "Found templates with label runInPod: {0}", templates); for (PodTemplate template : cloud.getAllTemplates()) { LOGGER.log(Level.INFO, "Cloud template \"{0}\" labels: {1}", new Object[] { template.getName(), template.getLabelSet() }); } Map<String, String> labels = getLabels(cloud, this, name); SemaphoreStep.waitForStart("pod/1", b); for (Computer c : r.jenkins.getComputers()) { // TODO perhaps this should be built into JenkinsRule via ComputerListener.preLaunch? new Thread(() -> { long pos = 0; try { while (Jenkins.getInstanceOrNull() != null) { // otherwise get NPE from Computer.getLogDir if (c.getLogFile().isFile()) { // TODO should LargeText.FileSession handle this? pos = c.getLogText().writeLogTo(pos, System.out); } Thread.sleep(100); } } catch (Exception x) { x.printStackTrace(); } }, "watching logs for " + c.getDisplayName()).start(); System.out.println(c.getLog()); } PodList pods = cloud.connect().pods().withLabels(labels).list(); assertThat( "Expected one pod with labels " + labels + " but got: " + pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()), pods.getItems(), hasSize(1)); SemaphoreStep.success("pod/1", null); PodTemplate template = templates.get(0); List<PodAnnotation> annotations = template.getAnnotations(); assertNotNull(annotations); boolean foundBuildUrl=false; for(PodAnnotation pd : annotations) { if(pd.getKey().equals("buildUrl")) { assertTrue(pd.getValue().contains(p.getUrl())); foundBuildUrl=true; } } assertTrue(foundBuildUrl); assertEquals(Integer.MAX_VALUE, template.getInstanceCap()); assertThat(template.getLabelsMap(), hasEntry("jenkins/" + name.getMethodName(), "true")); Pod pod = pods.getItems().get(0); LOGGER.log(Level.INFO, "One pod found: {0}", pod); assertThat(pod.getMetadata().getLabels(), hasEntry("jenkins", "slave")); assertThat("Pod labels are wrong: " + pod, pod.getMetadata().getLabels(), hasEntry("jenkins/" + name.getMethodName(), "true")); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("script file contents: ", b); assertFalse("There are pods leftover after test execution, see previous logs", deletePods(cloud.connect(), getLabels(cloud, this, name), true)); assertThat("routine build should not issue warnings", warnings.getRecords().stream(). filter(lr -> lr.getLevel().intValue() >= Level.WARNING.intValue()). map(lr -> lr.getSourceClassName() + "." + lr.getSourceMethodName() + ": " + lr.getMessage()).collect(Collectors.toList()), // LogRecord does not override toString emptyIterable()); } @Test public void runIn2Pods() throws Exception { SemaphoreStep.waitForStart("podTemplate1/1", b); String label1 = name.getMethodName() + "-1"; PodTemplate template1 = podTemplatesWithLabel(label1, cloud.getAllTemplates()).get(0); SemaphoreStep.success("podTemplate1/1", null); assertEquals(Integer.MAX_VALUE, template1.getInstanceCap()); assertThat(template1.getLabelsMap(), hasEntry("jenkins/" + label1, "true")); SemaphoreStep.waitForStart("pod1/1", b); Map<String, String> labels1 = getLabels(cloud, this, name); labels1.put("jenkins/"+label1, "true"); PodList pods = cloud.connect().pods().withLabels(labels1).list(); assertTrue(!pods.getItems().isEmpty()); SemaphoreStep.success("pod1/1", null); SemaphoreStep.waitForStart("podTemplate2/1", b); String label2 = name.getMethodName() + "-2"; PodTemplate template2 = podTemplatesWithLabel(label2, cloud.getAllTemplates()).get(0); SemaphoreStep.success("podTemplate2/1", null); assertEquals(Integer.MAX_VALUE, template2.getInstanceCap()); assertThat(template2.getLabelsMap(), hasEntry("jenkins/" + label2, "true")); assertNull(label2 + " should not inherit from anything", template2.getInheritFrom()); SemaphoreStep.waitForStart("pod2/1", b); Map<String, String> labels2 = getLabels(cloud, this, name); labels1.put("jenkins/" + label2, "true"); PodList pods2 = cloud.connect().pods().withLabels(labels2).list(); assertTrue(!pods2.getItems().isEmpty()); SemaphoreStep.success("pod2/1", null); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("script file contents: ", b); assertFalse("There are pods leftover after test execution, see previous logs", deletePods(cloud.connect(), getLabels(cloud, this, name), true)); } private List<PodTemplate> podTemplatesWithLabel(String label, List<PodTemplate> templates) { return templates.stream().filter(t -> label.equals(t.getLabel())).collect(Collectors.toList()); } @Issue("JENKINS-57893") @Test public void runInPodFromYaml() throws Exception { List<PodTemplate> templates = cloud.getTemplates(); while (templates.isEmpty()) { LOGGER.log(Level.INFO, "Waiting for template to be created"); templates = cloud.getTemplates(); Thread.sleep(1000); } assertFalse(templates.isEmpty()); PodTemplate template = templates.get(0); assertEquals(Integer.MAX_VALUE, template.getInstanceCap()); r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("script file contents: ", b); r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b); r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b); assertFalse("There are pods leftover after test execution, see previous logs", deletePods(cloud.connect(), getLabels(cloud, this, name), true)); } @Test public void runInPodWithDifferentShell() throws Exception { r.assertBuildStatus(Result.FAILURE,r.waitForCompletion(b)); /* TODO instead the program fails with a IOException: Pipe closed from ContainerExecDecorator.doExec: r.assertLogContains("/bin/bash: no such file or directory", b); */ } @Test public void bourneShellElsewhereInPath() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("/kaniko:/busybox", b); } @Test public void runInPodWithMultipleContainers() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("image: \"jenkins/jnlp-slave:3.10-1-alpine\"", b); r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b); r.assertLogContains("image: \"golang:1.6.3-alpine\"", b); r.assertLogContains("My Kubernetes Pipeline", b); r.assertLogContains("my-mount", b); r.assertLogContains("Apache Maven 3.3.9", b); } @Test public void runInPodNested() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b); r.assertLogContains("image: \"golang:1.6.3-alpine\"", b); r.assertLogContains("Apache Maven 3.3.9", b); r.assertLogContains("go version go1.6.3", b); } @Issue("JENKINS-57548") @Test public void runInPodNestedExplicitInherit() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("image: \"maven:3.3.9-jdk-8-alpine\"", b); r.assertLogNotContains("image: \"golang:1.6.3-alpine\"", b); r.assertLogContains("Apache Maven 3.3.9", b); r.assertLogNotContains("go version go1.6.3", b); } @Issue({"JENKINS-57893", "JENKINS-58540"}) @Test public void runInPodWithExistingTemplate() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("outside container", b); r.assertLogContains("inside container", b); assertEnvVars(r, b); } @Issue({"JENKINS-57893", "JENKINS-58540"}) @Test public void runWithEnvVariables() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); assertEnvVars(r, b); r.assertLogContains("OUTSIDE_CONTAINER_BUILD_NUMBER = 1\n", b); r.assertLogContains("INSIDE_CONTAINER_BUILD_NUMBER = 1\n", b); r.assertLogContains("OUTSIDE_CONTAINER_JOB_NAME = " + getProjectName() + "\n", b); r.assertLogContains("INSIDE_CONTAINER_JOB_NAME = " + getProjectName() +"\n", b); // check that we are getting the correct java home r.assertLogContains("INSIDE_JAVA_HOME =\n", b); r.assertLogContains("JNLP_JAVA_HOME = /usr/lib/jvm/java-1.8-openjdk\n", b); r.assertLogContains("JAVA7_HOME = /usr/lib/jvm/java-1.7-openjdk/jre\n", b); r.assertLogContains("JAVA8_HOME = /usr/lib/jvm/java-1.8-openjdk/jre\n", b); // check that we are not filtering too much r.assertLogContains("INSIDE_JAVA_HOME_X = java-home-x\n", b); r.assertLogContains("OUTSIDE_JAVA_HOME_X = java-home-x\n", b); r.assertLogContains("JNLP_JAVA_HOME_X = java-home-x\n", b); r.assertLogContains("JAVA7_HOME_X = java-home-x\n", b); r.assertLogContains("JAVA8_HOME_X = java-home-x\n", b); } @Test public void runWithEnvVariablesInContext() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("The initial value of POD_ENV_VAR is pod-env-var-value", b); r.assertLogContains("The value of POD_ENV_VAR outside container is /bin/mvn:pod-env-var-value", b); r.assertLogContains("The value of FROM_ENV_DEFINITION is ABC", b); r.assertLogContains("The value of FROM_WITHENV_DEFINITION is DEF", b); r.assertLogContains("The value of WITH_QUOTE is \"WITH_QUOTE", b); r.assertLogContains("The value of AFTER_QUOTE is AFTER_QUOTE\"", b); r.assertLogContains("The value of ESCAPED_QUOTE is \\\"ESCAPED_QUOTE", b); r.assertLogContains("The value of AFTER_ESCAPED_QUOTE is AFTER_ESCAPED_QUOTE\\\"", b); r.assertLogContains("The value of SINGLE_QUOTE is BEFORE'AFTER", b); r.assertLogContains("The value of WITH_NEWLINE is before newline\nafter newline", b); r.assertLogContains("The value of POD_ENV_VAR is /bin/mvn:pod-env-var-value", b); r.assertLogContains("The value of WILL.NOT is ", b); } private void assertEnvVars(JenkinsRuleNonLocalhost r2, WorkflowRun b) throws Exception { r.assertLogNotContains(POD_ENV_VAR_FROM_SECRET_VALUE, b); r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b); r.assertLogContains("INSIDE_CONTAINER_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n", b); r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_LEGACY = " + CONTAINER_ENV_VAR_VALUE + "\n", b); r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b); r.assertLogContains("INSIDE_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b); r.assertLogContains("INSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b); r.assertLogContains("INSIDE_EMPTY_POD_ENV_VAR_FROM_SECRET = ''", b); r.assertLogContains("INSIDE_GLOBAL = " + GLOBAL + "\n", b); r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR =\n", b); r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR_LEGACY =\n", b); r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR_FROM_SECRET = or\n", b); r.assertLogContains("OUTSIDE_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b); r.assertLogContains("OUTSIDE_POD_ENV_VAR_FROM_SECRET = ******** or " + POD_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b); r.assertLogContains("OUTSIDE_EMPTY_POD_ENV_VAR_FROM_SECRET = ''", b); r.assertLogContains("OUTSIDE_GLOBAL = " + GLOBAL + "\n", b); } @Test public void runWithOverriddenEnvVariables() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("OUTSIDE_CONTAINER_HOME_ENV_VAR = /home/jenkins\n", b); r.assertLogContains("INSIDE_CONTAINER_HOME_ENV_VAR = /root\n",b); r.assertLogContains("OUTSIDE_CONTAINER_POD_ENV_VAR = " + POD_ENV_VAR_VALUE + "\n", b); r.assertLogContains("INSIDE_CONTAINER_POD_ENV_VAR = " + CONTAINER_ENV_VAR_VALUE + "\n",b); } @Test public void supportComputerEnvVars() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("OPENJDK_BUILD_NUMBER: 1\n", b); r.assertLogContains("JNLP_BUILD_NUMBER: 1\n", b); r.assertLogContains("DEFAULT_BUILD_NUMBER: 1\n", b); } @Test public void runDirContext() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); String workspace = "/home/jenkins/agent/workspace/" + getProjectName(); r.assertLogContains("initpwd is -" + workspace + "-", b); r.assertLogContains("dirpwd is -" + workspace + "/hz-", b); r.assertLogContains("postpwd is -" + workspace + "-", b); } @Test public void runInPodWithLivenessProbe() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); r.assertLogContains("Still alive", b); } @Test public void runWithActiveDeadlineSeconds() throws Exception { SemaphoreStep.waitForStart("podTemplate/1", b); PodTemplate deadlineTemplate = cloud.getAllTemplates().stream().filter(x -> name.getMethodName().equals(x.getLabel())).findAny().orElse(null); assertNotNull(deadlineTemplate); SemaphoreStep.success("podTemplate/1", null); assertEquals(10, deadlineTemplate.getActiveDeadlineSeconds()); r.assertLogNotContains("Hello from container!", b); } @Test public void runInPodWithRetention() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); assertTrue(deletePods(cloud.connect(), getLabels(this, name), true)); } @Issue("JENKINS-49707") @Test public void terminatedPod() throws Exception { r.waitForMessage("+ sleep", b); deletePods(cloud.connect(), getLabels(this, name), false); r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b)); r.waitForMessage(new ExecutorStepExecution.RemovedNodeCause().getShortDescription(), b); } @Issue("JENKINS-58306") @Test public void cascadingDelete() throws Exception { try { cloud.connect().apps().deployments().withName("cascading-delete").delete(); } catch (KubernetesClientException x) { assumeNoException("was not permitted to clean up any previous deployment, so presumably cannot run test either", x); } cloud.connect().apps().replicaSets().withLabel("app", "cascading-delete").delete(); cloud.connect().pods().withLabel("app", "cascading-delete").delete(); r.assertBuildStatusSuccess(r.waitForCompletion(b)); } @Test public void computerCantBeConfigured() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.ADMINISTER).everywhere().to("admin")); SemaphoreStep.waitForStart("pod/1", b); Optional<KubernetesSlave> optionalNode = r.jenkins.getNodes().stream().filter(KubernetesSlave.class::isInstance).map(KubernetesSlave.class::cast).findAny(); assertTrue(optionalNode.isPresent()); KubernetesSlave node = optionalNode.get(); JenkinsRule.WebClient wc = r.createWebClient().login("admin"); wc.getOptions().setPrintContentOnFailingStatusCode(false); HtmlPage nodeIndex = wc.getPage(node);
package org.wyona.yanel.servlet.security.impl; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.servlet.YanelServlet; import org.wyona.yanel.core.api.security.WebAuthenticator; import org.wyona.security.core.api.AccessManagementException; import org.wyona.security.core.ExpiredIdentityException; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.User; import org.wyona.security.core.api.UserManager; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import java.net.URL; import org.w3c.dom.Element; import org.apache.log4j.Logger; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; // JOID is an alternative openid impl /* import org.verisign.joid.consumer.OpenIdFilter; import org.verisign.joid.util.UrlUtils; */ import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.discovery.Discovery; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.message.AuthRequest; import org.openid4java.message.ParameterList; public class DefaultWebAuthenticatorImpl implements WebAuthenticator { private static Logger log = Logger.getLogger(DefaultWebAuthenticatorImpl.class); private static String OPENID_DISCOVERED_KEY = "openid-discovered"; private static String LOGIN_DEFAULT_COOKIE_NAME = "_yanel-login-default"; private static String LOGIN_OPENID_COOKIE_NAME = "_yanel-login-openid"; private static final String LOGIN_USER_REQUEST_PARAM_NAME = "yanel.login.username"; // NOTE: The OpenID consumer manager needs to be the same instance for redirect to provider and provider verification private ConsumerManager manager; private boolean allowOpenIdUserCreation; /** * @see org.wyona.yanel.core.api.security.WebAuthenticator#init(Document, URIResolver) */ public void init(org.w3c.dom.Document configuration, javax.xml.transform.URIResolver resolver) throws Exception { // TODO: commented because there is a problem with this line //manager = new ConsumerManager(); // TODO: Make this configurable in order to prevent OpenID user creation attack allowOpenIdUserCreation = true; } /** * @see org.wyona.yanel.core.api.security.WebAuthenticator#doAuthenticate(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.wyona.yanel.core.map.Map, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws ServletException, IOException { try { Realm realm = map.getRealm(request.getServletPath()); String path = map.getPath(realm, request.getServletPath()); //Realm realm = map.getRealm(new Path(request.getServletPath())); if (log.isDebugEnabled()) log.debug("Generic WebAuthenticator called for realm path " + path); HttpSession session = request.getSession(true); // HTML Form based authentication String loginUsername = request.getParameter(LOGIN_USER_REQUEST_PARAM_NAME); String openID = request.getParameter("yanel.login.openid"); String openIDSignature = request.getParameter("openid.sig"); if (loginUsername != null || openID != null) { doRememberMyLoginName(request, response, loginUsername, openID); //boolean rememberMyLoginName = doRememberMyLoginName(request, response, loginUsername, openID); } if(loginUsername != null) { try { String loginPassword = request.getParameter("yanel.login.password"); if (loginPassword != null && authenticateUser(loginUsername, loginPassword, realm, session)) { log.debug("Login of user '" + loginUsername + "' was successful"); doAutoLogin(request, response, loginUsername, openID, realm); return null; } if (loginPassword == null) { log.warn("No password specified yet!"); getXHTMLAuthenticationForm(request, response, realm, "Please make sure to enter password!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); } else { log.warn("Login failed: " + loginUsername + " (True ID: " + realm.getIdentityManager().getUserManager().getTrueId(loginUsername) + ")"); getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); } return response; } catch (ExpiredIdentityException e) { log.warn("Login failed: [" + loginUsername + "] " + e); getXHTMLAuthenticationForm(request, response, realm, "The account has expired!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); return response; } catch (AccessManagementException e) { log.warn("Login failed: [" + loginUsername + "] " + e); getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); return response; } } else if (openID != null) { // Append http scheme if missing if (!openID.startsWith("http: openID = "http://" + openID; } String redirectUrlString = null; try { redirectUrlString = getOpenIDRedirectURL(openID, request, map); response.sendRedirect(redirectUrlString); } catch (Exception e) { log.error(e, e); getXHTMLAuthenticationForm(request, response, realm, "Login failed: " + e.getMessage() + "!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); } log.debug("Redirect URL: " + redirectUrlString); return response; } else if (openIDSignature != null) { log.debug("Verify OpenID provider response ..."); if (verifyOpenIDProviderResponse(request, map)) { UserManager uManager = realm.getIdentityManager().getUserManager(); String openIdentity = request.getParameter("openid.identity"); if (openIdentity != null) { if (!uManager.existsUser(openIdentity) && allowOpenIdUserCreation) { uManager.createUser(openIdentity, null, null, null); log.warn("An OpenID user has been created: " + openIdentity); } User user = uManager.getUser(openIdentity); //User user = uManager.getUser(openIdentity, true); YanelServlet.setIdentity(new Identity(user, openIDSignature), session, realm); // OpenID authentication successful, hence return null instead an "exceptional" response // TODO: Do not return null (although successful), but rather strip-off all the openid query string stuff and then do a redirect response.sendRedirect(request.getParameter("openid.return_to")); return response; } log.error("No openid.identity!"); getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but no openid.identity!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); } else { getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); } return response; } else { if (log.isDebugEnabled()) log.debug("No form based authentication request."); } // Check for Neutron-Auth based authentication String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) { log.debug("Neutron Authentication ..."); return handleNeutronAuthAuthenticationRequest(request, response, map, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort); } if (log.isDebugEnabled()) log.debug("No Neutron based authentication request."); return getUnauthenticatedResponse(request, response, map, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } /** * Do Neutron authentication */ private static HttpServletResponse handleNeutronAuthAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws Exception { Realm realm = map.getRealm(request.getServletPath()); HttpSession session = request.getSession(true); String username = null; String password = null; String originalRequest = null; DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); try { Configuration config = builder.build(request.getInputStream()); Configuration originalRequestConfig = config.getChild("original-request"); originalRequest = originalRequestConfig.getAttribute("url", null); Configuration[] paramConfig = config.getChildren("param"); for (int i = 0; i < paramConfig.length; i++) { String paramName = paramConfig[i].getAttribute("name", null); if (paramName != null) { if (paramName.equals("username")) { username = paramConfig[i].getValue(); } else if (paramName.equals("password")) { password = paramConfig[i].getValue(); } } } } catch(Exception e) { log.warn(e); } log.debug("Username: " + username); if (username != null) { log.debug("Realm ID: " + realm.getID()); User user = realm.getIdentityManager().getUserManager().getUser(username, true); if (user != null && user.authenticate(password)) { log.info("Authentication successful: " + username); YanelServlet.setIdentity(new Identity(user, username), session, realm); // TODO: send some XML content, e.g. <authentication-successful/> response.setContentType("text/plain; charset=" + YanelServlet.DEFAULT_ENCODING); response.setStatus(HttpServletResponse.SC_OK); if (log.isDebugEnabled()) log.debug("Neutron Authentication successful."); PrintWriter writer = response.getWriter(); writer.print("Neutron Authentication Successful!"); return response; } log.warn("Neutron Authentication failed: " + username); // TODO: Refactor this code with the one from doAuthenticate ... log.debug("Original Request: " + originalRequest); // TODO: Use org.wyona.neutron.XMLExceptionV1.getAuthenticationException(...) StringBuilder sb = new StringBuilder(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); return response; } // TODO: Refactor resp. reuse response from above ... log.warn("Neutron Authentication failed because username is NULL!"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed because no username was sent!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter writer = response.getWriter(); writer.print(sb); return response; } private static boolean challengeUsingNeutronAuth(HttpServletRequest request, HttpServletResponse response, Realm realm, String sslPort) throws Exception { String neutronVersions = request.getHeader("Neutron"); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { log.debug("Neutron Versions supported by client: " + neutronVersions); log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme); // TODO: Use org.wyona.neutron.XMLExceptionV1.getAuthorizationException(...) StringBuilder sb = new StringBuilder(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authorization denied: " + getRequestPatchedURL(request, null, true, realm) + "</message>"); sb.append("<authentication>"); sb.append("<original-request url=\"" + getRequestPatchedURL(request, null, true, realm) + "\"/>"); //TODO: Also support https ... sb.append("<login url=\"" + getRequestPatchedURL(request, "yanel.usecase=neutron-auth", true, realm) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... sb.append("<logout url=\"" + getRequestPatchedURL(request, "yanel.usecase=logout", true, realm) + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "NEUTRON-AUTH"); PrintWriter w = response.getWriter(); w.print(sb); return true; } return false; } private HttpServletResponse getUnauthenticatedResponse(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws Exception { Realm realm = map.getRealm(request.getServletPath()); log.warn("No credentials specified yet!"); // Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request if (challengeUsingNeutronAuth(request, response, realm, sslPort)) { } else if (request.getRequestURI().endsWith(".ics")) { log.warn("Somebody seems to ask for a Calendar (ICS) ..."); response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { getXHTMLAuthenticationForm(request, response, realm, null, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map); } return response; /* if (log.isDebugEnabled()) log.debug("TODO: Was this authentication request really necessary!"); return null; */ } /** * Custom XHTML Form for authentication * @param xsltLoginScreenDefault Path of default XSLT */ public void getXHTMLAuthenticationForm(HttpServletRequest request, HttpServletResponse response, Realm realm, String message, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort, Map map) throws ServletException, IOException { // TODO: Enhance with global resource, which will make it more flexible if(log.isDebugEnabled()) log.debug("Default authentication form implementation!"); try { org.w3c.dom.Document adoc = generateAuthenticationScreenXML(request, realm, message, sslPort, map); String yanelFormat = request.getParameter("yanel.login.format"); if(yanelFormat != null && yanelFormat.equals("xml")) { response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING); //OutputStream out = response.getOutputStream(); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getOutputStream())); //out.close(); } else { //String mimeType = YanelServlet.patchMimeType("text/html", request); String mimeType = YanelServlet.patchMimeType("application/xhtml+xml", request); response.setContentType(mimeType + "; charset=" + YanelServlet.DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); File realmDir = realm.getRootDir(); if (realmDir == null) realmDir = new File(realm.getConfigFile().getParent()); File xsltLoginScreen = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + xsltLoginScreenDefault); if (!xsltLoginScreen.isFile()) xsltLoginScreen = org.wyona.commons.io.FileUtil.file(servletContextRealPath, xsltLoginScreenDefault); Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltLoginScreen)); String pathRelativeToRealm = request.getServletPath().replaceFirst(realm.getMountPoint(),"/"); // INFO: For example "/en/index.html" //log.debug("Path relative to realm: " + pathRelativeToRealm); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(pathRelativeToRealm); transformer.setParameter("yanel.back2realm", backToRealm); transformer.setParameter("yanel.reservedPrefix", reservedPrefix); //transformer.setParameter("language", "TODO"); // INFO: resource.getRequestedLanguage() String twoLetterLangCode = getContentLanguage(pathRelativeToRealm); if (twoLetterLangCode != null) { transformer.setParameter("content-language", twoLetterLangCode); // INFO: resource.getContentLanguage() } transformer.transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getWriter())); // TODO: i18n } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } /** * Patch request with proxy settings re realm configuration */ private static String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml, Map map) { try { Realm realm = map.getRealm(request.getServletPath()); // TODO: Handle this exception more gracefully! if (realm == null) log.error("No realm found for path " +request.getServletPath()); return getRequestPatchedURL(request, addQS, xml, realm); } catch (Exception e) { log.error(e); return null; } } /** * XXX REFACTORME: Once the proxy settings exist independently from the Realm API, we should * extract this method and use a "proxy settings object" as parameter instead of a Realm. */ private static String getRequestPatchedURL(HttpServletRequest request, String addQS, boolean xml, Realm realm) { String proxyHostName = realm.getProxyHostName(); int proxyPort = realm.getProxyPort(); String proxyPrefix = realm.getProxyPrefix(); boolean isProxySet = realm.isProxySet(); try { URL url = null; url = new URL(request.getRequestURL().toString()); //if(proxyHostName != null || proxyPort >= null || proxyPrefix != null) { if(isProxySet) { if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } if (proxyPort >= 0) { url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } //log.debug("Proxy enabled for this realm resp. request: " + realm + ", " + url); } else { //log.debug("No proxy set for this realm resp. request: " + realm + ", " + url); } String urlQS = url.toString(); if (request.getQueryString() != null) { urlQS = urlQS + "?" + request.getQueryString(); if (addQS != null) urlQS = urlQS + "&" + addQS; } else { if (addQS != null) urlQS = urlQS + "?" + addQS; } if (xml) urlQS = urlQS.replaceAll("&", "&amp;"); if(log.isDebugEnabled()) log.debug("Request: " + urlQS); return urlQS; } catch (Exception e) { log.error(e); return null; } } // Using openid4java library private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception { String returnToUrlString = getRequestURLQS(request, null, false, map); Identifier identifier = Discovery.parseIdentifier(openID); java.util.List discoveries = new Discovery().discover(identifier); DiscoveryInformation discovered = null; try { discovered = manager.associate(discoveries); } catch(Exception e) { log.warn(e, e); } if (discovered == null) { throw new Exception("OpenID DiscoverInfo is null"); } request.getSession(true).setAttribute(OPENID_DISCOVERED_KEY, discovered); AuthRequest authReq = manager.authenticate(discovered, returnToUrlString); return authReq.getDestinationUrl(true); } // Using JOID library /* private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception { String returnToUrlString = UrlUtils.getFullUrl(request); log.debug("After successful authentication return to: " + returnToUrlString); String redirectUrlString = OpenIdFilter.joid().getAuthUrl(openID, returnToUrlString, returnToUrlString); log.debug("OpenID Provider URL: " + redirectUrlString); return redirectUrlString; } */ /** * Verify OpenID provider response */ private boolean verifyOpenIDProviderResponse (HttpServletRequest request, Map map) throws Exception { ParameterList responseParas = new ParameterList(request.getParameterMap()); DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(OPENID_DISCOVERED_KEY); String receivingURL = getRequestURLQS(request, null, false, map); log.debug("Receiving URL: " + receivingURL); VerificationResult verification = manager.verify(receivingURL.toString(), responseParas, discovered); Identifier verified = verification.getVerifiedId(); if (verified != null) { /* AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse(); if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX); List emails = fetchResp.getAttributeValues("email"); String email = (String) emails.get(0); } */ return true; } return false; } /** * Handle "auto login" */ private static boolean doAutoLogin(HttpServletRequest request, HttpServletResponse response, String loginUsername, String openID, Realm realm) throws Exception { if (request.getParameter("auto-login") != null) { AutoLogin.enableAutoLogin(loginUsername, request, response, realm); return true; } else { log.debug("Ignore auto login..."); return false; } } /** * Handle "remember my login" */ private static boolean doRememberMyLoginName(HttpServletRequest request, HttpServletResponse response, String loginUsername, String openID) { boolean rememberMyLoginName = false; if (request.getParameter("remember-my-login-name") != null) { log.debug("Remember my login name: " + loginUsername + "," + openID); rememberMyLoginName = true; Cookie rememberLoginNameCookie = null; // TODO: Add realm as additional information if (loginUsername != null) { rememberLoginNameCookie = new Cookie(LOGIN_DEFAULT_COOKIE_NAME, loginUsername); } else if (openID != null) { rememberLoginNameCookie = new Cookie(LOGIN_OPENID_COOKIE_NAME, openID); } else { log.warn("Neither default nor OpenID login!"); } if (rememberLoginNameCookie != null) { rememberLoginNameCookie.setPath(request.getContextPath()); rememberLoginNameCookie.setMaxAge(86400); // 1 day is 86400 seconds response.addCookie(rememberLoginNameCookie); } } else { log.debug("Do NOT remember my login name: " + loginUsername + "," + openID); rememberMyLoginName = false; // Unset Login Cookies (http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/Cookie.html#setMaxAge(int)) Cookie rememberLoginDefaultCookie = new Cookie(LOGIN_DEFAULT_COOKIE_NAME, ""); rememberLoginDefaultCookie.setMaxAge(0); // Expire it immediately response.addCookie(rememberLoginDefaultCookie); Cookie rememberLoginOpenIDCookie = new Cookie(LOGIN_OPENID_COOKIE_NAME, ""); rememberLoginOpenIDCookie.setMaxAge(0); // Expire it immediately response.addCookie(rememberLoginOpenIDCookie); } return rememberMyLoginName; } /** * Default authentication. Overwrite this method in order to implement a custom user authentication. * * @param username Login username, which might be an alias * @param password Plain text password * @param realm Realm * @param session HTTP session * * @return true if authentication was successful and else false */ protected boolean authenticateUser(String username, String password, Realm realm, HttpSession session) throws Exception { return authenticate(username, password, realm, session); } /** * Default authentication. WARN: This method is used by realms/konakart-yanel-realm/res-types/shared/src/java/org/wyona/yanel/resources/konakart/shared/SharedResource.java, whereas it was probably a mistake to make this method public! Do not use it, but rather implement a custom web authenticator. * * @param username Login username, which might be an alias * @param password Plain text password * @param realm Realm * @param session HTTP session * * @return true if authentication was successful and else false */ public static boolean authenticate(String username, String password, Realm realm, HttpSession session) throws Exception { String trueId = realm.getIdentityManager().getUserManager().getTrueId(username); User user = realm.getIdentityManager().getUserManager().getUser(trueId, true); if (user != null && user.authenticate(password)) { log.debug("Realm: " + realm); YanelServlet.setIdentity(new Identity(user, username), session, realm); log.warn("Authentication was successful for user: " + user.getID()); log.warn("TODO: Add user to session listener!"); return true; } else { log.warn("Authentication failed for user: " + username + " (Realm: " + realm.getName() + ")"); } return false; } /** * Generate XML of authentication/login screen * @param request * @param realm * @param message Error message, e.g. "Login failed" * @param sslPort * @param map */ protected org.w3c.dom.Document generateAuthenticationScreenXML(HttpServletRequest request, Realm realm, String message, String sslPort, Map map) throws Exception { log.debug("Generate authentication screen XML..."); org.w3c.dom.Document adoc = YanelServlet.getDocument(YanelServlet.NAMESPACE, "yanel-auth-screen"); Element rootElement = adoc.getDocumentElement(); if (message != null) { Element messageElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "message")); messageElement.appendChild(adoc.createTextNode(message)); } Element requestElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "request")); requestElement.setAttributeNS(YanelServlet.NAMESPACE, "urlqs", getRequestURLQS(request, null, true, map)); if (request.getQueryString() != null) { requestElement.setAttributeNS(YanelServlet.NAMESPACE, "qs", request.getQueryString().replaceAll("&", "&amp;")); } Element realmElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "realm")); realmElement.setAttributeNS(YanelServlet.NAMESPACE, "name", realm.getName()); realmElement.setAttributeNS(YanelServlet.NAMESPACE, "mount-point", realm.getMountPoint().toString()); String currentUserId = null; Identity identity = YanelServlet.getIdentity(request.getSession(true), realm); if (identity != null) { currentUserId = identity.getUsername(); } //String currentUserId = getCurrentUserId(request.getSession(true), realm); if (currentUserId != null) { Element userElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "user")); userElement.setAttributeNS(YanelServlet.NAMESPACE, "id", currentUserId); } Element sslElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "ssl")); if(sslPort != null) { sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "ON"); } else { sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "OFF"); } Cookie[] cookies = request.getCookies(); if (cookies != null) { // INFO: Check cookies if login name was set to be remembered for (int i = 0; i < cookies.length; i++) { log.debug("Cookie: " + cookies[i].getName() + ", " + cookies[i].getValue()); // TODO: Parse realm and login name (see method doRememberMyLoginName()) if (cookies[i].getName().equals(LOGIN_DEFAULT_COOKIE_NAME)) { Element loginDefaultElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "login-default")); loginDefaultElement.setAttributeNS(YanelServlet.NAMESPACE, "username", cookies[i].getValue()); } else if (cookies[i].getName().equals(LOGIN_OPENID_COOKIE_NAME)) { Element loginOpenIDElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "login-openid")); loginOpenIDElement.setAttributeNS(YanelServlet.NAMESPACE, "openid", cookies[i].getValue()); } } } String loginUsername = request.getParameter(LOGIN_USER_REQUEST_PARAM_NAME); // INFO: Check request parameter for login name if (loginUsername != null) { Element presetLoginElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "login-preset")); presetLoginElement.setAttributeNS(YanelServlet.NAMESPACE, "username", loginUsername); } return adoc; } /** * Get content language from path * @param path Path such as for example "/en/index.html" * @return two-letter language code, e.g. "en" */ private String getContentLanguage(String path) { if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(3) == '/') { return path.substring(1,3); } else { log.warn("No two-letter language code detected inside: " + path); return null; } } }
package com.vangent.hieos.services.xds.registry.transactions; import com.vangent.hieos.xutil.atna.XATNALogger; import com.vangent.hieos.xutil.metadata.structure.MetadataTypes; import com.vangent.hieos.adt.verify.Verify; import com.vangent.hieos.services.xds.registry.storedquery.RegistryObjectValidator; import com.vangent.hieos.xutil.exception.MetadataException; import com.vangent.hieos.xutil.exception.MetadataValidationException; import com.vangent.hieos.xutil.exception.SchemaValidationException; import com.vangent.hieos.xutil.exception.XdsDeprecatedException; import com.vangent.hieos.xutil.exception.XdsException; import com.vangent.hieos.xutil.exception.XdsFormatException; import com.vangent.hieos.xutil.exception.XdsInternalException; import com.vangent.hieos.xutil.exception.XdsPatientIdDoesNotMatchException; import com.vangent.hieos.xutil.exception.XdsUnknownPatientIdException; import com.vangent.hieos.services.xds.registry.backend.BackendRegistry; import com.vangent.hieos.xutil.metadata.structure.IdParser; import com.vangent.hieos.xutil.metadata.structure.Metadata; import com.vangent.hieos.xutil.metadata.structure.MetadataParser; import com.vangent.hieos.xutil.metadata.structure.MetadataSupport; import com.vangent.hieos.xutil.response.RegistryResponse; import com.vangent.hieos.xutil.registry.RegistryUtility; import com.vangent.hieos.xutil.services.framework.XBaseTransaction; import com.vangent.hieos.xutil.metadata.validation.Validator; import com.vangent.hieos.services.xds.registry.storedquery.SQFactory; import com.vangent.hieos.xutil.response.RegistryErrorList; import com.vangent.hieos.xutil.xlog.client.XLogMessage; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import com.vangent.hieos.xutil.xconfig.XConfigActor; import com.vangent.hieos.xutil.xml.Util; import java.util.List; import javax.xml.transform.TransformerConfigurationException; import org.apache.axiom.om.OMElement; import org.apache.axis2.context.MessageContext; import org.apache.log4j.Logger; /** * * @author NIST, Bernie Thuman (overall cleanup). */ public class SubmitObjectsRequest extends XBaseTransaction { //Message context was added when trying to send audit message MessageContext messageContext; boolean submit_raw = false; private final static Logger logger = Logger.getLogger(SubmitObjectsRequest.class); /** * * @param logMessage * @param messageContext */ public SubmitObjectsRequest(XLogMessage logMessage, MessageContext messageContext) { this.log_message = logMessage; this.messageContext = messageContext; try { init(new RegistryResponse(), messageContext); } catch (XdsInternalException e) { logger.fatal(logger_exception_details(e)); } } /** * * @param sor * @param validater * @return */ public OMElement run(OMElement sor) { try { sor.build(); //AUDIT:POINT //call to audit message for document registry //for Transaction id = ITI-42. (Register Document set-b) // NOTE!!: Moved above "SubjectObjectsRequestInternal()" method call since the "sor" instance // is changed during the execution of "SubjectObjectsRequestInternal() method. Otherwise, // we would need to pay the penalty for a deep copy of the "sor" instance. performAudit( XATNALogger.TXN_ITI42, sor, null, XATNALogger.ActorType.REGISTRY, XATNALogger.OutcomeIndicator.SUCCESS); SubmitObjectsRequestInternal(sor); } catch (XdsFormatException e) { response.add_error(MetadataSupport.XDSRegistryError, "SOAP Format Error: " + e.getMessage(), this.getClass().getName(), log_message); } catch (XdsDeprecatedException e) { response.add_error("XDSRegistryDeprecatedDocumentError", "XDS Deprecated Document Error:\n " + e.getMessage(), this.getClass().getName(), log_message); logger.warn(logger_exception_details(e)); } catch (XdsUnknownPatientIdException e) { response.add_error(MetadataSupport.XDSUnknownPatientId, "XDS Unknown Patient Id:\n " + e.getMessage(), this.getClass().getName(), log_message); logger.warn(logger_exception_details(e)); } catch (XdsPatientIdDoesNotMatchException e) { response.add_error(MetadataSupport.XDSPatientIdDoesNotMatch, "Patient ID does not match:\n " + e.getMessage(), this.getClass().getName(), log_message); logger.warn(logger_exception_details(e)); } catch (XdsInternalException e) { response.add_error(MetadataSupport.XDSRegistryError, "XDS Internal Error:\n " + e.getMessage(), this.getClass().getName(), log_message); logger.fatal(logger_exception_details(e)); } catch (MetadataValidationException e) { response.add_error(MetadataSupport.XDSRegistryMetadataError, "Metadata Validation Errors:\n " + e.getMessage(), this.getClass().getName(), log_message); } catch (SchemaValidationException e) { response.add_error(MetadataSupport.XDSRegistryMetadataError, "Schema Validation Errors:\n" + e.getMessage(), this.getClass().getName(), log_message); } catch (XdsException e) { response.add_error(MetadataSupport.XDSRegistryError, "Exception:\n " + e.getMessage(), this.getClass().getName(), log_message); logger.warn(logger_exception_details(e)); } catch (TransformerConfigurationException e) { response.add_error(MetadataSupport.XDSRegistryError, "Internal Error: Transformer Configuration Error: " + e.getMessage(), this.getClass().getName(), log_message); logger.fatal(logger_exception_details(e)); } catch (SQLException e) { response.add_error(MetadataSupport.XDSRegistryError, "Internal Logging error: SQLException: " + e.getMessage(), this.getClass().getName(), log_message); logger.fatal(logger_exception_details(e)); } catch (Exception e) { response.add_error(MetadataSupport.XDSRegistryError, "XDS General Error:\n " + e.getMessage(), this.getClass().getName(), log_message); logger.fatal(logger_exception_details(e)); } //this.log_response(); OMElement res = null; try { res = response.getResponse(); this.log_response(); } catch (XdsInternalException e) { } return res; } /** * * @param sor * @throws SQLException * @throws SchemaValidationException * @throws MetadataValidationException * @throws XdsInternalException * @throws TransformerConfigurationException * @throws MetadataValidationException * @throws XdsException */ void SubmitObjectsRequestInternal(OMElement sor) throws SQLException, SchemaValidationException, MetadataValidationException, XdsInternalException, TransformerConfigurationException, MetadataValidationException, XdsException { boolean status; // First, make sure that the "SubmitObjectRequest" is valid against the XDS.b schema: RegistryUtility.schema_validate_local(sor, MetadataTypes.METADATA_TYPE_Rb); try { Metadata m = new Metadata(sor); // Create meta-data instance for SOR. this.logMetadata(m); // Validate that the SOR is internally consistent: Validator val = new Validator(m, response.registryErrorList, true, log_message); val.run(); // VALIDATION STEP: // Make sure that object ids submitted do not already exist (see RegistryObjectValidator // for additional rules). RegistryObjectValidator rov = new RegistryObjectValidator(response, log_message); rov.validateProperUids(m); if (response.has_errors()) { logger.error("metadata validator failed"); } // Get out early if the validation process failed: if (response.has_errors()) { return; // EARLY EXIT! } // VALIDATION STEP: // Get the patient id associated with the request and validate that it is known // to the registry. String patientId = m.getSubmissionSetPatientId(); log_message.addOtherParam("Patient ID", patientId); this.validatePatientId(patientId); // Check for references to registry contents List<String> referencedObjects = m.getReferencedObjects(); if (referencedObjects.size() > 0) { // Make sure that referenced objects are "APPROVED": List<String> missing = rov.validateApproved(referencedObjects); if (missing != null) { throw new XdsDeprecatedException("The following registry objects were referenced by this submission but are not present, as Approved documents, in the registry: " + missing); } // Make allowance for by reference inclusion missing = rov.validateSamePatientId(m.getReferencedObjectsThatMustHaveSamePatientId(), patientId); if (missing != null) { throw new XdsPatientIdDoesNotMatchException("The following registry objects were referenced by this submission but do not reference the same patient ID: " + missing); } } // Allocate uuids for symbolic ids IdParser idParser = new IdParser(m); idParser.compileSymbolicNamesIntoUuids(); // Check that submission does not include any object ids that are already in registry /* DISABLED - In general, we should be OK here given prior checks. Also, the underlying registry does * allow updates to occur based on prior submissions. * List<String> idsInSubmission = m.getAllDefinedIds(); List<String> idsAlreadyInRegistry = rov.validateNotExists(idsInSubmission); if (idsAlreadyInRegistry.size() != 0) { response.add_error(MetadataSupport.XDSRegistryMetadataError, "The following UUIDs which are present in the submission are already present in registry: " + idsAlreadyInRegistry, this.getClass().getName(), log_message); } */ // Update any folders "lastUpdateTime" slot with the current time: m.updateFoldersLastUpdateTimeSlot(); // If this submission includes a DocumentEntry replace and the original DocumentEntry is in a folder // then the replacement document must be put into the folder as well. This must happen here // so the following logic to update folder lastUpdateTime can be triggered. HashMap<String, String> rplcToOrigIds = new HashMap<String, String>(); for (OMElement assoc : m.getAssociations()) { if (MetadataSupport.xdsB_ihe_assoc_type_rplc.equals(m.getAssocType(assoc))) { rplcToOrigIds.put(m.getAssocSource(assoc), m.getAssocTarget(assoc)); } } for (String replacementDocumentId : rplcToOrigIds.keySet()) { String originalDocumentId = rplcToOrigIds.get(replacementDocumentId); // for each original document, find the collection of folders it belongs to Metadata me = new SQFactory(this, false).findFoldersForDocumentByUuid(originalDocumentId); ArrayList<String> folderIds = me.getObjectIds(me.getObjectRefs()); // for each folder, add an association placing replacment in that folder // This brings up interesting question, should the Assoc between SS and Assoc be generated also? YES! for (String fid : folderIds) { OMElement assoc = m.addAssociation(m.makeAssociation(MetadataSupport.xdsB_eb_assoc_type_has_member, fid, replacementDocumentId)); OMElement assoc2 = m.addAssociation(m.makeAssociation(MetadataSupport.xdsB_eb_assoc_type_has_member, m.getSubmissionSetId(), assoc.getAttributeValue(MetadataSupport.id_qname))); } } BackendRegistry backendRegistry = new BackendRegistry(response, log_message); // if this submission adds a document to a folder then update that folder's lastUpdateTime Slot for (OMElement assoc : m.getAssociations()) { if (MetadataSupport.xdsB_eb_assoc_type_has_member.equals(m.getAssocType(assoc))) { String sourceId = m.getAssocSource(assoc); if (!m.getSubmissionSetId().equals(sourceId) && !m.getFolderIds().contains(sourceId)) { // Assoc src not part of the submission logger.info("Adding to Folder (1)" + sourceId); if (this.isFolder(sourceId)) { logger.info("Adding to Folder (2)" + sourceId); OMElement res = backendRegistry.basicQuery("SELECT * from RegistryPackage rp WHERE rp.id='" + sourceId + "'", true /* leafClass */); // Update any folders "lastUpdateTime" slot: Metadata fm = MetadataParser.parseNonSubmission(res); fm.updateFoldersLastUpdateTimeSlot(); OMElement to_backend = fm.getV3SubmitObjectsRequest(); log_message.addOtherParam("From Registry Adaptor", to_backend); status = submitToBackendRegistry(backendRegistry, to_backend); if (!status) { return; } } } } } // Finally, make the actual submission: OMElement request = m.getV3SubmitObjectsRequest(); log_message.addOtherParam("From Registry Adaptor", request); status = submitToBackendRegistry(backendRegistry, request); if (!status) { return; } // Approve ArrayList approvableObjectIds = m.getApprovableObjectIds(); if (approvableObjectIds.size() > 0) { this.submitApproveObjectsRequest(backendRegistry, approvableObjectIds); } // Deprecate ArrayList<String> deprecatableObjectIds = m.getDeprecatableObjectIds(); // add to the list of things to deprecate, any XFRM or APND documents hanging off documents // in the deprecatable_object_ids list List<String> XFRMandAPNDDocuments = rov.getXFRMandAPNDDocuments(deprecatableObjectIds); deprecatableObjectIds.addAll(XFRMandAPNDDocuments); if (deprecatableObjectIds.size() > 0) { // validate that these are documents first List<String> missing = rov.validateDocuments(deprecatableObjectIds); if (missing != null) { throw new XdsException("The following documents were referenced by this submission but are not present in the registry: " + missing); } this.submitDeprecateObjectsRequest(backendRegistry, deprecatableObjectIds); } //this.log_response(); } catch (MetadataException e) { response.add_error(MetadataSupport.XDSRegistryError, e.getMessage(), this.getClass().getName(), log_message); return; } } /** * * @param backendRegistry * @param objectIds * @throws XdsException */ private void submitApproveObjectsRequest(BackendRegistry backendRegistry, ArrayList objectIds) throws XdsException { OMElement approveObjectsRequest = backendRegistry.getApproveObjectsRequest(objectIds); log_message.addOtherParam("Approve", approveObjectsRequest); submitToBackendRegistry(backendRegistry, approveObjectsRequest); } /** * * @param backendRegistry * @param objectIds * @throws XdsException */ private void submitDeprecateObjectsRequest(BackendRegistry backendRegistry, ArrayList<String> objectIds) throws XdsException { OMElement deprecateObjectsRequest = backendRegistry.getDeprecateObjectsRequest(objectIds); log_message.addOtherParam("Deprecate", deprecateObjectsRequest); submitToBackendRegistry(backendRegistry, deprecateObjectsRequest); } /** * * @param patientId * @throws java.sql.SQLException * @throws com.vangent.hieos.xutil.exception.XdsException * @throws com.vangent.hieos.xutil.exception.XdsInternalException */ private void validatePatientId(String patientId) throws SQLException, XdsException, XdsInternalException { //if (Properties.loader().getBoolean("validate_patient_id")) { XConfigActor registryConfig = this.getConfigActor(); String validatePatientIdAsString = registryConfig.getProperty("validatePatientId"); boolean validatePatientId = true; if (validatePatientIdAsString != null) { validatePatientId = registryConfig.getPropertyAsBoolean("validatePatientId"); } if (validatePatientId) { Verify v = new Verify(); boolean isValidPatientId = v.isValid(patientId); if (!isValidPatientId) { throw new XdsUnknownPatientIdException("PatientId " + patientId + " is not known to the Registry"); } } } //AMS 04/29/2009 - FIXME invoked by XdsRaw. REMOVE at some point. /** * * @param val */ public void setSubmitRaw(boolean val) { submit_raw = val; } /** * * @param id * @return * @throws XdsException */ public boolean isFolder(String id) throws XdsException { //if (m.getFolderIds().contains(id)) { // return true; if (!id.startsWith("urn:uuid:")) { return false; } RegistryErrorList rel = new RegistryErrorList(false /* log */); RegistryObjectValidator rov = new RegistryObjectValidator(rel, log_message); ArrayList<String> ids = new ArrayList<String>(); ids.add(id); List<String> missing = rov.validateAreFolders(ids); if (missing != null && missing.contains(id)) { return false; } return true; } /* AMS 04/21/2009 - Added new method. */ /** * * @param br * @param omElement * @return * @throws XdsException */ private boolean submitToBackendRegistry(BackendRegistry br, OMElement omElement) throws XdsException { OMElement result = br.submit(omElement); return getResult(result);// Method should be renamed to getRegistrySubmissionStatus ... } /** * * @param m * @throws MetadataException */ private void logMetadata(Metadata m) throws MetadataException { // Log relevant data (if logger is turned on of course). if (log_message.isLogEnabled() == true) { log_message.addOtherParam("SSuid", m.getSubmissionSetUniqueId()); ArrayList<String> doc_uids = new ArrayList<String>(); for (String id : m.getExtrinsicObjectIds()) { String uid = m.getUniqueIdValue(id); if (uid != null && !uid.equals("")) { doc_uids.add(uid); } } log_message.addOtherParam("DOCuids", doc_uids); ArrayList<String> fol_uids = new ArrayList<String>(); for (String id : m.getFolderIds()) { String uid = m.getUniqueIdValue(id); if (uid != null && !uid.equals("")) { fol_uids.add(uid); } } log_message.addOtherParam("FOLuids", fol_uids); log_message.addOtherParam("Structure", m.structure()); } } /** * * @param result * @return */ private boolean getResult(OMElement result) { if (result == null) { return false; } String value = result.getAttributeValue(MetadataSupport.status_qname); if (value == null) { return false; } if (value.indexOf(":") == -1) { return false; } String[] parts = value.split(":"); if ("Success".equals(parts[parts.length - 1])) { return true; } else { return false; } } }
package edu.pitt.dbmi.deepphe.summarization.jess; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeSet; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import jess.JessException; import jess.Rete; import edu.pitt.dbmi.deepphe.i2b2.I2B2DataDataWriter; import edu.pitt.dbmi.deepphe.i2b2.PartialPath; import edu.pitt.dbmi.deepphe.summarization.jess.kb.Patient; import edu.pitt.dbmi.deepphe.summarization.ontology.OntologyCleaner; import edu.pitt.dbmi.deepphe.summarization.orm.i2b2data.I2b2DataDataSourceManager; public class SummarizationGui extends JFrame implements ActionListener, PropertyChangeListener { public static String PROJECT_LOCATION = "/home/tseytlin/Work/DeepPhe/"; private static final long serialVersionUID = 1L; public static void main(String[] args) { if(args.length > 0) PROJECT_LOCATION = args[0]; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { new SummarizationGui("DeepPhe Summarization"); } private final TreeSet<PartialPath> partialPathTreeSet = new TreeSet<PartialPath>(); private final HashMap<String, PartialPath> partialPathMap = new HashMap<>(); private final Rete engine = new Rete(); private final PatientKnowledgeExtractor patientKnowledgeExtractor = new JessPatientKnowledgeExtractor(); private final JessTextInputer jessInputer = new JessTextInputer(); private final JessTextOutputer jessOutputer = new JessTextOutputer(); private final PatientListReader patientListReader = new PatientListReader(); private final List<Patient> patients = new ArrayList<>(); private WindowAdapter windowAdapter; private JPanel mainPanel; private ImageIcon iconOne = new ImageIcon( SummarizationGui.class.getResource("/images/24/dashboardico.gif")); private JTabbedPane mainTabbedPane = new JTabbedPane(); private AnnotationTabPanel annotationTabPanel; private OntologyCleaner ontologyCleaner; private PatientExtractionPipeDialog patientExtractor; public SummarizationGui(String title) { super(title); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); SummarizationMenu mainMenu = new SummarizationMenu(); mainMenu.setActionListener(this); mainMenu.injectActionListener(); setJMenuBar(mainMenu); establishWindowControls(); buildMainPanel(); JPanel mainPanel = getMainPanel(); getContentPane().add(mainPanel); pack(); setLocationRelativeTo(null); setVisible(true); } private void establishWindowControls() { windowAdapter = new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); // You can still stop closing if you want to int res = JOptionPane.showConfirmDialog(SummarizationGui.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION); if (res == 0) { // dispose method issues the WINDOW_CLOSED event SummarizationGui.this.dispose(); } } @Override public void windowClosed(WindowEvent e) { super.windowClosed(e); System.exit(0); } }; addWindowListener(windowAdapter); } private void buildMainPanel() { mainPanel = new JPanel(); annotationTabPanel = new AnnotationTabPanel(); mainTabbedPane.addTab("Annotation", iconOne, annotationTabPanel, "AnnotateTab"); mainTabbedPane.setSelectedIndex(0); annotationTabPanel.setPatients(patients); annotationTabPanel.setPatientListReader(patientListReader); annotationTabPanel.build(); InferenceTabPanel inferenceTabPanel = new InferenceTabPanel(); mainTabbedPane.addTab("Inference", iconOne, inferenceTabPanel, "InferenceTab"); establishExtractor(); patientKnowledgeExtractor.setJessTextOutputer(jessOutputer); jessInputer.setJessTextOutputer(jessOutputer); jessInputer.setKnowledgeExtractor(patientKnowledgeExtractor); inferenceTabPanel.setJessInputer(jessInputer); inferenceTabPanel.setJessOutputer(jessOutputer); inferenceTabPanel.setKnowledgeExtractor(patientKnowledgeExtractor); inferenceTabPanel.setEngine(engine); inferenceTabPanel.setPatients(patients); inferenceTabPanel.build(); mainPanel.setLayout(new GridLayout(1, 1)); mainPanel.add(mainTabbedPane); mainPanel.setPreferredSize(new Dimension(1200, 900)); } private void establishExtractor() { try { engine.reset(); patientKnowledgeExtractor.setJessEngine(engine); patientKnowledgeExtractor.loadProductionClipsFiles(); patientKnowledgeExtractor.setPatients(patients); EncounterKnowlegeExractorFactory.setEncounterKnowledgeExtractor(new FhirEncounterKnowledgeExtractor()); } catch (JessException e) { e.printStackTrace(); } } public void loadReportWiget(ReportWidget fileWidget) { } public JPanel getMainPanel() { return mainPanel; } public void setMainPanel(JPanel mainPanel) { this.mainPanel = mainPanel; } public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); System.out.println(actionCommand); if (actionCommand.equals("Exit")) { closeWindow(); } else if (actionCommand.equals("Summarize All Patients")) { processExtractPatient(); } else if (actionCommand.equals("Load Single Patient To KB")) { processLoadSinglePatientToKb(); } else if (actionCommand.equals("Extract Encounters")) { processExtractEncounters(); } else if (actionCommand.equals("Ontology Clean")) { processOntologyClean(); } else if (actionCommand.equals("Patient Clean")) { processPatientClean(); } else if (actionCommand.equals("Reset")) { patientKnowledgeExtractor.executeJess("(reset)"); } else if (actionCommand.equals("Clear")) { patientKnowledgeExtractor.clearJess(); } else if (actionCommand.equals("Eval")) { patientKnowledgeExtractor.executeJess(jessInputer.geSelectedText()); } else if (actionCommand.equals("Run")) { patientKnowledgeExtractor.executeJess("(run)"); } else if (e.getActionCommand().equals("Templates")) { patientKnowledgeExtractor.displayDeftemplates(); } else if (e.getActionCommand().equals("Facts")) { patientKnowledgeExtractor.displayFacts(); } } private void processExtractEncounters() { EncounterKnowledgeExtractor encounterKnowledgeExtractor = new CtakesEncounterKnowledgeExtractor(); for (Patient patient : patients) { encounterKnowledgeExtractor.setPatient(patient); encounterKnowledgeExtractor.execute(); } } private void processExtractPatient() { patientExtractor = new PatientExtractionPipeDialog(this); patientExtractor.setAnnotationTabPanel(annotationTabPanel); patientExtractor.setKnowledgeExtractor(patientKnowledgeExtractor); patientExtractor.setPatients(patients); patientExtractor.setPartialPathTreeSet(partialPathTreeSet); patientExtractor.setPartialPathMap(partialPathMap); patientExtractor.addPropertyChangeListener(this); patientExtractor.setVisible(true); (new Thread(patientExtractor)).start(); } private void processLoadSinglePatientToKb() { EncounterKnowledgeExtractor encounterKnowledgeExtractor = EncounterKnowlegeExractorFactory.getEncounterKnowledgeExtractor(); for (Patient patient : patients) { encounterKnowledgeExtractor.setPatient(patient); encounterKnowledgeExtractor.execute(); break; } patientKnowledgeExtractor.setPatients(patients); patientKnowledgeExtractor.iteratePatients(); if (patientKnowledgeExtractor.hasMorePatients()) { patientKnowledgeExtractor.nextPatient(); patientKnowledgeExtractor.loadSinglePatient(); } } private void processPatientClean() { try { final I2b2DataDataSourceManager i2b2DataDataSourceManager = new I2b2DataDataSourceManager(); final I2B2DataDataWriter i2b2DataDataWriter = new I2B2DataDataWriter(); i2b2DataDataWriter.setDataSourceMgr(i2b2DataDataSourceManager); i2b2DataDataWriter.setSourceSystemCd("DEEPPHE2"); i2b2DataDataWriter.execute(); i2b2DataDataSourceManager.destroy(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } private void processOntologyClean() { partialPathTreeSet.clear(); partialPathMap.clear(); ontologyCleaner = new OntologyCleaner(this); ontologyCleaner.setPartialPathTreeSet(partialPathTreeSet); ontologyCleaner.setPartialPathMap(partialPathMap); ontologyCleaner.addPropertyChangeListener(this); ontologyCleaner.setVisible(true); (new Thread(ontologyCleaner)).start(); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() == ontologyCleaner && evt.getNewValue().equals("Finished")) { ontologyCleaner.dispose(); } else if (evt.getSource() == patientExtractor && evt.getNewValue().equals("Finished")) { patientExtractor.dispose(); } } private void closeWindow() { WindowEvent closingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue() .postEvent(closingEvent); } }
package com.uber.tchannel.benchmarks; import com.uber.tchannel.api.Request; import com.uber.tchannel.api.RequestHandler; import com.uber.tchannel.api.Response; import com.uber.tchannel.api.TChannel; import io.netty.util.concurrent.Promise; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.net.InetAddress; @State(Scope.Thread) public class PingPongServerBenchmark { TChannel channel; TChannel client; int port; @Setup(Level.Trial) public void setup() throws Exception { this.channel = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .build(); this.client = new TChannel.Builder("ping-client").build(); channel.listen(); this.port = this.channel.getListeningPort(); } @Benchmark @BenchmarkMode(Mode.Throughput) public void benchmark() throws Exception { Request<Ping> request = new Request.Builder<>(new Ping("{'key': 'ping?'}")) .setEndpoint("ping") .setService("some-service") .build(); Promise<Response<Pong>> f = this.client.callJSON( InetAddress.getLocalHost(), this.port, request, Pong.class ); f.get(); } @TearDown(Level.Trial) public void teardown() throws Exception { this.client.shutdown(); this.channel.shutdown(); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(".*" + PingPongServerBenchmark.class.getSimpleName() + ".*") .warmupIterations(5) .measurementIterations(10) .forks(1) .build(); new Runner(options).run(); } public class Ping { private final String request; public Ping(String request) { this.request = request; } } public class Pong { private final String response; public Pong(String response) { this.response = response; } } public class PingRequestHandler implements RequestHandler<Ping, Pong> { @Override public Class<Ping> getRequestType() { return Ping.class; } @Override public Class<Pong> getResponseType() { return Pong.class; } @Override public Response<Pong> handle(Request<Ping> request) { return new Response.Builder<>(new Pong("pong!")) .setEndpoint(request.getEndpoint()) .setHeaders(request.getHeaders()) .build(); } } }
package com.barryzhang.tcontributionsview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.barryzhang.tcontributionsview.adapter.BaseContributionsViewAdapter; import com.barryzhang.tcontributionsview.adapter.PositionContributionsViewAdapter; import com.barryzhang.tcontributionsview.adapter.TestContributionAdapter; public class TContributionsView extends View { protected BaseContributionsViewAdapter mAdapter; private int colorEmpty = Color.parseColor("#e0e0e0"); private int colorL1 = Color.parseColor("#cde372"); private int colorL2 = Color.parseColor("#7bbd52"); private int colorL3 = Color.parseColor("#389631"); private int colorL4 = Color.parseColor("#1a571b"); protected int itemWidth = 30; protected int itemHeight = 30; protected int itemSpace = 6; protected Paint paintEmpty = new Paint(); protected Paint paintL1 = new Paint(); protected Paint paintL2 = new Paint(); protected Paint paintL3 = new Paint(); protected Paint paintL4 = new Paint(); private RectF rectF; private boolean useCircleMode = false; OnDrawItemListener mOnDrawItemListener; public TContributionsView(Context context) { this(context, null); } public TContributionsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TContributionsView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TContributionsView); try { itemWidth = a.getDimensionPixelSize(R.styleable.TContributionsView_contributions_item_width, 20); itemHeight = a.getDimensionPixelSize(R.styleable.TContributionsView_contributions_item_height, 20); itemSpace = a.getDimensionPixelSize(R.styleable.TContributionsView_contributions_item_space, 2); colorEmpty = a.getColor(R.styleable.TContributionsView_contributions_color_0, colorEmpty); colorL1 = a.getColor(R.styleable.TContributionsView_contributions_color_1, colorL1); colorL2 = a.getColor(R.styleable.TContributionsView_contributions_color_2, colorL2); colorL3 = a.getColor(R.styleable.TContributionsView_contributions_color_3, colorL3); colorL4 = a.getColor(R.styleable.TContributionsView_contributions_color_4, colorL4); useCircleMode = a.getBoolean(R.styleable.TContributionsView_contributions_use_circle, useCircleMode); } catch (Exception e) { e.printStackTrace(); } finally { a.recycle(); } paintEmpty.setColor(colorEmpty); paintL1.setColor(colorL1); paintL2.setColor(colorL2); paintL3.setColor(colorL3); paintL4.setColor(colorL4); paintEmpty.setAntiAlias(true); paintL1.setAntiAlias(true); paintL2.setAntiAlias(true); paintL3.setAntiAlias(true); paintL4.setAntiAlias(true); rectF = new RectF(0, 0, itemWidth, itemHeight); if (isInEditMode()) { mAdapter = new TestContributionAdapter(); this.setAdapter(mAdapter); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int row = 0; int column = 0; if (this.mAdapter != null) { row = mAdapter.getRowCount(); column = mAdapter.getColumnCount(); } int measureWidth = (column == 0 ? 0 : column * (itemWidth + itemSpace) - itemSpace) + getPaddingLeft() + getPaddingRight(); int measureHeight = (row == 0 ? 0 : row * (itemHeight + itemSpace) - itemSpace) + getPaddingTop() + getPaddingBottom() ; int mWidth = widthMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(widthMeasureSpec) : measureWidth; int mHeight = heightMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(heightMeasureSpec) : measureHeight; setMeasuredDimension(mWidth, mHeight); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.clipRect(getPaddingLeft(), getPaddingTop(), getRight()- getPaddingRight(), getBottom() - getPaddingBottom()); if (mAdapter != null) { final int columnCount = mAdapter.getColumnCount(); final int rowCount = mAdapter.getRowCount(); for (int week = 0; week < columnCount; week++) { for (int day = 0; day < rowCount; day++) { rectF.left = (week == 0 ? 0 : week * (itemWidth + itemSpace)) + getPaddingLeft(); rectF.right = rectF.left + itemWidth ; rectF.top = (day == 0 ? 0 : day * (itemHeight + itemSpace)) + + getPaddingTop(); rectF.bottom = rectF.top + itemHeight; final int level = mAdapter.getLevel(day, week); final Paint paintByLevel = getPaintByLevel(level); if(mOnDrawItemListener == null || (mOnDrawItemListener != null &&!mOnDrawItemListener.beforeDrawItem(rectF, canvas,paintByLevel, level))) { if (level >= 0) { drawItem(rectF, canvas,paintByLevel, level); } } if(mOnDrawItemListener != null){ mOnDrawItemListener.afterDrawItem(rectF, canvas,paintByLevel, level); } } } } } protected void drawItem(RectF rect, Canvas canvas, Paint paintByLevel, int level) { if (useCircleMode) { paintByLevel.setAntiAlias(true); canvas.drawCircle((rectF.left + rectF.right) / 2, (rectF.top + rectF.bottom) / 2, Math.min(itemWidth, itemHeight) / 2, paintByLevel); } else { canvas.drawRect(rect, paintByLevel); } } private Paint getPaintByLevel(int level) { switch (level) { case 0: return paintEmpty; case 1: return paintL1; case 2: return paintL2; case 3: return paintL3; case 4: return paintL4; } return paintEmpty; } public void setAdapter(BaseContributionsViewAdapter adapter) { this.mAdapter = adapter; if (this.mAdapter != null) { this.mAdapter.setContributionsView(this); this.mAdapter.notifyDataSetChanged(); } } public BaseContributionsViewAdapter getAdapter() { return mAdapter; } public int getItemWidth() { return itemWidth; } public int getItemHeight() { return itemHeight; } public int getItemSpace() { return itemSpace; } public boolean isUseCircleMode() { return useCircleMode; } public static interface OnDrawItemListener{ /** * called before the default drawItem method, * You are abel to control if call default drawItem next. * @param rect * @param canvas * @param level * @return True will not called default drawItem method, false otherwise. */ boolean beforeDrawItem(RectF rect, Canvas canvas, Paint paint, int level); /** * called after the default drawItem method * @param rect * @param canvas * @param level */ void afterDrawItem(RectF rect, Canvas canvas, Paint paint, int level); } public void setOnDrawItemListener(OnDrawItemListener onDrawItemListener) { this.mOnDrawItemListener = onDrawItemListener; } }
import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; public class RangeMultiMap<V> { Map<Double, SortedMap<Envelope1D, Collection<V>>> scaleMapss = new HashMap<>(); private double discreteLen(double len) { return len == 0 ? 0 : Math.exp(Math.ceil(Math.log(len))); } public boolean put(Envelope1D range, V value) { double scaleLength = discreteLen(range.len()); SortedMap<Envelope1D, Collection<V>> scaleData = scaleMapss.get(scaleLength); if (scaleData == null) { scaleData = new TreeMap<>(); scaleMapss.put(scaleLength, scaleData); } Collection<V> values = scaleData.get(range); if (values == null) { values = new ArrayList<>(); scaleData.put(range, values); } return values.add(value); } public boolean remove(Envelope1D range, V value) { double scaleLength = discreteLen(range.len()); SortedMap<Envelope1D, Collection<V>> scaleData = scaleMapss.get(scaleLength); if (scaleData == null) { return false; } Collection<V> values = scaleData.get(range); if (values == null) { return false; } if (!values.remove(value)) { return false; } if (values.isEmpty()) { scaleData.remove(range); if (scaleData.isEmpty()) { scaleMapss.remove(scaleLength); } } return true; } public Iterable<Envelope1D> getKeys(Envelope1D query) { return Iterables.transform(getEntries(query), new Function<Map.Entry<Envelope1D, Collection<V>>, Envelope1D>() { public Envelope1D apply(Map.Entry<Envelope1D, Collection<V>> entry) { return entry.getKey(); }; }); } public Iterable<V> getValues(Envelope1D query) { return Iterables.concat(Iterables.transform(getEntries(query), new Function<Map.Entry<Envelope1D, Collection<V>>, Collection<V>>() { public Collection<V> apply(Map.Entry<Envelope1D, Collection<V>> entry) { return entry.getValue(); }; })); } public Iterable<Map.Entry<Envelope1D, Collection<V>>> getEntries(final Envelope1D query) { Collection<Iterable<Map.Entry<Envelope1D, Collection<V>>>> scaleIterators = new ArrayList<>(); for (Map.Entry<Double, SortedMap<Envelope1D, Collection<V>>> entry : scaleMapss.entrySet()) { Double scale = entry.getKey(); SortedMap<Envelope1D, Collection<V>> scaleValues = entry.getValue(); scaleIterators.add(Iterables.filter( scaleValues.subMap( new Envelope1D(query.min - scale, Double.NEGATIVE_INFINITY), new Envelope1D(query.max, Double.POSITIVE_INFINITY)).entrySet(), new Predicate<Map.Entry<Envelope1D, Collection<V>>>() { @Override public boolean apply(Entry<Envelope1D, Collection<V>> entry) { return query.intersects(entry.getKey()) ; } })); } return Iterables.mergeSorted(scaleIterators, new Comparator<Map.Entry<Envelope1D, Collection<V>>>() { @Override public int compare(Entry<Envelope1D, Collection<V>> o1, Entry<Envelope1D, Collection<V>> o2) { return o1.getKey().compareTo(o2.getKey()); } }); } }
package Replay; import Constants.GameMode; import Constants.Mod; import com.google.auto.value.AutoValue; import java.util.EnumSet; import java.util.List; @AutoValue public abstract class Replay { public abstract GameMode gameMode(); public abstract int gameVersion(); public abstract String beatmapHash(); public abstract long timestamp(); public abstract String replayHash(); public abstract String playerName(); public abstract EnumSet<Mod> mods(); public abstract int totalScore(); public abstract short maxCombo(); public abstract boolean isPerfect(); public abstract short num300(); public abstract short num100(); public abstract short num50(); public abstract short numGeki(); public abstract short numKatu(); public abstract short numMiss(); public abstract List<LifeBarSample> lifebar(); public abstract List<Action> events(); public static Builder builder() { return new AutoValue_Replay.Builder(); } public abstract Builder toBuilder(); @AutoValue.Builder public abstract static class Builder { public abstract Builder setGameMode(GameMode gameMode); public abstract Builder setGameVersion(int gameVersion); public abstract Builder setBeatmapHash(String beatmapHash); public abstract Builder setTimestamp(long timestamp); public abstract Builder setReplayHash(String replayHash); public abstract Builder setPlayerName(String playerName); public abstract Builder setMods(EnumSet<Mod> mods); public abstract Builder setTotalScore(int totalScore); public abstract Builder setMaxCombo(short maxCombo); public abstract Builder setIsPerfect(boolean isPerfect); public abstract Builder setNum300(short num300); public abstract Builder setNum100(short num100); public abstract Builder setNum50(short num50); public abstract Builder setNumGeki(short numGeki); public abstract Builder setNumKatu(short numKatu); public abstract Builder setNumMiss(short numMiss); public abstract Builder setLifebar(List<LifeBarSample> lifebar); public abstract Builder setEvents(List<Action> events); public abstract Replay build(); } }
package Replay; import Constants.GameMode; import Constants.Mod; import java.util.EnumSet; import java.util.List; public class Replay { private final GameMode gameMode; private final int gameVersion; private final String beatmapHash; private final long timestamp; private final String replayHash; private final String playerName; private final EnumSet<Mod> mods; private final int totalScore; private final short maxCombo; private final boolean isPerfect; private final short num300; private final short num100; private final short num50; private final short numGeki; private final short numKatu; private final short numMiss; private final List<LifeBarSample> lifebar; private final List<Action> events; Replay( GameMode gameMode, int gameVersion, String beatmapHash, long timestamp, String replayHash, String playerName, EnumSet<Mod> mods, int totalScore, short maxCombo, boolean isPerfect, short num300, short num100, short num50, short numGeki, short numKatu, short numMiss, List<LifeBarSample> lifebar, List<Action> events) { this.gameMode = gameMode; this.gameVersion = gameVersion; this.beatmapHash = beatmapHash; this.timestamp = timestamp; this.replayHash = replayHash; this.playerName = playerName; this.mods = mods; this.totalScore = totalScore; this.maxCombo = maxCombo; this.isPerfect = isPerfect; this.num300 = num300; this.num100 = num100; this.num50 = num50; this.numGeki = numGeki; this.numKatu = numKatu; this.numMiss = numMiss; this.lifebar = lifebar; this.events = events; } public GameMode getGameMode() { return gameMode; } public int getGameVersion() { return gameVersion; } public String getBeatmapHash() { return beatmapHash; } public long getTimestamp() { return timestamp; } public String getReplayHash() { return replayHash; } public String getPlayerName() { return playerName; } public EnumSet<Mod> getMods() { return mods; } public int getTotalScore() { return totalScore; } public short getMaxCombo() { return maxCombo; } public boolean isPerfect() { return isPerfect; } public short getNum300() { return num300; } public short getNum100() { return num100; } public short getNum50() { return num50; } public short getNumGeki() { return numGeki; } public short getNumKatu() { return numKatu; } public short getNumMiss() { return numMiss; } public List<LifeBarSample> getLifebar() { return lifebar; } public List<Action> getEvents() { return events; } public static Builder builder() { return new Builder(); } public static class Builder<T extends Builder> { private GameMode gameMode; private int gameVersion; private String beatmapHash; private long timestamp; private String replayHash; private String playerName; private EnumSet<Mod> mods; private int totalScore; private short maxCombo; private boolean isPerfect; private short num300; private short num100; private short num50; private short numGeki; private short numKatu; private short numMiss; private List<LifeBarSample> lifebar; private List<Action> events; public Replay.Builder setGameMode(GameMode gameMode) { this.gameMode = gameMode; return this; } public Builder setGameVersion(int gameVersion) { this.gameVersion = gameVersion; return this; } public Builder setBeatmapHash(String beatmapHash) { this.beatmapHash = beatmapHash; return this; } public Builder setTimestamp(long timestamp) { this.timestamp = timestamp; return this; } public Builder setReplayHash(String replayHash) { this.replayHash = replayHash; return this; } public Builder setPlayerName(String playerName) { this.playerName = playerName; return this; } public Builder setMods(EnumSet<Mod> mods) { this.mods = mods; return this; } public Builder setTotalScore(int totalScore) { this.totalScore = totalScore; return this; } public Builder setMaxCombo(short maxCombo) { this.maxCombo = maxCombo; return this; } public Builder setIsPerfect(boolean isPerfect) { this.isPerfect = isPerfect; return this; } public Builder setNum300(short num300) { this.num300 = num300; return this; } public Builder setNum100(short num100) { this.num100 = num100; return this; } public Builder setNum50(short num50) { this.num50 = num50; return this; } public Builder setNumGeki(short numGeki) { this.numGeki = numGeki; return this; } public Builder setNumKatu(short numKatu) { this.numKatu = numKatu; return this; } public Builder setNumMiss(short numMiss) { this.numMiss = numMiss; return this; } public Builder setLifebar(List<LifeBarSample> lifebar) { this.lifebar = lifebar; return this; } public Builder setEvents(List<Action> events) { this.events = events; return this; } public Replay build() { return new Replay( gameMode, gameVersion, beatmapHash, timestamp, replayHash, playerName, mods, totalScore, maxCombo, isPerfect, num300, num100, num50, numGeki, numKatu, numMiss, lifebar, events); } public static Builder fromReplay(Replay source) { return new Builder() .setGameMode(source.getGameMode()) .setGameVersion(source.getGameVersion()) .setBeatmapHash(source.getBeatmapHash()) .setTimestamp(source.getTimestamp()) .setReplayHash(source.getReplayHash()) .setPlayerName(source.getPlayerName()) .setMods(source.getMods()) .setTotalScore(source.getTotalScore()) .setMaxCombo(source.getMaxCombo()) .setIsPerfect(source.isPerfect()) .setNum300(source.getNum300()) .setNum100(source.getNum100()) .setNum50(source.getNum50()) .setNumGeki(source.getNumGeki()) .setNumKatu(source.getNumKatu()) .setNumMiss(source.getNumMiss()) .setLifebar(source.getLifebar()) .setEvents(source.getEvents()); } } }
package ibis.io; import ibis.util.TypedProperties; import java.io.IOException; /** * This is the <code>SerializationOutputStream</code> version that is used * for data serialization. With data serialization, you can only write * basic types and arrays of basic types. It also serves as a base type * for Ibis serialization. */ public class DataSerializationOutputStream extends SerializationOutputStream implements IbisStreamFlags { /** * The underlying <code>Accumulator</code>. */ private final Accumulator out; /** * Allocator for the typed buffer arrays. */ private static final DataAllocator allocator = TypedProperties.booleanProperty(IOProps.s_cache, false) ? new DataAllocator() : (DataAllocator) new DummyAllocator(); /** * Storage for bytes (or booleans) written. */ private byte[] byte_buffer; /** * Storage for chars written. */ private char[] char_buffer; /** * Storage for shorts written. */ private short[] short_buffer; /** * Storage for ints written. */ private int[] int_buffer; /** * Storage for longs written. */ private long[] long_buffer; /** * Storage for floats written. */ private float[] float_buffer; /** * Storage for doubles written. */ private double[] double_buffer; /** * Current index in <code>byte_buffer</code>. */ private int byte_index; /** * Current index in <code>char_buffer</code>. */ private int char_index; /** * Current index in <code>short_buffer</code>. */ private int short_index; /** * Current index in <code>int_buffer</code>. */ private int int_index; /** * Current index in <code>long_buffer</code>. */ private int long_index; /** * Current index in <code>float_buffer</code>. */ private int float_index; /** * Current index in <code>double_buffer</code>. */ private int double_index; /** * Register how often we need to acquire a new set of primitive array * buffers. private int unfinished; { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.err.println(DataSerializationOutputStream.this + ": unfinished calls " + unfinished); statistics(); } }); } */ /** * Structure summarizing an array write. */ private static final class ArrayDescriptor { int type; boolean[] booleanArray; byte[] byteArray; char[] charArray; short[] shortArray; int[] intArray; long[] longArray; float[] floatArray; double[] doubleArray; int offset; int len; } /** * Where the arrays to be written are collected. */ private ArrayDescriptor[] array; /** * Index in the <code>array</code> array. */ private int array_index; /** * Collects all indices of the <code>_buffer</code> arrays. */ private short[] indices_short; /** * For each */ private boolean[] touched = new boolean[PRIMITIVE_TYPES]; /** * Constructor with an <code>Accumulator</code>. * @param out the underlying <code>Accumulator</code> * @exception IOException gets thrown when an IO error occurs. */ public DataSerializationOutputStream(Accumulator out) throws IOException { super(); this.out = out; initArrays(); } /** * Constructor, may be used when this class is sub-classed. */ protected DataSerializationOutputStream() throws IOException { super(); out = null; } public String serializationImplName() { return "data"; } public void statistics() { } /** * Method to put a boolean array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayBoolean(boolean[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_BOOLEAN) { // System.err.println("Special boolean array write len " + len); /* Maybe lift the check from the writeBoolean? */ for (int i = offset; i < offset + len; i++) { writeBoolean(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayBoolean: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_BOOLEAN); } array[array_index].type = TYPE_BOOLEAN; array[array_index].offset = offset; array[array_index].len = len; array[array_index].booleanArray = ref; array_index++; addStatSendArray(ref, TYPE_BOOLEAN, len); } stopTimer(); } /** * Method to put a byte array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayByte(byte[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_BYTE) { // System.err.println("Special byte array write len " + len); for (int i = offset; i < offset + len; i++) { writeByte(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayByte: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_BYTE); } array[array_index].type = TYPE_BYTE; array[array_index].offset = offset; array[array_index].len = len; array[array_index].byteArray = ref; array_index++; addStatSendArray(ref, TYPE_BYTE, len); } stopTimer(); } /** * Method to put a char array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayChar(char[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_CHAR) { // System.err.println("Special char array write len " + len); for (int i = offset; i < offset + len; i++) { writeChar(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayChar: " + new String(ref) + " offset: " + offset + " len: " + len + " type: " + TYPE_CHAR); } array[array_index].type = TYPE_CHAR; array[array_index].offset = offset; array[array_index].len = len; array[array_index].charArray = ref; array_index++; addStatSendArray(ref, TYPE_CHAR, len); } stopTimer(); } /** * Method to put a short array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayShort(short[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_SHORT) { // System.err.println("Special short array write len " + len); for (int i = offset; i < offset + len; i++) { writeShort(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayShort: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_SHORT); } array[array_index].type = TYPE_SHORT; array[array_index].offset = offset; array[array_index].len = len; array[array_index].shortArray = ref; array_index++; addStatSendArray(ref, TYPE_SHORT, len); } stopTimer(); } /** * Method to put a int array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayInt(int[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_INT) { // System.err.println("Special int array write len " + len); for (int i = offset; i < offset + len; i++) { writeInt(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayInt: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_INT); } array[array_index].type = TYPE_INT; array[array_index].offset = offset; array[array_index].len = len; array[array_index].intArray = ref; array_index++; addStatSendArray(ref, TYPE_INT, len); } stopTimer(); } /** * Method to put a long array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayLong(long[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_LONG) { // System.err.println("Special long array write len " + len); for (int i = offset; i < offset + len; i++) { writeLong(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayLong: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_LONG); } array[array_index].type = TYPE_LONG; array[array_index].offset = offset; array[array_index].len = len; array[array_index].longArray = ref; array_index++; addStatSendArray(ref, TYPE_LONG, len); } stopTimer(); } /** * Method to put a float array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayFloat(float[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_FLOAT) { // System.err.println("Special float array write len " + len); for (int i = offset; i < offset + len; i++) { writeFloat(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayFloat: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_FLOAT); } array[array_index].type = TYPE_FLOAT; array[array_index].offset = offset; array[array_index].len = len; array[array_index].floatArray = ref; array_index++; addStatSendArray(ref, TYPE_FLOAT, len); } stopTimer(); } /** * Method to put a double array in the "array cache". If the cache is full * it is written to the arrayOutputStream. * This method is public because it gets called from rewritten code. * @param ref the array to be written * @param offset the offset at which to start * @param len number of elements to write * * @exception IOException on IO error. */ public void writeArrayDouble(double[] ref, int offset, int len) throws IOException { startTimer(); if (len < SMALL_ARRAY_BOUND / SIZEOF_DOUBLE) { // System.err.println("Special double array write len " + len); for (int i = offset; i < offset + len; i++) { writeDouble(ref[i]); } } else { if (array_index == ARRAY_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("writeArrayDouble: " + ref + " offset: " + offset + " len: " + len + " type: " + TYPE_DOUBLE); } array[array_index].type = TYPE_DOUBLE; array[array_index].offset = offset; array[array_index].len = len; array[array_index].doubleArray = ref; array_index++; addStatSendArray(ref, TYPE_DOUBLE, len); } stopTimer(); } void addStatSendArray(Object ref, int type, int len) { } /** * Flushes everything collected sofar. * @exception IOException on an IO error. */ public void flush() throws IOException { if (DEBUG) { dbPrint("doing a flush()"); } suspendTimer(); flushBuffers(); /* Retain the order in which the arrays were pushed. This * costs a cast at receive time. */ for (int i = 0; i < array_index; i++) { ArrayDescriptor a = array[i]; switch(a.type) { case TYPE_BOOLEAN: out.writeArray(a.booleanArray, a.offset, a.len); break; case TYPE_BYTE: out.writeArray(a.byteArray, a.offset, a.len); break; case TYPE_CHAR: out.writeArray(a.charArray, a.offset, a.len); break; case TYPE_SHORT: out.writeArray(a.shortArray, a.offset, a.len); break; case TYPE_INT: out.writeArray(a.intArray, a.offset, a.len); break; case TYPE_LONG: out.writeArray(a.longArray, a.offset, a.len); break; case TYPE_FLOAT: out.writeArray(a.floatArray, a.offset, a.len); break; case TYPE_DOUBLE: out.writeArray(a.doubleArray, a.offset, a.len); break; } } array_index = 0; out.flush(); resumeTimer(); if (out instanceof ArrayOutputStream) { ArrayOutputStream o = (ArrayOutputStream) out; if (! o.finished()) { indices_short = allocator.getIndexArray(); if (touched[TYPE_BYTE]) { byte_buffer = allocator.getByteArray(); } if (touched[TYPE_CHAR]) { char_buffer = allocator.getCharArray(); } if (touched[TYPE_SHORT]) { short_buffer = allocator.getShortArray(); } if (touched[TYPE_INT]) { int_buffer = allocator.getIntArray(); } if (touched[TYPE_LONG]) { long_buffer = allocator.getLongArray(); } if (touched[TYPE_FLOAT]) { float_buffer = allocator.getFloatArray(); } if (touched[TYPE_DOUBLE]) { double_buffer = allocator.getDoubleArray(); } // unfinished++; } } for (int i = 0; i < PRIMITIVE_TYPES; i++) { touched[i] = false; } } /** * Writes a boolean value to the accumulator. * @param value The boolean value to write. * @exception IOException on IO error. */ public void writeBoolean(boolean value) throws IOException { startTimer(); if (byte_index == BYTE_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote boolean " + value); } byte_buffer[byte_index++] = (byte) (value ? 1 : 0); stopTimer(); } /** * Writes a byte value to the accumulator. * @param value The byte value to write. * @exception IOException on IO error. */ public void writeByte(int value) throws IOException { startTimer(); if (byte_index == BYTE_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote byte " + value); } byte_buffer[byte_index++] = (byte) value; stopTimer(); } /** * Writes a char value to the accumulator. * @param value The char value to write. * @exception IOException on IO error. */ public void writeChar(char value) throws IOException { startTimer(); if (char_index == CHAR_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote char " + value); } char_buffer[char_index++] = value; stopTimer(); } /** * Writes a short value to the accumulator. * @param value The short value to write. * @exception IOException on IO error. */ public void writeShort(int value) throws IOException { startTimer(); if (short_index == SHORT_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote short " + value); } short_buffer[short_index++] = (short) value; stopTimer(); } /** * Writes a int value to the accumulator. * @param value The int value to write. * @exception IOException on IO error. */ public void writeInt(int value) throws IOException { startTimer(); if (int_index == INT_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote int[HEX] " + value + "[0x" + Integer.toHexString(value) + "]"); } int_buffer[int_index++] = value; stopTimer(); } /** * Writes a long value to the accumulator. * @param value The long value to write. * @exception IOException on IO error. */ public void writeLong(long value) throws IOException { startTimer(); if (long_index == LONG_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote long " + value); } long_buffer[long_index++] = value; stopTimer(); } /** * Writes a float value to the accumulator. * @param value The float value to write. * @exception IOException on IO error. */ public void writeFloat(float value) throws IOException { startTimer(); if (float_index == FLOAT_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote float " + value); } float_buffer[float_index++] = value; stopTimer(); } /** * Writes a double value to the accumulator. * @param value The double value to write. * @exception IOException on IO error. */ public void writeDouble(double value) throws IOException { startTimer(); if (double_index == DOUBLE_BUFFER_SIZE) { flush(); } if (DEBUG) { dbPrint("wrote double " + value); } double_buffer[double_index++] = value; stopTimer(); } public void close() throws IOException { flush(); out.close(); } /* * If you are overriding DataSerializationOutputStream, * you can stop now :-) * The rest is built on top of these. */ /** * Allocates buffers. */ private void initArrays() { array = new ArrayDescriptor[ARRAY_BUFFER_SIZE]; for (int i = 0; i < ARRAY_BUFFER_SIZE; i++) { array[i] = new ArrayDescriptor(); } indices_short = allocator.getIndexArray(); byte_buffer = allocator.getByteArray(); char_buffer = allocator.getCharArray(); short_buffer = allocator.getShortArray(); int_buffer = allocator.getIntArray(); long_buffer = allocator.getLongArray(); float_buffer = allocator.getFloatArray(); double_buffer = allocator.getDoubleArray(); } /** * The array buffer allocator. Use this to return data arrays * when they are finished. The allocator may cache/reuse them. */ public DataAllocator getAllocator() { if (allocator instanceof DummyAllocator) { return null; } return allocator; } /** * Debugging print. * @param s the string to be printed. */ void dbPrint(String s) { DataSerializationInputStream.debuggerPrint(this + ": " + s); } public void reset() throws IOException { } /* This is the data output / object output part */ public void write(int v) throws IOException { writeByte((byte)(0xff & v)); } public void write(byte[] b) throws IOException { write(b, 0, b.length); } public void write(byte[] b, int off, int len) throws IOException { writeArray(b, off, len); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeUTF(String str) throws IOException { throw new IOException("Illegal data type written"); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeClass(Class ref) throws IOException { throw new IOException("Illegal data type written"); } /** * Initialize all buffer indices to zero. */ private void reset_indices() { byte_index = 0; char_index = 0; short_index = 0; int_index = 0; long_index = 0; float_index = 0; double_index = 0; } /** * Flush the primitive arrays. * * @exception IOException is thrown when any <code>writeArray</code> * throws it. */ private void flushBuffers() throws IOException { indices_short[TYPE_BYTE] = (short) byte_index; indices_short[TYPE_CHAR] = (short) char_index; indices_short[TYPE_SHORT] = (short) short_index; indices_short[TYPE_INT] = (short) int_index; indices_short[TYPE_LONG] = (short) long_index; indices_short[TYPE_FLOAT] = (short) float_index; indices_short[TYPE_DOUBLE] = (short) double_index; if (DEBUG) { dbPrint("writing bytes " + byte_index); dbPrint("writing chars " + char_index); dbPrint("writing shorts " + short_index); dbPrint("writing ints " + int_index); dbPrint("writing longs " + long_index); dbPrint("writing floats " + float_index); dbPrint("writing doubles " + double_index); } out.writeArray(indices_short, BEGIN_TYPES, PRIMITIVE_TYPES-BEGIN_TYPES); if (byte_index > 0) { out.writeArray(byte_buffer, 0, byte_index); touched[TYPE_BYTE] = true; } if (char_index > 0) { out.writeArray(char_buffer, 0, char_index); touched[TYPE_CHAR] = true; } if (short_index > 0) { out.writeArray(short_buffer, 0, short_index); touched[TYPE_SHORT] = true; } if (int_index > 0) { out.writeArray(int_buffer, 0, int_index); touched[TYPE_INT] = true; } if (long_index > 0) { out.writeArray(long_buffer, 0, long_index); touched[TYPE_LONG] = true; } if (float_index > 0) { out.writeArray(float_buffer, 0, float_index); touched[TYPE_FLOAT] = true; } if (double_index > 0) { out.writeArray(double_buffer, 0, double_index); touched[TYPE_DOUBLE] = true; } reset_indices(); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeBytes(String s) throws IOException { throw new IOException("Illegal data type written"); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeChars(String s) throws IOException { throw new IOException("Illegal data type written"); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(boolean[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayBoolean(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(byte[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayByte(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(short[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayShort(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(char[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayChar(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(int[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayInt(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(long[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayLong(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(float[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayFloat(ref, off, len); stopTimer(); } /** * {@inheritDoc} * * We must write something before the array to ensure that the receiver * reads its buffer bounds. */ public void writeArray(double[] ref, int off, int len) throws IOException { startTimer(); writeInt(len); writeArrayDouble(ref, off, len); stopTimer(); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeArray(Object[] ref, int off, int len) throws IOException { throw new IOException("Illegal data type written"); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeObjectOverride(Object ref) throws IOException { throw new IOException("Illegal data type written"); } /** * @exception IOException is thrown, as this is not allowed. */ public void writeUnshared(Object ref) throws IOException { throw new IOException("Illegal data type written"); } public void useProtocolVersion(int version) { /* ignored. */ } /** * @exception IOException is thrown, as this is not allowed. */ public void writeFields() throws IOException { throw new IOException("Illegal data type written"); } /** * @exception IOException is thrown, as this is not allowed. */ public PutField putFields() throws IOException { throw new IOException("Illegal data type written"); } /** * @exception IOException is thrown, as this is not allowed. */ public void defaultWriteObject() throws IOException { throw new IOException("Illegal data type written"); } }
package com.linkedin.thirdeye.bootstrap; import com.fasterxml.jackson.databind.ObjectMapper; import com.linkedin.thirdeye.api.StarTree; import com.linkedin.thirdeye.api.StarTreeConfig; import com.linkedin.thirdeye.api.StarTreeConstants; import com.linkedin.thirdeye.api.StarTreeNode; import com.linkedin.thirdeye.api.StarTreeRecord; import com.linkedin.thirdeye.impl.StarTreeImpl; import com.linkedin.thirdeye.impl.StarTreeQueryImpl; import com.linkedin.thirdeye.impl.StarTreeRecordImpl; import com.linkedin.thirdeye.impl.StarTreeRecordStoreCircularBufferImpl; import com.linkedin.thirdeye.impl.StarTreeUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class StarTreeBootstrapJob extends Configured { public static final String PROP_STARTREE_CONFIG = "startree.config"; public static final String PROP_STARTREE_ROOT = "startree.root"; public static final String PROP_INPUT_PATHS = "input.paths"; public static final String PROP_OUTPUT_PATH = "output.path"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final String name; private final Properties props; public StarTreeBootstrapJob(String name, Properties props) { super(new Configuration()); this.name = name; this.props = props; } public static class StarTreeBootstrapMapper extends Mapper<Object, Text, Text, Text> { private final Text nodeId = new Text(); private StarTree starTree; @Override public void setup(Context context) throws IOException, InterruptedException { FileSystem fileSystem = FileSystem.get(context.getConfiguration()); Path rootPath = new Path(context.getConfiguration().get(PROP_STARTREE_ROOT)); Path configPath = new Path(context.getConfiguration().get(PROP_STARTREE_CONFIG)); try { StarTreeConfig config = StarTreeConfig.fromJson(OBJECT_MAPPER.readTree(fileSystem.open(configPath))); ObjectInputStream objectInputStream = new ObjectInputStream(fileSystem.open(rootPath)); StarTreeNode root = (StarTreeNode) objectInputStream.readObject(); starTree = new StarTreeImpl(config, root); } catch (Exception e) { throw new IOException(e); } } @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { int idx = 0; String[] tokens = value.toString().split("\t"); // TSV -> query StarTreeQueryImpl.Builder query = new StarTreeQueryImpl.Builder(); for (String dimensionName : starTree.getConfig().getDimensionNames()) { query.setDimensionValue(dimensionName, tokens[idx++]); } query.setTimeBuckets(new HashSet<Long>(Arrays.asList(Long.valueOf(tokens[idx])))); // Get node IDs Collection<StarTreeNode> nodes = starTree.findAll(query.build()); // Output ID -> entry mapping for (StarTreeNode node : nodes) { nodeId.set(node.getId().toString()); context.write(nodeId, value); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { // Write an all-other node w/ empty metric values for each StringBuilder sb = new StringBuilder(); for (String dimensionName : starTree.getConfig().getDimensionNames()) { sb.append(StarTreeConstants.OTHER).append("\t"); } for (String metricName : starTree.getConfig().getMetricNames()) { sb.append(0).append("\t"); } sb.append(0); Text value = new Text(sb.toString()); writeOtherRecord(context, starTree.getRoot(), value); } private void writeOtherRecord(Context context, StarTreeNode node, Text value) throws IOException, InterruptedException { if (node.isLeaf()) { nodeId.set(node.getId().toString()); context.write(nodeId, value); } else { for (StarTreeNode child : node.getChildren()) { writeOtherRecord(context, child, value); } writeOtherRecord(context, node.getOtherNode(), value); writeOtherRecord(context, node.getStarNode(), value); } } } public static class StarTreeBootstrapReducer extends Reducer<Text, Text, NullWritable, NullWritable> { private static final Logger LOG = LoggerFactory.getLogger(StarTreeBootstrapReducer.class); private StarTreeConfig config; private int numTimeBuckets; private Path outputPath; @Override public void setup(Context context) throws IOException, InterruptedException { try { Path configPath = new Path(context.getConfiguration().get(PROP_STARTREE_CONFIG)); config = StarTreeConfig.fromJson( OBJECT_MAPPER.readTree(FileSystem.get(context.getConfiguration()).open(configPath))); numTimeBuckets = Integer.valueOf(config.getRecordStoreFactory().getConfig().getProperty("numTimeBuckets")); } catch (Exception e) { throw new IOException(e); } outputPath = new Path(context.getConfiguration().get(PROP_OUTPUT_PATH)); } @Override public void reduce(Text nodeId, Iterable<Text> tsvRecords, Context context) throws IOException, InterruptedException { Map<String, Map<Long, StarTreeRecord>> records = new HashMap<String, Map<Long, StarTreeRecord>>(); LOG.info("Merging records for " + nodeId.toString()); // Aggregate records for (Text tsvRecord : tsvRecords) { StarTreeRecord record = createRecord(tsvRecord); // Initialize buckets Map<Long, StarTreeRecord> timeBuckets = records.get(record.getKey(false)); if (timeBuckets == null) { timeBuckets = new HashMap<Long, StarTreeRecord>(); records.put(record.getKey(false), timeBuckets); } // Get bucket long bucket = record.getTime() % numTimeBuckets; // Merge or overwrite existing record StarTreeRecord aggRecord = timeBuckets.get(bucket); if (aggRecord == null || aggRecord.getTime() < record.getTime()) { timeBuckets.put(bucket, record); } else if (aggRecord.getTime().equals(record.getTime())) { timeBuckets.put(bucket, StarTreeUtils.merge(Arrays.asList(record, aggRecord))); } } // Get all merged records List<StarTreeRecord> mergedRecords = new ArrayList<StarTreeRecord>(); for (Map<Long, StarTreeRecord> timeBucket : records.values()) { for (Map.Entry<Long, StarTreeRecord> entry : timeBucket.entrySet()) { mergedRecords.add(entry.getValue()); } } records = null; // for gc // Create new forward index int nextValueId = StarTreeConstants.FIRST_VALUE; Map<String, Map<String, Integer>> forwardIndex = new HashMap<String, Map<String, Integer>>(); for (StarTreeRecord record : mergedRecords) { for (String dimensionName : config.getDimensionNames()) { Map<String, Integer> forward = forwardIndex.get(dimensionName); if (forward == null) { forward = new HashMap<String, Integer>(); forwardIndex.put(dimensionName, forward); } String dimensionValue = record.getDimensionValues().get(dimensionName); Integer valueId = forward.get(dimensionValue); if (valueId == null) { forward.put(dimensionValue, nextValueId++); } } } // Get buffer int bufferSize = mergedRecords.size() * // number of records in the store (config.getDimensionNames().size() * Integer.SIZE / 8 // the dimension part + (config.getMetricNames().size() + 1) * numTimeBuckets * Long.SIZE / 8); // metric + time ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize); // Load records into buffer buffer.clear(); StarTreeRecordStoreCircularBufferImpl.fillBuffer( buffer, config.getDimensionNames(), config.getMetricNames(), forwardIndex, mergedRecords, numTimeBuckets, true); // Write that buffer to file (n.b. known heap buffer so use backing array) buffer.flip(); Path bufferPath = new Path(outputPath, nodeId.toString() + StarTreeRecordStoreFactoryCircularBufferHdfsImpl.BUFFER_SUFFIX); OutputStream outputStream = FileSystem.get(context.getConfiguration()).create(bufferPath, true); WritableByteChannel channel = Channels.newChannel(outputStream); channel.write(buffer); outputStream.flush(); outputStream.close(); // Write forward index to file Path indexPath = new Path(outputPath, nodeId.toString() + StarTreeRecordStoreFactoryCircularBufferHdfsImpl.INDEX_SUFFIX); outputStream = FileSystem.get(context.getConfiguration()).create(indexPath, true); OBJECT_MAPPER.writeValue(outputStream, forwardIndex); outputStream.flush(); outputStream.close(); } private StarTreeRecord createRecord(Text tsvLine) { StarTreeRecordImpl.Builder builder = new StarTreeRecordImpl.Builder(); int idx = 0; String[] tokens = tsvLine.toString().split("\t"); for (String dimensionName : config.getDimensionNames()) { builder.setDimensionValue(dimensionName, tokens[idx++]); } for (String metricName : config.getMetricNames()) { builder.setMetricValue(metricName, Long.valueOf(tokens[idx++])); } builder.setTime(Long.valueOf(tokens[idx])); return builder.build(); } } public void run() throws Exception { Job job = Job.getInstance(getConf()); job.setJobName(name); job.setJarByClass(StarTreeBootstrapJob.class); // Map config job.setMapperClass(StarTreeBootstrapMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); // Reduce config job.setReducerClass(StarTreeBootstrapReducer.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(NullWritable.class); // Star-tree config job.getConfiguration().set(PROP_STARTREE_CONFIG, getAndCheck(PROP_STARTREE_CONFIG)); job.getConfiguration().set(PROP_STARTREE_ROOT, getAndCheck(PROP_STARTREE_ROOT)); job.getConfiguration().set(PROP_OUTPUT_PATH, getAndCheck(PROP_OUTPUT_PATH)); for (String inputPath : getAndCheck(PROP_INPUT_PATHS).split(",")) { FileInputFormat.addInputPath(job, new Path(inputPath)); } FileOutputFormat.setOutputPath(job, new Path(getAndCheck(PROP_OUTPUT_PATH))); job.waitForCompletion(true); } private String getAndCheck(String propName) { String propValue = props.getProperty(propName); if (propValue == null) { throw new IllegalArgumentException(propName + " required property"); } return propValue; } public static void main(String[] args) throws Exception { if (args.length != 1) { throw new IllegalArgumentException("usage: config.properties"); } Properties props = new Properties(); props.load(new FileInputStream(args[0])); StarTreeBootstrapJob bootstrapJob = new StarTreeBootstrapJob("star_tree_bootstrap_job", props); bootstrapJob.run(); } }
package org.jboss.xnio; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.Selector; import java.nio.channels.Channel; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.zip.ZipFile; import org.jboss.xnio.log.Logger; import java.util.logging.Handler; /** * General I/O utility methods. * * @apiviz.exclude */ public final class IoUtils { private static final Executor NULL_EXECUTOR = new Executor() { private final String string = String.format("null executor <%s>", Integer.toHexString(hashCode())); public void execute(final Runnable command) { // no operation } public String toString() { return string; } }; private static final Executor DIRECT_EXECUTOR = new Executor() { private final String string = String.format("direct executor <%s>", Integer.toHexString(hashCode())); public void execute(final Runnable command) { command.run(); } public String toString() { return string; } }; private static final Closeable NULL_CLOSEABLE = new Closeable() { private final String string = String.format("null closeable <%s>", Integer.toHexString(hashCode())); public void close() throws IOException { // no operation } public String toString() { return string; } }; private IoUtils() {} /** * Get the direct executor. This is an executor that executes the provided task in the same thread. * * @return a direct executor */ public static Executor directExecutor() { return DIRECT_EXECUTOR; } /** * Get the null executor. This is an executor that never actually executes the provided task. * * @return a null executor */ public static Executor nullExecutor() { return NULL_EXECUTOR; } /** * Get a closeable executor wrapper for an {@code ExecutorService}. The given timeout is used to determine how long * the {@code close()} method will wait for a clean shutdown before the executor is shut down forcefully. * * @param executorService the executor service * @param timeout the timeout * @param unit the unit for the timeout * @return a new closeable executor */ public static CloseableExecutor closeableExecutor(final ExecutorService executorService, final long timeout, final TimeUnit unit) { return new CloseableExecutor() { public void close() throws IOException { executorService.shutdown(); try { if (executorService.awaitTermination(timeout, unit)) { return; } executorService.shutdownNow(); throw new IOException("Executor did not shut down cleanly (killed)"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); executorService.shutdownNow(); throw new InterruptedIOException("Interrupted while awaiting executor shutdown"); } } public void execute(final Runnable command) { executorService.execute(command); } }; } /** * Get the null closeable. This is a simple {@code Closeable} instance that does nothing when its {@code close()} * method is invoked. * * @return the null closeable */ public static Closeable nullCloseable() { return NULL_CLOSEABLE; } private static final Logger closeLog = Logger.getLogger("org.jboss.xnio.safe-close"); /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Closeable resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Socket resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final DatagramSocket resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Selector resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final ServerSocket resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final ZipFile resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Handler resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a future resource, logging an error if an error occurs. Attempts to cancel the operation if it is * still in progress. * * @param futureResource the resource to close */ public static void safeClose(final IoFuture<? extends Closeable> futureResource) { futureResource.cancel().addNotifier(closingNotifier(), null); } private static final IoFuture.Notifier<Object, Closeable> ATTACHMENT_CLOSING_NOTIFIER = new IoFuture.Notifier<Object, Closeable>() { public void notify(final IoFuture<?> future, final Closeable attachment) { IoUtils.safeClose(attachment); } }; private static final IoFuture.Notifier<Closeable, Void> CLOSING_NOTIFIER = new IoFuture.HandlingNotifier<Closeable, Void>() { public void handleDone(final Closeable result, final Void attachment) { IoUtils.safeClose(result); } }; /** * Get a notifier that closes the attachment. * * @return a notifier which will close its attachment */ public static IoFuture.Notifier<Object, Closeable> attachmentClosingNotifier() { return ATTACHMENT_CLOSING_NOTIFIER; } /** * Get a notifier that closes the result. * * @return a notifier which will close the result of the operation (if successful) */ public static IoFuture.Notifier<Closeable, Void> closingNotifier() { return CLOSING_NOTIFIER; } /** * Get a notifier that runs the supplied action. * * @param runnable the notifier type * @param <T> the future type (not used) * @return a notifier which will run the given command */ public static <T> IoFuture.Notifier<T, Void> runnableNotifier(final Runnable runnable) { return new IoFuture.Notifier<T, Void>() { public void notify(final IoFuture<? extends T> future, final Void attachment) { runnable.run(); } }; } /** * Get a {@code java.util.concurrent}-style {@code Future} instance wrapper for an {@code IoFuture} instance. * * @param ioFuture the {@code IoFuture} to wrap * @return a {@code Future} */ public static <T> Future<T> getFuture(final IoFuture<T> ioFuture) { return new Future<T>() { public boolean cancel(final boolean mayInterruptIfRunning) { ioFuture.cancel(); return ioFuture.await() == IoFuture.Status.CANCELLED; } public boolean isCancelled() { return ioFuture.getStatus() == IoFuture.Status.CANCELLED; } public boolean isDone() { return ioFuture.getStatus() == IoFuture.Status.DONE; } public T get() throws InterruptedException, ExecutionException { try { return ioFuture.getInterruptibly(); } catch (IOException e) { throw new ExecutionException(e); } } public T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { if (ioFuture.awaitInterruptibly(timeout, unit) == IoFuture.Status.WAITING) { throw new TimeoutException("Operation timed out"); } return ioFuture.getInterruptibly(); } catch (IOException e) { throw new ExecutionException(e); } } public String toString() { return String.format("java.util.concurrent.Future wrapper <%s> for %s", Integer.toHexString(hashCode()), ioFuture); } }; } private static final IoFuture.Notifier<Object, CountDownLatch> COUNT_DOWN_NOTIFIER = new IoFuture.Notifier<Object, CountDownLatch>() { public void notify(final IoFuture<?> future, final CountDownLatch latch) { latch.countDown(); } }; public static void awaitAll(IoFuture<?>... futures) { final int len = futures.length; final CountDownLatch cdl = new CountDownLatch(len); for (IoFuture<?> future : futures) { future.addNotifier(COUNT_DOWN_NOTIFIER, cdl); } boolean intr = false; try { while (cdl.getCount() > 0L) { try { cdl.await(); } catch (InterruptedException e) { intr = true; } } } finally { if (intr) { Thread.currentThread().interrupt(); } } } public static void awaitAllInterruptibly(IoFuture<?>... futures) throws InterruptedException { final int len = futures.length; final CountDownLatch cdl = new CountDownLatch(len); for (IoFuture<?> future : futures) { future.addNotifier(COUNT_DOWN_NOTIFIER, cdl); } cdl.await(); } /** * Create an {@code IoFuture} which wraps another {@code IoFuture}, but returns a different type. * * @param parent the original {@code IoFuture} * @param type the class of the new {@code IoFuture} * @param <I> the type of the original result * @param <O> the type of the wrapped result * @return a wrapper {@code IoFuture} */ public static <I, O> IoFuture<? extends O> cast(final IoFuture<I> parent, final Class<O> type) { return new CastingIoFuture<O, I>(parent, type); } // nested classes private static class CastingIoFuture<O, I> implements IoFuture<O> { private final IoFuture<I> parent; private final Class<O> type; private CastingIoFuture(final IoFuture<I> parent, final Class<O> type) { this.parent = parent; this.type = type; } public IoFuture<O> cancel() { parent.cancel(); return this; } public Status getStatus() { return parent.getStatus(); } public Status await() { return parent.await(); } public Status await(final long time, final TimeUnit timeUnit) { return parent.await(time, timeUnit); } public Status awaitInterruptibly() throws InterruptedException { return parent.awaitInterruptibly(); } public Status awaitInterruptibly(final long time, final TimeUnit timeUnit) throws InterruptedException { return parent.awaitInterruptibly(time, timeUnit); } public O get() throws IOException, CancellationException { return type.cast(parent.get()); } public O getInterruptibly() throws IOException, InterruptedException, CancellationException { return type.cast(parent.getInterruptibly()); } public IOException getException() throws IllegalStateException { return parent.getException(); } public <A> IoFuture<O> addNotifier(final Notifier<? super O, A> notifier, final A attachment) { parent.<A>addNotifier(new Notifier<I, A>() { public void notify(final IoFuture<? extends I> future, final A attachment) { notifier.notify((IoFuture<O>)CastingIoFuture.this, attachment); } }, attachment); return this; } } private static final Logger listenerLog = Logger.getLogger("org.jboss.xnio.channel-listener"); /** * Invoke a channel listener on a given channel, logging any errors. * * @param channel the channel * @param channelListener the channel listener * @param <T> the channel type * @return {@code true} if the handler completed successfully, or {@code false} if it failed */ public static <T extends Channel> boolean invokeChannelListener(T channel, ChannelListener<? super T> channelListener) { if (channelListener != null) try { channelListener.handleEvent(channel); } catch (Throwable t) { listenerLog.error(t, "A channel event listener threw an exception"); return false; } return true; } private static ChannelListener<Channel> CLOSING_CHANNEL_LISTENER = new ChannelListener<Channel>() { public void handleEvent(final Channel channel) { IoUtils.safeClose(channel); } }; /** * Get a channel listener which closes the channel when notified. * * @return the channel listener */ public static ChannelListener<Channel> closingChannelListener() { return CLOSING_CHANNEL_LISTENER; } /** * Get a setter based on an atomic reference field updater. Used by channel implementations to avoid having to * define an anonymous class for each listener field. * * @param channel the channel * @param updater the updater * @param <T> the channel type * @param <C> the holding class * @return the setter */ public static <T extends Channel, C> ChannelListener.Setter<T> getSetter(final C channel, final AtomicReferenceFieldUpdater<C, ChannelListener> updater) { return new ChannelListener.Setter<T>() { public void set(final ChannelListener<? super T> channelListener) { updater.set(channel, channelListener); } }; } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.swing; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Paint; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.text.AttributedCharacterIterator; import java.util.Map; /** * A Graphics2D that pipes all processing to two subgraphics. */ public class TGraphics2D extends Graphics2D { /** * Construct a TGraphics2D. * @param primary the primary underlying graphics. Get methods will * result in calls only to the primary Graphics2D. * @param copy the underlying graphics of lesser importance. */ public TGraphics2D (Graphics2D primary, Graphics2D copy) { _primary = primary; _copy = copy; } /** * Get the primary Graphics2D underneath us, for bypass purposes. */ public Graphics2D getPrimary () { return _primary; } @Override public void draw3DRect (int x, int y, int w, int h, boolean r) { _copy.draw3DRect(x, y, w, h, r); _primary.draw3DRect(x, y, w, h, r); } @Override public void fill3DRect (int x, int y, int w, int h, boolean r) { _copy.fill3DRect(x, y, w, h, r); _primary.fill3DRect(x, y, w, h, r); } @Override public void draw (Shape s) { _copy.draw(s); _primary.draw(s); } @Override public boolean drawImage (Image i, AffineTransform a, ImageObserver o) { _copy.drawImage(i, a, null); return _primary.drawImage(i, a, o); } @Override public void drawImage (BufferedImage i, BufferedImageOp o, int x, int y) { _copy.drawImage(i, o, x, y); _primary.drawImage(i, o, x, y); } @Override public void drawRenderedImage (RenderedImage i, AffineTransform a) { _copy.drawRenderedImage(i, a); _primary.drawRenderedImage(i, a); } @Override public void drawRenderableImage (RenderableImage i, AffineTransform a) { _copy.drawRenderableImage(i, a); _primary.drawRenderableImage(i, a); } @Override public void drawString (String s, int x, int y) { _copy.drawString(s, x, y); _primary.drawString(s, x, y); } @Override public void drawString (String s, float x, float y) { _copy.drawString(s, x, y); _primary.drawString(s, x, y); } @Override public void drawString (AttributedCharacterIterator i, int x, int y) { _copy.drawString(i, x, y); _primary.drawString(i, x, y); } @Override public void drawString (AttributedCharacterIterator i, float x, float y) { _copy.drawString(i, x, y); _primary.drawString(i, x, y); } @Override public void drawGlyphVector (GlyphVector g, float x, float y) { _copy.drawGlyphVector(g, x, y); _primary.drawGlyphVector(g, x, y); } @Override public void fill (Shape s) { _copy.fill(s); _primary.fill(s); } @Override public boolean hit (Rectangle r, Shape s, boolean x) { _copy.hit(r, s, x); return _primary.hit(r, s, x); } @Override public GraphicsConfiguration getDeviceConfiguration () { return _primary.getDeviceConfiguration(); } @Override public void setComposite (Composite c) { _copy.setComposite(c); _primary.setComposite(c); } @Override public void setPaint (Paint p) { _copy.setPaint(p); _primary.setPaint(p); } @Override public void setStroke (Stroke s) { _copy.setStroke(s); _primary.setStroke(s); } @Override public void setRenderingHint (RenderingHints.Key k, Object v) { _copy.setRenderingHint(k, v); _primary.setRenderingHint(k, v); } @Override public Object getRenderingHint (RenderingHints.Key k) { return _primary.getRenderingHint(k); } @Override public void setRenderingHints (Map<?, ?> m) { _copy.setRenderingHints(m); _primary.setRenderingHints(m); } @Override public void addRenderingHints (Map<?, ?> m) { _copy.addRenderingHints(m); _primary.addRenderingHints(m); } @Override public RenderingHints getRenderingHints () { return _primary.getRenderingHints(); } @Override public void translate (int x, int y) { _copy.translate(x, y); _primary.translate(x, y); } @Override public void translate (double x, double y) { _copy.translate(x, y); _primary.translate(x, y); } @Override public void rotate (double t) { _copy.rotate(t); _primary.rotate(t); } @Override public void rotate (double t, double u, double v) { _copy.rotate(t, u, v); _primary.rotate(t, u, v); } @Override public void scale (double x, double y) { _copy.scale(x, y); _primary.scale(x, y); } @Override public void shear (double x, double y) { _copy.shear(x, y); _primary.shear(x, y); } @Override public void transform (AffineTransform a) { _copy.transform(a); _primary.transform(a); } @Override public void setTransform (AffineTransform a) { _copy.setTransform(a); _primary.setTransform(a); } @Override public AffineTransform getTransform () { return _primary.getTransform(); } @Override public Paint getPaint () { return _primary.getPaint(); } @Override public Composite getComposite () { return _primary.getComposite(); } @Override public void setBackground (Color c) { _copy.setBackground(c); _primary.setBackground(c); } @Override public Color getBackground () { return _primary.getBackground(); } @Override public Stroke getStroke () { return _primary.getStroke(); } @Override public void clip (Shape s) { _copy.clip(s); _primary.clip(s); } @Override public FontRenderContext getFontRenderContext () { return _primary.getFontRenderContext(); } @Override public Graphics create () { return _primary.create(); } @Override public Graphics create (int x, int y, int w, int h) { return _primary.create(x, y, w, h); } @Override public Color getColor () { return _primary.getColor(); } @Override public void setColor (Color c) { _copy.setColor(c); _primary.setColor(c); } @Override public void setPaintMode () { _copy.setPaintMode(); _primary.setPaintMode(); } @Override public void setXORMode (Color c) { _copy.setXORMode(c); _primary.setXORMode(c); } @Override public Font getFont () { return _primary.getFont(); } @Override public void setFont (Font f) { _copy.setFont(f); _primary.setFont(f); } @Override public FontMetrics getFontMetrics () { return _primary.getFontMetrics(); } @Override public FontMetrics getFontMetrics (Font f) { return _primary.getFontMetrics(f); } @Override public Rectangle getClipBounds () { return _primary.getClipBounds(); } @Override public void clipRect (int x, int y, int w, int h) { _copy.clipRect(x, y, w, h); _primary.clipRect(x, y, w, h); } @Override public void setClip (int x, int y, int w, int h) { _copy.setClip(x, y, w, h); _primary.setClip(x, y, w, h); } @Override public Shape getClip () { return _primary.getClip(); } @Override public void setClip (Shape s) { _copy.setClip(s); _primary.setClip(s); } @Override public void copyArea (int x, int y, int w, int h, int a, int b) { // was seeing errors here, Don't worry about failure on copy try { _copy.copyArea(x, y, w, h, a, b); } catch (Error e) { } _primary.copyArea(x, y, w, h, a, b); } @Override public void drawLine (int x, int y, int a, int b) { _copy.drawLine(x, y, a, b); _primary.drawLine(x, y, a, b); } @Override public void fillRect (int x, int y, int w, int h) { _copy.fillRect(x, y, w, h); _primary.fillRect(x, y, w, h); } @Override public void drawRect (int x, int y, int w, int h) { _copy.drawRect(x, y, w, h); _primary.drawRect(x, y, w, h); } @Override public void clearRect (int x, int y, int w, int h) { _copy.clearRect(x, y, w, h); _primary.clearRect(x, y, w, h); } @Override public void drawRoundRect (int x, int y, int w, int h, int a, int b) { _copy.drawRoundRect(x, y, w, h, a, b); _primary.drawRoundRect(x, y, w, h, a, b); } @Override public void fillRoundRect (int x, int y, int w, int h, int a, int b) { _copy.fillRoundRect(x, y, w, h, a, b); _primary.fillRoundRect(x, y, w, h, a, b); } @Override public void drawOval (int x, int y, int w, int h) { _copy.drawOval(x, y, w, h); _primary.drawOval(x, y, w, h); } @Override public void fillOval (int x, int y, int w, int h) { _copy.fillOval(x, y, w, h); _primary.fillOval(x, y, w, h); } @Override public void drawArc (int x, int y, int w, int h, int a, int b) { _copy.drawArc(x, y, w, h, a, b); _primary.drawArc(x, y, w, h, a, b); } @Override public void fillArc (int x, int y, int w, int h, int a, int b) { _copy.fillArc(x, y, w, h, a, b); _primary.fillArc(x, y, w, h, a, b); } @Override public void drawPolyline (int[] x, int[] y, int n) { _copy.drawPolyline(x, y, n); _primary.drawPolyline(x, y, n); } @Override public void drawPolygon (int[] x, int[] y, int n) { _copy.drawPolygon(x, y, n); _primary.drawPolygon(x, y, n); } @Override public void drawPolygon (Polygon p) { _copy.drawPolygon(p); _primary.drawPolygon(p); } @Override public void fillPolygon (int[] x, int[] y, int n) { _copy.fillPolygon(x, y, n); _primary.fillPolygon(x, y, n); } @Override public void fillPolygon (Polygon p) { _copy.fillPolygon(p); _primary.fillPolygon(p); } @Override public void drawChars (char[] c, int x, int y, int w, int h) { _copy.drawChars(c, x, y, w, h); _primary.drawChars(c, x, y, w, h); } @Override public void drawBytes (byte[] b, int x, int y, int w, int h) { _copy.drawBytes(b, x, y, w, h); _primary.drawBytes(b, x, y, w, h); } @Override public boolean drawImage (Image i, int x, int y, ImageObserver o) { _copy.drawImage(i, x, y, null); return _primary.drawImage(i, x, y, o); } @Override public boolean drawImage ( Image i, int x, int y, int w, int h, ImageObserver o) { _copy.drawImage(i, x, y, w, h, null); return _primary.drawImage(i, x, y, w, h, o); } @Override public boolean drawImage (Image i, int x, int y, Color c, ImageObserver o) { _copy.drawImage(i, x, y, c, null); return _primary.drawImage(i, x, y, c, o); } @Override public boolean drawImage ( Image i, int x, int y, int w, int h, Color c, ImageObserver o) { _copy.drawImage(i, x, y, w, h, c, null); return _primary.drawImage(i, x, y, w, h, c, o); } @Override public boolean drawImage ( Image i, int x, int y, int w, int h, int a, int b, int c, int d, ImageObserver o) { _copy.drawImage(i, x, y, w, h, a, b, c, d, null); return _primary.drawImage(i, x, y, w, h, a, b, c, d, o); } @Override public boolean drawImage ( Image i, int x, int y, int w, int h, int a, int b, int c, int d, Color k, ImageObserver o) { _copy.drawImage(i, x, y, w, h, a, b, c, d, k, null); return _primary.drawImage(i, x, y, w, h, a, b, c, d, k, o); } @Override public void dispose () { _copy.dispose(); _primary.dispose(); } @Override public void finalize () { // We don't want to have our super's finalize called because that will end up calling // dispose() which we don't want. } @Override public String toString () { return _primary.toString(); } @Override @Deprecated public Rectangle getClipRect () { // getClipRect is deprecated, but getClipBounds is the new way to do the same thing. We // call that to avoid deprecation warnings. return _primary.getClipBounds(); } @Override public boolean hitClip (int x, int y, int w, int h) { return _primary.hitClip(x, y, w, h); } @Override public Rectangle getClipBounds (Rectangle r) { return _primary.getClipBounds(r); } protected Graphics2D _primary, _copy; }
package fr.jayasoft.ivy.ant; import fr.jayasoft.ivy.Ivy; import fr.jayasoft.ivy.ModuleDescriptor; import fr.jayasoft.ivy.ModuleId; import fr.jayasoft.ivy.DependencyDescriptor; import fr.jayasoft.ivy.util.Message; import fr.jayasoft.ivy.xml.XmlModuleDescriptorParser; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.types.FileList; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Iterator; import java.util.HashSet; import java.util.Set; public class IvyBuildList extends IvyTask { private List _buildFiles = new ArrayList(); // List (FileSet) private String _reference; private boolean _haltOnError = true; private boolean _skipBuildWithoutIvy = false; private boolean _reverse = false; private String _ivyFilePath; private String _root; public void addFileset(FileSet buildFiles) { _buildFiles.add(buildFiles); } public String getReference() { return _reference; } public void setReference(String reference) { _reference = reference; } public String getRoot() { return _root; } public void setRoot(String root) { _root = root; } public void execute() throws BuildException { if (_reference == null) { throw new BuildException("reference should be provided in ivy build list"); } if (_buildFiles.isEmpty()) { throw new BuildException("at least one nested fileset should be provided in ivy build list"); } _ivyFilePath = getProperty(_ivyFilePath, getIvyInstance(), "ivy.buildlist.ivyfilepath"); Path path = new Path(getProject()); Map buildFiles = new HashMap(); // Map (ModuleDescriptor -> File buildFile) Collection mds = new ArrayList(); List independent = new ArrayList(); ModuleDescriptor rootModuleDescriptor = null; for (ListIterator iter = _buildFiles.listIterator(); iter.hasNext();) { FileSet fs = (FileSet)iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] builds = ds.getIncludedFiles(); for (int i = 0; i < builds.length; i++) { File buildFile = new File(ds.getBasedir(), builds[i]); File ivyFile = getIvyFileFor(buildFile); if (!ivyFile.exists()) { if (_skipBuildWithoutIvy) { Message.debug("skipping "+buildFile+": ivy file "+ivyFile+" doesn't exist"); } else { Message.verbose("no ivy file for "+buildFile+": ivyfile="+ivyFile+": adding it at the beginning of the path"); Message.verbose("\t(set skipbuildwithoutivy to true if you don't want this file to be added to the path)"); independent.add(buildFile); } } else { try { ModuleDescriptor md = XmlModuleDescriptorParser.parseDescriptor(getIvyInstance(), ivyFile.toURL(), isValidate()); buildFiles.put(md, buildFile); mds.add(md); if (_root != null && _root.equals(md.getModuleRevisionId().getName())) { rootModuleDescriptor = md; } } catch (Exception ex) { if (_haltOnError) { throw new BuildException("impossible to parse ivy file for "+buildFile+": ivyfile="+ivyFile+" exception="+ex.getMessage(), ex); } else { Message.warn("impossible to parse ivy file for "+buildFile+": ivyfile="+ivyFile+" exception="+ex.getMessage()); Message.info("\t=> adding it at the beginning of the path"); independent.add(buildFile); } } } } } if (_root != null && rootModuleDescriptor == null) { throw new BuildException("unable to find root module " + _root + " in build fileset"); } if (rootModuleDescriptor != null) { Message.info("Filtering modules based on root " + rootModuleDescriptor.getModuleRevisionId().getName()); mds = filterModules(mds, rootModuleDescriptor); } List sortedModules = Ivy.sortModuleDescriptors(mds); for (ListIterator iter = independent.listIterator(); iter.hasNext();) { File buildFile = (File)iter.next(); addBuildFile(path, buildFile); } if (isReverse()) { Collections.reverse(sortedModules); } for (ListIterator iter = sortedModules.listIterator(); iter.hasNext();) { ModuleDescriptor md = (ModuleDescriptor)iter.next(); File buildFile = (File)buildFiles.get(md); addBuildFile(path, buildFile); } getProject().addReference(getReference(), path); } /** * Returns a collection of ModuleDescriptors that are conatined in the input * collection of ModuleDescriptors and upon which the root module depends * * @param mds input collection of ModuleDescriptors * @param rootmd root module * @return filtered list of modules */ private Collection filterModules(Collection mds, ModuleDescriptor rootmd) { // Make a map of ModuleId objects -> ModuleDescriptors Map moduleIdMap = new HashMap(); for (Iterator iter = mds.iterator(); iter.hasNext();) { ModuleDescriptor md = ((ModuleDescriptor) iter.next()); moduleIdMap.put(md.getModuleRevisionId().getModuleId(), md); } // recursively process the nodes Set toKeep = new HashSet(); processFilterNode(rootmd, toKeep, moduleIdMap); // just for logging for (Iterator iter = toKeep.iterator(); iter.hasNext();) { ModuleDescriptor md = ((ModuleDescriptor) iter.next()); Message.verbose("Kept module " + md.getModuleRevisionId().getModuleId().getName()); } return toKeep; } /** * Adds the current node to the toKeep collection and then processes the each of the direct dependencies * of this node that appear in the moduleIdMap (indicating that the dependency is part of this BuildList) * * @param node the node to be processed * @param toKeep the set of ModuleDescriptors that should be kept * @param moduleIdMap reference mapping of moduleId to ModuleDescriptor that are part of the BuildList */ private void processFilterNode(ModuleDescriptor node, Set toKeep, Map moduleIdMap) { toKeep.add(node); DependencyDescriptor[] deps = node.getDependencies(); for (int i=0; i<deps.length; i++) { ModuleId id = deps[i].getDependencyId(); if (moduleIdMap.get(id) != null) { processFilterNode((ModuleDescriptor) moduleIdMap.get(id), toKeep, moduleIdMap); } } } private void addBuildFile(Path path, File buildFile) { FileList fl = new FileList(); fl.setDir(buildFile.getParentFile()); FileList.FileName fileName = new FileList.FileName(); fileName.setName(buildFile.getName()); fl.addConfiguredFile(fileName); path.addFilelist(fl); } private File getIvyFileFor(File buildFile) { return new File(buildFile.getParentFile(), _ivyFilePath); } public boolean isHaltonerror() { return _haltOnError; } public void setHaltonerror(boolean haltOnError) { _haltOnError = haltOnError; } public String getIvyfilepath() { return _ivyFilePath; } public void setIvyfilepath(String ivyFilePath) { _ivyFilePath = ivyFilePath; } public boolean isSkipbuildwithoutivy() { return _skipBuildWithoutIvy; } public void setSkipbuildwithoutivy(boolean skipBuildFilesWithoutIvy) { _skipBuildWithoutIvy = skipBuildFilesWithoutIvy; } public boolean isReverse() { return _reverse; } public void setReverse(boolean reverse) { _reverse = reverse; } }
// Inner class for a Namespace node. package org.jaxen.dom; import org.jaxen.pattern.Pattern; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; /** * Extension DOM2 node type for a namespace node. * * <p>This class implements the DOM2 {@link Node} interface to * allow namespace nodes to be included in the result * set of an XPath selectNodes operation, even though DOM2 does * not model namespaces in scope as separate nodes.</p> * * <p>While all of the methods are implemented with reasonable * defaults, there will be some unexpected surprises, so users are * advised to test for NamespaceNodes and filter them out from the * result sets as early as possible:</p> * * <ol> * * <li>The {@link #getNodeType} method returns {@link #NAMESPACE_NODE}, * which is not one of the usual DOM2 node types. Generic code may * fall unexpectedly out of switch statements, for example.</li> * * <li>The {@link #getOwnerDocument} method returns the owner document * of the parent node, but that owner document will know nothing about * the namespace node.</p> * * <li>The {@link #isSupported} method always returns false.</li> * * </ol> * * <p>All attempts to modify a <code>NamespaceNode</code> will fail with a {@link * DOMException} ({@link * DOMException#NO_MODIFICATION_ALLOWED_ERR}).</p> * * @author David Megginson * @see DocumentNavigator */ public class NamespaceNode implements Node { // Constants. /** * Constant: this is a NamespaceNode. * * @see #getNodeType */ public final static short NAMESPACE_NODE = Pattern.NAMESPACE_NODE; // Protected Constructors. /** * Constructor. * * @param parent the DOM node to which the namespace is attached * @param name the namespace prefix * @param value the namespace URI */ public NamespaceNode (Node parent, String name, String value) { this.parent = parent; this.name = name; this.value = value; } /** * Constructor. * * @param parent the DOM node to which the namespace is attached * @param attribute the DOM attribute object containing the * namespace declaration */ NamespaceNode (Node parent, Node attribute) { String name = attribute.getNodeName(); if (name.equals("xmlns")) { this.name = ""; } else if (name.startsWith("xmlns:")) { this.name = name.substring(6); // the part after "xmlns:" } else { // workaround for Crimson bug; Crimson incorrectly reports the prefix as the node name this.name = name; } this.parent = parent; this.value = attribute.getNodeValue(); } // Implementation of org.w3c.dom.Node. /** * Get the namespace prefix. * * @return the namespace prefix, or "" for the default namespace */ public String getNodeName () { return name; } /** * Get the namespace URI. * * @return the namespace URI */ public String getNodeValue () { return value; } /** * Change the namespace URI (always fails). * * @param value the new URI * @throws DOMException always */ public void setNodeValue (String value) throws DOMException { disallowModification(); } /** * Get the node type. * * @return always {@link #NAMESPACE_NODE}. */ public short getNodeType () { return NAMESPACE_NODE; } /** * Get the parent node. * * <p>This method returns the element that was queried for Namespaces * in effect, <em>not</em> necessarily the actual element containing * the Namespace declaration.</p> * * @return the parent node (not null) */ public Node getParentNode () { return parent; } /** * Get the list of child nodes. * * @return an empty node list */ public NodeList getChildNodes () { return new EmptyNodeList(); } /** * Get the first child node. * * @return null */ public Node getFirstChild () { return null; } /** * Get the last child node. * * @return null */ public Node getLastChild () { return null; } /** * Get the previous sibling node. * * @return null */ public Node getPreviousSibling () { return null; } /** * Get the next sibling node. * * @return null */ public Node getNextSibling () { return null; } /** * Get the attribute nodes. * * @return null */ public NamedNodeMap getAttributes () { return null; } /** * Get the owner document. * * @return the owner document <em>of the parent node</em> */ public Document getOwnerDocument () { // FIXME: this could cause confusion return (parent == null ? null : parent.getOwnerDocument()); } /** * Insert a new child node (always fails). * * @param newChild the node to add * @param oldChild ignored * @return never * @throws DOMException always * @see Node#insertBefore */ public Node insertBefore (Node newChild, Node refChild) throws DOMException { disallowModification(); return null; } /** * Replace a child node (always fails). * * @param newChild the node to add * @param oldChild the child node to replace * @return never * @throws DOMException always * @see Node#replaceChild */ public Node replaceChild (Node newChild, Node oldChild) throws DOMException { disallowModification(); return null; } /** * Remove a child node (always fails). * * @param oldChild the child node to remove * @return never * @throws DOMException always * @see Node#removeChild */ public Node removeChild (Node oldChild) throws DOMException { disallowModification(); return null; } /** * Append a new child node (always fails). * * @param newChild the node to add * @return never * @throws DOMException always * @see Node#appendChild */ public Node appendChild (Node newChild) throws DOMException { disallowModification(); return null; } /** * Test for child nodes. * * @return false */ public boolean hasChildNodes () { return false; } /** * Create a copy of this node. * * @param deep make a deep copy (no effect, since namespace nodes * don't have children). * @return a new copy of this namespace node */ public Node cloneNode (boolean deep) { return new NamespaceNode(parent, name, value); } /** * Normalize the text descendants of this node. * * <p>This method has no effect, since Namespace nodes have no * descendants.</p> */ public void normalize () { // no op } /** * Test if a DOM2 feature is supported. * * @param feature the feature name * @param version the feature version * @return false */ public boolean isSupported (String feature, String version) { return false; } /** * Get the namespace URI of this node. * * <p>Namespace declarations are not themselves * Namespace-qualified.</p> * * @return null */ public String getNamespaceURI () { return null; } /** * Get the namespace prefix of this node. * * <p>Namespace declarations are not themselves * namespace-qualified.</p> * * @return null * @see #getLocalName */ public String getPrefix () { return null; } /** * Change the namespace prefix of this node (always fails). * * @param prefix the new prefix * @throws DOMException always thrown */ public void setPrefix (String prefix) throws DOMException { disallowModification(); } /** * Get the XPath name of the namespace node;; i.e. the * namespace prefix. * * @return the namespace prefix */ public String getLocalName () { return name; } /** * Test if this node has attributes. * * @return false */ public boolean hasAttributes () { return false; } /** * Throw a NO_MODIFICATION_ALLOWED_ERR DOMException. * * @throws DOMException always thrown */ private void disallowModification () throws DOMException { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "Namespace node may not be modified"); } // Override default methods from java.lang.Object. /** * Generate a hash code for a namespace node. * * @return a hash code for this node */ public int hashCode () { return hashCode(parent) + hashCode(name) + hashCode(value); } /** * Test for equivalence with another object. * * <p>Two Namespace nodes are considered equivalent if their parents, * names, and values are equal.</p> * * @param o the object to test for equality * @return true if the object is equivalent to this node, false * otherwise */ public boolean equals (Object o) { if (o == this) return true; else if (o == null) return false; else if (o instanceof NamespaceNode) { NamespaceNode ns = (NamespaceNode)o; return (equals(parent, ns.getParentNode()) && equals(name, ns.getNodeName()) && equals(value, ns.getNodeValue())); } else { return false; } } /** * Helper method for generating a hash code. * * @param o the object for generating a hash code (possibly null) * @return the object's hash code, or 0 if the object is null * @see java.lang.Object#hashCode */ private int hashCode (Object o) { return (o == null ? 0 : o.hashCode()); } /** * Helper method for comparing two objects. * * @param a the first object to compare (possibly null) * @param b the second object to compare (possibly null) * @return true if the objects are equivalent or are both null * @see java.lang.Object#equals */ private boolean equals (Object a, Object b) { return ((a == null && b == null) || (a != null && a.equals(b))); } // Internal state. private Node parent; private String name; private String value; // Inner class: empty node list. /** * A node list with no members. * * <p>This class is necessary for the {@link Node#getChildNodes} * method, which must return an empty node list rather than * null when there are no children.</p> */ private static class EmptyNodeList implements NodeList { /** * @see NodeList#getLength */ public int getLength () { return 0; } /** * @see NodeList#item */ public Node item(int index) { return null; } } public String getBaseURI() { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public short compareDocumentPosition(Node other) throws DOMException { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public String getTextContent() throws DOMException { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public void setTextContent(String textContent) throws DOMException { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public boolean isSameNode(Node other) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public String lookupPrefix(String namespaceURI) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public boolean isDefaultNamespace(String namespaceURI) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public String lookupNamespaceURI(String prefix) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public boolean isEqualNode(Node arg) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public Object getFeature(String feature, String version) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public Object setUserData(String key, Object data, UserDataHandler handler) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } public Object getUserData(String key) { throw new UnsupportedOperationException("Changing interfaces in a JDK blows chunks!"); } } // end of Namespace.java
package net.sf.samtools.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Encapsulates file representation of various primitive data types. Forces little-endian disk representation. * Note that this class is currently not very efficient. There are plans to increase the size of the ByteBuffer, * and move data between the ByteBuffer and the underlying input or output stream in larger chunks. * * All the read methods throw RuntimeEOFException if the input stream is exhausted before the required number * of bytes are read. * * @author Dave Tefft */ public class BinaryCodec { //Outstream to write to private OutputStream outputStream; //If a file or filename was given it will be stored here. Used for error reporting. private String outputFileName; //Input stream to read from private InputStream inputStream; //If a file or filename was give to read from it will be stored here. Used for error reporting. private String inputFileName; /* Mode that the BinaryCodec is in. It is either writing to a binary file or reading from. This is set to true if it is writing to a binary file Right now we don't support reading and writing to the same file with the same BinaryCodec instance */ private boolean isWriting; /** * For byte swapping. */ private ByteBuffer byteBuffer; /** * For reading Strings of known length, this can reduce object creation */ private final byte[] scratchBuffer = new byte[16]; // Byte order used in BAM files. private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; private static final byte NULL_BYTE[] = {0}; private static final long MAX_UBYTE = (Byte.MAX_VALUE * 2) + 1; private static final long MAX_USHORT = (Short.MAX_VALUE * 2) + 1; private static final long MAX_UINT = ((long)Integer.MAX_VALUE * 2) + 1; // We never serialize more than this much at a time (except for Strings) private static final int MAX_BYTE_BUFFER = 8; // Constructors // /** * Constructs BinaryCodec from a file and set it's mode to writing or not * * @param file file to be written to or read from * @param writing whether the file is being written to */ public BinaryCodec(final File file, final boolean writing) { this(); try { this.isWriting = writing; if (this.isWriting) { this.outputStream = new FileOutputStream(file); this.outputFileName = file.getName(); } else { this.inputStream = new FileInputStream(file); this.inputFileName = file.getName(); } } catch (FileNotFoundException e) { throw new RuntimeIOException("File not found: " + file, e); } } /** * Constructs BinaryCodec from a file name and set it's mode to writing or not * * @param fileName name of the file to be written to or read from * @param writing writing whether the file is being written to */ public BinaryCodec(final String fileName, final boolean writing) { this(new File(fileName), writing); } /** * Constructs BinaryCodec from an output stream * * @param outputStream Stream to write to, since it's an output stream we know that isWriting * should be set to true */ public BinaryCodec(final OutputStream outputStream) { this(); setOutputStream(outputStream); } /** * Constructs BinaryCodec from an input stream * * @param inputStream Stream to read from, since we are reading isWriting is set to false */ public BinaryCodec(final InputStream inputStream) { this(); setInputStream(inputStream); } /** * Ambiguous whether reading or writing until set{In,Out}putStream is called */ public BinaryCodec() { initByteBuffer(); } /** * Shared among ctors. * Note that if endianness is changed, all the unsigned methods must also be changed. */ private void initByteBuffer() { byteBuffer = ByteBuffer.allocate(MAX_BYTE_BUFFER); byteBuffer.order(LITTLE_ENDIAN); } // Writing methods // /** * Write whatever has been put into the byte buffer * @param numBytes -- how much to write. Note that in case of writing an unsigned value, * more bytes were put into the ByteBuffer than will get written out. */ private void writeByteBuffer(final int numBytes) { assert(numBytes <= byteBuffer.limit()); writeBytes(byteBuffer.array(), 0, numBytes); } /** * Writes a byte to the output buffer * * @param bite byte array to write */ public void writeByte(final byte bite) { byteBuffer.clear(); byteBuffer.put(bite); writeByteBuffer(1); } public void writeByte(final int b) { writeByte((byte)b); } /** * Writes a byte array to the output buffer * * @param bytes value to write */ public void writeBytes(final byte[] bytes) { writeBytes(bytes, 0, bytes.length); } public void writeBytes(final byte[] bytes, final int startOffset, final int numBytes) { if (!isWriting) { throw new IllegalStateException("Calling write method on BinaryCodec open for read."); } try { outputStream.write(bytes, startOffset, numBytes); } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Write error"), e); } } /** * Write a 32-bit int to the output stream * * @param value int to write */ public void writeInt(final int value) { byteBuffer.clear(); byteBuffer.putInt(value); writeByteBuffer(4); } /** * Write a double (8 bytes) to the output stream * * @param value double to write */ public void writeDouble(final double value) { byteBuffer.clear(); byteBuffer.putDouble(value); writeByteBuffer(8); } /** * Write a 64-bit long to the output stream * * @param value long to write */ public void writeLong(final long value) { byteBuffer.clear(); byteBuffer.putLong(value); writeByteBuffer(8); } /** * Write a 16-bit short to output stream */ public void writeShort(final short value) { byteBuffer.clear(); byteBuffer.putShort(value); writeByteBuffer(2); } /** * Write a float (4 bytes) to the output stream * * @param value float to write */ public void writeFloat(final float value) { byteBuffer.clear(); byteBuffer.putFloat(value); writeByteBuffer(4); } /** * Writes a boolean (1 byte) to the output buffer * * @param value boolean to write */ public void writeBoolean(final boolean value) { byteBuffer.clear(); byteBuffer.put(value ? (byte)1 : (byte)0); writeByteBuffer(1); } /** * Writes a string to the buffer as ASCII bytes * * @param value string to write to buffer * @param writeLength prefix the string with the length as a 32-bit int * @param appendNull add a null byte to the end of the string */ public void writeString(final String value, final boolean writeLength, final boolean appendNull) { if (writeLength) { int lengthToWrite = value.length(); if (appendNull) lengthToWrite++; writeInt(lengthToWrite); } //Actually writes the string to a buffer writeString(value); if (appendNull) writeBytes(NULL_BYTE); } /** * Write a string to the buffer as ASCII bytes * * @param value string to write */ private void writeString(final String value) { writeBytes(StringUtil.stringToBytes(value)); } /** * Write an 8-bit unsigned byte. * NOTE: This method will break if we change to big-endian. */ public void writeUByte(final short val) { if (val < 0) { throw new IllegalArgumentException("Negative value (" + val + ") passed to unsigned writing method."); } if (val > MAX_UBYTE) { throw new IllegalArgumentException("Value (" + val + ") to large to be written as ubyte."); } byteBuffer.clear(); byteBuffer.putShort(val); writeByteBuffer(1); } /** * Write a 16-bit unsigned short. * NOTE: This method will break if we change to big-endian. */ public void writeUShort(final int val) { if (val < 0) { throw new IllegalArgumentException("Negative value (" + val + ") passed to unsigned writing method."); } if (val > MAX_USHORT) { throw new IllegalArgumentException("Value (" + val + ") to large to be written as ushort."); } byteBuffer.clear(); byteBuffer.putInt(val); writeByteBuffer(2); } /** * Write a 32-bit unsigned int. * NOTE: This method will break if we change to big-endian. */ public void writeUInt(final long val) { if (val < 0) { throw new IllegalArgumentException("Negative value (" + val + ") passed to unsigned writing method."); } if (val > MAX_UINT) { throw new IllegalArgumentException("Value (" + val + ") to large to be written as uint."); } byteBuffer.clear(); byteBuffer.putLong(val); writeByteBuffer(4); } // Reading methods // /** * Read a byte array from the input stream. * * @throws net.sf.samtools.util.RuntimeEOFException if fewer than buffer.length bytes to read */ public void readBytes(final byte[] buffer) { readBytes(buffer, 0, buffer.length); } /** * Read a byte array from the input stream * * @param buffer where to put bytes read * @param offset offset to start putting bytes into buffer * @param length number of bytes to read * @throws RuntimeEOFException if fewer than length bytes to read */ public void readBytes(final byte[] buffer, final int offset, final int length) { int totalNumRead = 0; do { final int numRead = readBytesOrFewer(buffer, offset + totalNumRead, length - totalNumRead); if (numRead < 0) { throw new RuntimeEOFException(constructErrorMessage("Premature EOF")); } else { totalNumRead += numRead; } } while (totalNumRead < length); } /** * Reads a byte array from the input stream. * * @param buffer where to put bytes read * @param offset offset to start putting bytes into buffer * @param length number of bytes to read. Fewer bytes may be read if EOF is reached before length bytes * have been read. * @return the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. */ public int readBytesOrFewer(final byte[] buffer, final int offset, final int length) { if (isWriting) { throw new IllegalStateException("Calling read method on BinaryCodec open for write."); } try { return inputStream.read(buffer, offset, length); } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Read error"), e); } } /** * @return a single byte read from the input stream. */ public byte readByte() { if (isWriting) { throw new IllegalStateException("Calling read method on BinaryCodec open for write."); } try { final int ret = inputStream.read(); if (ret == -1) { throw new RuntimeEOFException(constructErrorMessage("Premature EOF")); } return (byte)ret; } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Read error"), e); } } /** * @return true if it is possible to know for sure if at EOF, and it is known for sure. * If the input stream is a ByteArrayInputStream, this is faster than causing a RuntimeEOFException * to be thrown. */ public boolean knownAtEof() { if (isWriting) { throw new IllegalStateException("Calling knownAtEof method on BinaryCodec open for write."); } try { return inputStream instanceof ByteArrayInputStream && inputStream.available() == 0; } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("available() error"), e); } } /** * Read a string off the input stream, as ASCII bytes * * @param length length of string to read * @return String read from stream */ public String readString(final int length) { final byte[] buffer; // Recycle single buffer if possible if (length <= scratchBuffer.length) { buffer = scratchBuffer; } else { buffer = new byte[length]; } readBytes(buffer, 0, length); return StringUtil.bytesToString(buffer, 0, length); } /** * Read ASCII bytes from the input stream until a null byte is read * @return String constructed from the ASCII bytes read */ public String readNullTerminatedString() { return StringUtil.readNullTerminatedString(this); } /** * Read an int length, and then a String of that length * @param devourNull if true, the length include a null terminator, which is read and discarded */ public String readLengthAndString(final boolean devourNull) { int length = readInt(); if (devourNull) { --length; } final String ret = readString(length); if (devourNull) { readByte(); } return ret; } private void readByteBuffer(final int numBytes) { assert(numBytes <= byteBuffer.capacity()); readBytes(byteBuffer.array(), 0, numBytes); byteBuffer.limit(byteBuffer.capacity()); byteBuffer.position(numBytes); } /** * Read an int off the input stream * * @return int from input stream */ public int readInt() { readByteBuffer(4); byteBuffer.flip(); return byteBuffer.getInt(); } /** * Reads a double off the input stream * * @return double */ public double readDouble() { readByteBuffer(8); byteBuffer.flip(); return byteBuffer.getDouble(); } /** * Reads a long off the input stream * * @return long */ public long readLong() { readByteBuffer(8); byteBuffer.flip(); return byteBuffer.getLong(); } public short readShort() { readByteBuffer(2); byteBuffer.flip(); return byteBuffer.getShort(); } /** * Reads a float off the input stream * * @return float */ public float readFloat() { readByteBuffer(4); byteBuffer.flip(); return byteBuffer.getFloat(); } /** * Reads a boolean off the input stream, represented as a byte with value 1 or 0 * * @return boolean */ public boolean readBoolean() { return (((int)readByte()) == 1); } /** * Reads an 8-bit unsigned byte from the input stream. * This method assumes little-endianness. */ public short readUByte() { readByteBuffer(1); byteBuffer.put((byte)0); byteBuffer.flip(); return byteBuffer.getShort(); } /** * Reads a 16-bit unsigned short from the input stream. * This method assumes little-endianness. */ public int readUShort() { readByteBuffer(2); byteBuffer.putShort((short)0); byteBuffer.flip(); return byteBuffer.getInt(); } /** * Reads a 32-bit unsigned int from the input stream. * This method assumes little-endianness. */ public long readUInt() { readByteBuffer(4); byteBuffer.putInt(0); byteBuffer.flip(); return byteBuffer.getLong(); } /** * Close the appropriate stream */ public void close() { try { if (this.isWriting) { // To the degree possible, make sure the bytes get forced to the file system, // or else cause an exception to be thrown. if (this.outputStream instanceof FileOutputStream) { this.outputStream.flush(); FileOutputStream fos = (FileOutputStream)this.outputStream; fos.getFD().sync(); } this.outputStream.close(); } else this.inputStream.close(); } catch (IOException e) { throw new RuntimeIOException(e.getMessage(), e); } } private String constructErrorMessage(final String msg) { final StringBuilder sb = new StringBuilder(msg); sb.append("; BinaryCodec in "); sb.append(isWriting? "write": "read"); sb.append("mode; "); final String filename = isWriting? outputFileName: inputFileName; if (filename != null) { sb.append("file: "); sb.append(filename); } else { sb.append("streamed file (filename not available)"); } return sb.toString(); } // Some getters // public String getInputFileName() { return inputFileName; } public String getOutputFileName() { return outputFileName; } public void setOutputFileName(final String outputFileName) { this.outputFileName = outputFileName; } public void setInputFileName(final String inputFileName) { this.inputFileName = inputFileName; } public boolean isWriting() { return isWriting; } public OutputStream getOutputStream() { return outputStream; } public InputStream getInputStream() { return inputStream; } public void setInputStream(final InputStream is) { isWriting = false; this.inputStream = is; } public void setOutputStream(final OutputStream os) { isWriting = true; this.outputStream = os; } }
package nl.jpoint.vertx.mod.cluster.aws; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.List; public class AwsAutoScalingUtilTest { private final static String ACCESS_KEY = "ak"; private final static String SECRET_ACCESS_KEY = "sak"; private final static String AS_GROUP_ID = "gid"; private final static String INSTANCE_ID = "iid"; private final static String ELB = "elb"; AwsAutoScalingUtil util = new AwsAutoScalingUtil(ACCESS_KEY, SECRET_ACCESS_KEY); AwsElbUtil elbUtil = new AwsElbUtil(ACCESS_KEY, SECRET_ACCESS_KEY, "eu-west-1", ELB, INSTANCE_ID); @Test @Ignore public void testElbInstanceState() throws AwsException { AwsState state = elbUtil.getInstanceState(); Assert.assertEquals(AwsState.INSERVICE, state); } @Test @Ignore public void testListInstancesInGroup() throws AwsException { List<String> result = util.listInstancesInGroup(""); Assert.assertEquals(1, result.size()); } @Test @Ignore public void testListLoadBalancersInGroup() throws AwsException { List<String> result = util.listLoadBalancers(AS_GROUP_ID); Assert.assertEquals(1, result.size()); } @Test @Ignore public void testFetchInstanceState() throws AwsException { AwsState result = util.getInstanceState(INSTANCE_ID,AS_GROUP_ID); Assert.assertEquals(AwsState.INSERVICE, result); } @Test @Ignore public void testEnterStandby() throws AwsException { util.enterStandby(INSTANCE_ID,AS_GROUP_ID); } @Test @Ignore public void testExitStandby() throws AwsException { util.exitStandby(INSTANCE_ID,AS_GROUP_ID); } }
package nl.b3p.viewer.util; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import nl.b3p.viewer.config.app.ApplicationLayer; import nl.b3p.viewer.config.app.ConfiguredAttribute; import nl.b3p.viewer.config.services.AttributeDescriptor; import nl.b3p.viewer.config.services.FeatureTypeRelation; import nl.b3p.viewer.config.services.FeatureTypeRelationKey; import nl.b3p.viewer.config.services.SimpleFeatureType; import static nl.b3p.viewer.stripes.FeatureInfoActionBean.FID; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.factory.CommonFactoryFinder; import org.geotools.factory.GeoTools; import org.geotools.feature.FeatureIterator; import org.geotools.filter.text.cql2.CQL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opengis.feature.simple.SimpleFeature; import org.opengis.filter.Filter; import org.opengis.filter.FilterFactory2; import org.opengis.filter.sort.SortBy; import org.opengis.filter.sort.SortOrder; /** * * @author Roy Braam */ public class FeatureToJson { private boolean arrays = false; private boolean edit = false; private static final int TIMEOUT=5000; public FeatureToJson(boolean arrays,boolean edit){ this.arrays=arrays; this.edit=edit; } /** * Get the features as JSONArray with the given params * @param al The application layer(if there is a application layer) * @param ft The featuretype that must be used to get the features * @param fs The featureSource * @param q The query * @param sort The attribute name that is used to sort * @param dir Sort direction (DESC or ASC) * @return JSONArray with features. * @throws IOException * @throws JSONException * @throws Exception */ public JSONArray getJSONFeatures(ApplicationLayer al,SimpleFeatureType ft, FeatureSource fs, Query q, String sort, String dir) throws IOException, JSONException, Exception{ Map<String,String> attributeAliases = new HashMap<String,String>(); if(!edit) { for(AttributeDescriptor ad: ft.getAttributes()) { if(ad.getAlias() != null) { attributeAliases.put(ad.getName(), ad.getAlias()); } } } List<String> propertyNames; if(al != null) { propertyNames = this.setPropertyNames(al, q, ft,edit); } else { propertyNames = new ArrayList<String>(); for(AttributeDescriptor ad: ft.getAttributes()) { propertyNames.add(ad.getName()); } } if (sort!=null){ setSortBy(q, propertyNames, sort, dir); } FeatureIterator<SimpleFeature> it = null; JSONArray features = new JSONArray(); try{ it=fs.getFeatures(q).features(); while(it.hasNext()){ SimpleFeature feature = it.next(); JSONObject j = this.toJSONFeature(new JSONObject(),feature,ft,al,propertyNames,attributeAliases,0); if (j!=null){ features.put(j); } } }finally{ it.close(); fs.getDataStore().dispose(); } return features; } private JSONObject toJSONFeature(JSONObject j,SimpleFeature f, SimpleFeatureType ft, ApplicationLayer al, List<String> propertyNames,Map<String,String> attributeAliases, int index) throws JSONException, Exception{ if(arrays) { for(String name: propertyNames) { Object value = f.getAttribute(name); j.put("c" + index++, formatValue(value)); } } else { for(String name: propertyNames) { String alias = null; if (attributeAliases!=null){ alias=attributeAliases.get(name); } j.put(alias != null ? alias : name, formatValue(f.getAttribute(name))); } } //if edit and not yet set if(edit && j.optString(FID,null)==null) { String id = f.getID(); j.put(FID, id); } if (ft.hasRelations()){ j = populateWithRelatedFeatures(j,f,ft,al,index); } return j; } /** * Populate the json object with related featues */ private JSONObject populateWithRelatedFeatures(JSONObject j,SimpleFeature feature,SimpleFeatureType ft,ApplicationLayer al, int index) throws Exception{ if (ft.hasRelations()){ JSONArray related_featuretypes = new JSONArray(); for (FeatureTypeRelation rel :ft.getRelations()){ boolean isJoin=rel.getType().equals(FeatureTypeRelation.JOIN); if (isJoin){ FeatureSource foreignFs = rel.getForeignFeatureType().openGeoToolsFeatureSource(TIMEOUT); FeatureIterator<SimpleFeature> foreignIt=null; try{ Query foreignQ = new Query(foreignFs.getName().toString()); //create filter Filter filter = createFilter(feature,rel); if (filter==null){ continue; } //if join only get 1 feature foreignQ.setMaxFeatures(1); //set propertynames List<String> propertyNames; if (al!=null){ propertyNames=setPropertyNames(al, foreignQ, rel.getForeignFeatureType(), edit); }else{ propertyNames = new ArrayList<String>(); for(AttributeDescriptor ad: rel.getForeignFeatureType().getAttributes()) { propertyNames.add(ad.getName()); } } //get aliases Map<String,String> attributeAliases = new HashMap<String,String>(); if(!edit) { for(AttributeDescriptor ad: rel.getForeignFeatureType().getAttributes()) { if(ad.getAlias() != null) { attributeAliases.put(ad.getName(), ad.getAlias()); } } } //Get Feature and populate JSON object with the values. foreignIt=foreignFs.getFeatures(foreignQ).features(); while (foreignIt.hasNext()){ SimpleFeature foreignFeature = foreignIt.next(); //join it in the same json j= toJSONFeature(j,foreignFeature, rel.getForeignFeatureType(), al,propertyNames,attributeAliases,index); } }finally{ if (foreignIt!=null){ foreignIt.close(); } foreignFs.getDataStore().dispose(); } }else{ Filter filter = createFilter(feature,rel); if (filter==null){ continue; } JSONObject related_ft = new JSONObject(); related_ft.put("filter", CQL.toCQL(filter)); related_ft.put("id",rel.getForeignFeatureType().getId()); related_featuretypes.put(related_ft); } } if (related_featuretypes.length()>0){ j.put("related_featuretypes",related_featuretypes); } } return j; } HashMap<Long,List<String>> propertyNamesQueryCache = new HashMap<Long,List<String>>(); HashMap<Long,Boolean> haveInvisiblePropertiesCache = new HashMap<Long,Boolean>(); HashMap<Long,List<String>> propertyNamesReturnCache = new HashMap<Long,List<String>>(); /** * Get the propertynames and add the needed propertynames to the query. */ private List<String> setPropertyNames(ApplicationLayer appLayer, Query q, SimpleFeatureType sft,boolean edit) { List<String> propertyNames = new ArrayList<String>(); boolean haveInvisibleProperties = false; if (propertyNamesQueryCache.containsKey(sft.getId())){ haveInvisibleProperties= haveInvisiblePropertiesCache.get(sft.getId()); if(haveInvisibleProperties){ q.setPropertyNames(propertyNamesQueryCache.get(sft.getId())); } return propertyNamesReturnCache.get(sft.getId()); }else{ for(ConfiguredAttribute ca: appLayer.getAttributes(sft)) { if((!edit && ca.isVisible()) || (edit && ca.isEditable())) { propertyNames.add(ca.getAttributeName()); } else { haveInvisibleProperties = true; } } haveInvisiblePropertiesCache.put(sft.getId(),haveInvisibleProperties); propertyNamesReturnCache.put(sft.getId(),propertyNames); propertyNamesQueryCache.put(sft.getId(),propertyNames); if(haveInvisibleProperties) { // By default Query retrieves Query.ALL_NAMES // Query.NO_NAMES is an empty String array q.setPropertyNames(propertyNames); // If any related featuretypes are set, add the leftside names in the query // don't add them to propertynames, maybe they are not visible if (sft.getRelations()!=null){ List<String> withRelations= new ArrayList<String>(); withRelations.addAll(propertyNames); for (FeatureTypeRelation ftr : sft.getRelations()){ if (ftr.getRelationKeys()!=null){ for (FeatureTypeRelationKey key : ftr.getRelationKeys()){ if (!withRelations.contains(key.getLeftSide().getName())){ withRelations.add(key.getLeftSide().getName()); } } } } propertyNamesQueryCache.put(sft.getId(), withRelations); q.setPropertyNames(withRelations); } } propertyNamesReturnCache.put(sft.getId(),propertyNames); return propertyNames; } } /** * Set sort order */ private void setSortBy(Query q, List<String> propertyNames, String sort, String dir) { FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints()); if(sort != null) { String sortAttribute = null; if(arrays) { int i = Integer.parseInt(sort.substring(1)); int j = 0; for(String name: propertyNames) { if(j == i) { sortAttribute = name; } j++; } } else { sortAttribute = sort; } if(sortAttribute != null) { q.setSortBy(new SortBy[] { ff2.sort(sortAttribute, "DESC".equals(dir) ? SortOrder.DESCENDING : SortOrder.ASCENDING) }); } } } private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); private Object formatValue(Object value) { if(value instanceof Date) { // JSON has no date type so format the date as it is used for // display, not calculation return dateFormat.format((Date)value); } else { return value; } } private Filter createFilter(SimpleFeature feature,FeatureTypeRelation rel) { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); List<Filter> filters = new ArrayList<Filter>(); for (FeatureTypeRelationKey key : rel.getRelationKeys()){ AttributeDescriptor rightSide = key.getRightSide(); AttributeDescriptor leftSide = key.getLeftSide(); Object value= feature.getAttribute(leftSide.getName()); if (value==null){ continue; } if (AttributeDescriptor.GEOMETRY_TYPES.contains(rightSide.getType()) && AttributeDescriptor.GEOMETRY_TYPES.contains(leftSide.getType())){ filters.add(ff.not(ff.isNull(ff.property(rightSide.getName())))); filters.add(ff.intersects(ff.property(rightSide.getName()),ff.literal(value))); }else{ filters.add(ff.equals(ff.property(rightSide.getName()),ff.literal(value))); } } if (filters.size()>1){ return ff.and(filters); }else if (filters.size()==1){ return filters.get(0); }else{ return null; } } }
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.sentdetect; import opennlp.maxent.Event; /** * An Event which can hold a pointer to another Event for use in a * linked list. * * Created: Sat Oct 27 11:53:55 2001 * * @author Eric D. Friedman * @version $Id: SDEvent.java,v 1.2 2006/01/19 01:01:29 joernkottmann Exp $ */ class SDEvent extends Event { private static final long serialVersionUID = 1; SDEvent next; SDEvent(String oc, String[] c) { super(oc,c); } }
package info.bitrich.xchangestream.kraken; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import info.bitrich.xchangestream.kraken.dto.KrakenSubscriptionConfig; import info.bitrich.xchangestream.kraken.dto.KrakenSubscriptionMessage; import info.bitrich.xchangestream.kraken.dto.KrakenSubscriptionStatusMessage; import info.bitrich.xchangestream.kraken.dto.KrakenSystemStatus; import info.bitrich.xchangestream.kraken.dto.enums.KrakenEventType; import info.bitrich.xchangestream.kraken.dto.enums.KrakenSubscriptionName; import info.bitrich.xchangestream.service.netty.JsonNettyStreamingService; import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import static info.bitrich.xchangestream.kraken.dto.enums.KrakenEventType.subscribe; /** * @author makarid, pchertalev */ public class KrakenStreamingService extends JsonNettyStreamingService { private static final Logger LOG = LoggerFactory.getLogger(KrakenStreamingService.class); private static final String EVENT = "event"; private final Map<Integer, String> channels = new ConcurrentHashMap<>(); private ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); private final Map<Integer, String> subscriptionRequestMap = new ConcurrentHashMap<>(); public KrakenStreamingService(String apiUrl) { super(apiUrl, Integer.MAX_VALUE); } @Override public boolean processArrayMassageSeparately() { return false; } @Override protected void handleMessage(JsonNode message) { String channelName = getChannel(message); try { JsonNode event = message.get(EVENT); KrakenEventType krakenEvent; if (event != null && (krakenEvent = KrakenEventType.getEvent(event.textValue())) != null) { switch (krakenEvent) { case heartbeat: LOG.debug("Heartbeat received"); break; case systemStatus: KrakenSystemStatus systemStatus = mapper.treeToValue(message, KrakenSystemStatus.class); LOG.info("System status: {}", systemStatus); break; case subscriptionStatus: KrakenSubscriptionStatusMessage statusMessage = mapper.treeToValue(message, KrakenSubscriptionStatusMessage.class); channelName = subscriptionRequestMap.remove(statusMessage.getReqid()); switch (statusMessage.getStatus()) { case subscribed: LOG.info("Channel {} has been subscribed", channelName); channels.put(statusMessage.getChannelID(), channelName); break; case unsubscribed: LOG.info("Channel {} has been unsubscribed", channelName); channels.remove(statusMessage.getChannelID()); break; case error: LOG.error("Channel {} has been failed: {}", channelName, statusMessage.getErrorMessage()); } break; default: LOG.warn("Unexpected event type has been received: {}", krakenEvent); } return; } } catch (JsonProcessingException e) { LOG.error("Error reading message: {}", e.getMessage(), e); } if (!message.isArray() || channelName == null) { LOG.error("Unknown message: {}", message.asText()); return; } super.handleMessage(message); } @Override protected String getChannelNameFromMessage(JsonNode message) throws IOException { String channelName = null; if (message.has("channelID")) { channelName = channels.get(message.get("channelID").asInt()); } if (message.isArray() && message.get(0).isInt()) { channelName = channels.get(message.get(0).asInt()); } if (LOG.isDebugEnabled()) { LOG.debug("ChannelName {}", StringUtils.isBlank(channelName) ? "not defined" : channelName); } return channelName; } @Override public String getSubscribeMessage(String channelName, Object... args) throws IOException { String [] channelData = channelName.split(KrakenStreamingMarketDataService.KRAKEN_CHANNEL_DELIMITER); String pair = channelData[1]; KrakenSubscriptionName subscriptionName = KrakenSubscriptionName.valueOf(channelData[0]); Integer depth = null; if (args.length > 0 && args[0] != null) { depth = (Integer) args[0]; } int reqID = Math.abs(UUID.randomUUID().hashCode()); subscriptionRequestMap.put(reqID, channelName); KrakenSubscriptionMessage subscriptionMessage = new KrakenSubscriptionMessage(reqID, subscribe, Collections.singletonList(pair), new KrakenSubscriptionConfig(subscriptionName, depth)); return objectMapper.writeValueAsString(subscriptionMessage); } @Override public String getUnsubscribeMessage(String channelName) throws IOException { String [] channelData = channelName.split(KrakenStreamingMarketDataService.KRAKEN_CHANNEL_DELIMITER); String pair = channelData[1]; KrakenSubscriptionName subscriptionName = KrakenSubscriptionName.valueOf(channelData[0]); int reqID = Math.abs(UUID.randomUUID().hashCode()); subscriptionRequestMap.put(reqID, channelName); KrakenSubscriptionMessage subscriptionMessage = new KrakenSubscriptionMessage(reqID, KrakenEventType.unsubscribe, Collections.singletonList(pair), new KrakenSubscriptionConfig(subscriptionName)); return objectMapper.writeValueAsString(subscriptionMessage); } }
package org.apache.lenya.cms.ac; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.log4j.Category; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Hashtable; import java.util.Properties; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; /** * @author egli * * */ public class LDAPUser extends FileUser { private static Properties defaultProperties = null; private static Category log = Category.getInstance(LDAPUser.class); public static final String LDAP_ID = "ldapid"; private static String PROVIDER_URL = "provider-url"; private static String MGR_DN = "mgr-dn"; private static String MGR_PW = "mgr-pw"; private static String PARTIAL_USER_DN = "partial-user-dn"; private static String KEY_STORE = "key-store"; private static String SECURITY_PROTOCOL = "security-protocol"; private static String SECURITY_AUTHENTICATION = "security-authentication"; private String ldapId; private String ldapName; /** * Creates a new LDAPUser object. */ public LDAPUser() { } /** * Creates a new LDAPUser object. * @param configurationDirectory The configuration directory. */ public LDAPUser(File configurationDirectory) { setConfigurationDirectory(configurationDirectory); } /** * Create an LDAPUser * * @param configurationDirectory * where the user will be attached to * @param id * user id of LDAPUser * @param email * of LDAPUser * @param ldapId * of LDAPUser * @throws ConfigurationException * if the properties could not be read */ public LDAPUser(File configurationDirectory, String id, String email, String ldapId) throws ConfigurationException { super(configurationDirectory, id, null, email, null); this.ldapId = ldapId; initialize(); } /** * Create a new LDAPUser from a configuration * * @param config * the <code>Configuration</code> specifying the user details * @throws ConfigurationException * if the user could not be instantiated */ public void configure(Configuration config) throws ConfigurationException { super.configure(config); ldapId = config.getChild(LDAP_ID).getValue(); initialize(); } /** * Checks if a user exists. * @param ldapId * @return * @throws AccessControlException */ public boolean existsUser(String ldapId) throws AccessControlException { boolean exists = false; LdapContext context = null; try { readProperties(); context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW)); String peopleName = "ou=People"; Attributes attributes = new BasicAttributes("uid", ldapId); NamingEnumeration enumeration = context.search(peopleName, attributes); exists = enumeration.hasMoreElements(); } catch (Exception e) { throw new AccessControlException("Exception during search: ", e); } finally { try { if (context != null) { close(context); } } catch (NamingException e) { throw new AccessControlException("Closing context failed: ", e); } } return exists; } /** * Initializes this user. * * @throws ConfigurationException * when something went wrong. */ protected void initialize() throws ConfigurationException { LdapContext context = null; try { readProperties(); String name = null; context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW)); String[] attrs = new String[1]; attrs[0] = "gecos"; /* users full name */ String searchString = "uid=" + ldapId + ",ou=People"; Attributes answer = context.getAttributes(searchString, attrs); if (answer != null) { Attribute attr = answer.get("gecos"); if (attr != null) { for (NamingEnumeration enum = attr.getAll(); enum.hasMore(); enum.next()) { name = (String) attr.get(); } } } this.ldapName = name; } catch (Exception e) { throw new ConfigurationException("Could not read properties", e); } finally { try { if (context != null) { close(context); } } catch (NamingException e) { throw new ConfigurationException("Closing context failed: ", e); } } } /** * (non-Javadoc) * * @see org.apache.lenya.cms.ac.FileUser#createConfiguration() */ protected Configuration createConfiguration() { DefaultConfiguration config = (DefaultConfiguration) super.createConfiguration(); // add ldap_id node DefaultConfiguration child = new DefaultConfiguration(LDAP_ID); child.setValue(ldapId); config.addChild(child); return config; } /** * Get the ldap id * * @return the ldap id */ public String getLdapId() { return ldapId; } /** * Set the ldap id * * @param string * the new ldap id */ public void setLdapId(String string) { ldapId = string; } /** * (non-Javadoc) * * @see org.apache.lenya.cms.ac.User#authenticate(java.lang.String) */ public boolean authenticate(String password) { String principal = "uid=" + getLdapId() + "," + defaultProperties.getProperty(PARTIAL_USER_DN); Context ctx; log.debug("Authenticating with principal [" + principal + "]"); try { ctx = bind(principal, password); close(ctx); log.debug("Context closed."); } catch (NamingException e) { // log this failure // StringWriter writer = new StringWriter(); // e.printStackTrace(new PrintWriter(writer)); log.info("Bind for user " + principal + " to Ldap server failed: ", e); } return true; } /** * @see org.apache.lenya.cms.ac.Item#getName() */ public String getName() { return ldapName; } /** * LDAP Users fetch their name information from the LDAP server, so we don't store it locally. * Since we only have read access we basically can't set the name, i.e. any request to change * the name is ignored. * * @param string * is ignored */ public void setName(String string) { // we do not have write access to LDAP, so we ignore // change request to the name. } /** * The LDAPUser doesn't store any passwords as they are handled by LDAP * * @param plainTextPassword * is ignored */ public void setPassword(String plainTextPassword) { setEncryptedPassword(null); } /** * The LDAPUser doesn't store any passwords as they are handled by LDAP * * @param encryptedPassword * is ignored */ protected void setEncryptedPassword(String encryptedPassword) { encryptedPassword = null; } /** * Connect to the LDAP server * * @param principal * the principal string for the LDAP connection * @param credentials * the credentials for the LDAP connection * @return a <code>LdapContext</code> * @throws NamingException * if there are problems establishing the Ldap connection */ private LdapContext bind(String principal, String credentials) throws NamingException { log.info("Binding principal: [" + principal + "]"); Hashtable env = new Hashtable(); System.setProperty( "javax.net.ssl.trustStore", getConfigurationDirectory().getAbsolutePath() + File.separator + defaultProperties.getProperty(KEY_STORE)); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, defaultProperties.getProperty(PROVIDER_URL)); env.put(Context.SECURITY_PROTOCOL, defaultProperties.getProperty(SECURITY_PROTOCOL)); env.put( Context.SECURITY_AUTHENTICATION, defaultProperties.getProperty(SECURITY_AUTHENTICATION)); env.put(Context.SECURITY_PRINCIPAL, principal); env.put(Context.SECURITY_CREDENTIALS, credentials); LdapContext ctx = new InitialLdapContext(env, null); log.info("Finished binding principal."); return ctx; } /** * Close the connection to the LDAP server * * @param ctx * the context that was returned from the bind * @throws NamingException * if there is a problem communicating to the LDAP server */ private void close(Context ctx) throws NamingException { ctx.close(); } /** * Read the properties * * @throws IOException * if the properties cannot be found. */ private void readProperties() throws IOException { // create and load default properties File propertiesFile = new File(getConfigurationDirectory(), "ldap.properties"); if (defaultProperties == null) { defaultProperties = new Properties(); FileInputStream in; in = new FileInputStream(propertiesFile); defaultProperties.load(in); in.close(); } } }
package org.xwiki.test.ui; import java.util.List; import org.apache.commons.configuration.PropertiesConfiguration; import org.junit.runner.RunWith; import org.xwiki.test.integration.XWikiExecutor; import org.xwiki.test.integration.XWikiExecutorSuite; /** * Runs all functional tests found in the classpath. * * @version $Id$ * @since 2.3M1 */ @RunWith(PageObjectSuite.class) public class AllTests { @XWikiExecutorSuite.PreStart public void preStart(List<XWikiExecutor> executors) throws Exception { XWikiExecutor executor = executors.get(0); PropertiesConfiguration propertiesConfiguration = executor.loadXWikiPropertiesConfiguration(); // Skip the distribution wizard. propertiesConfiguration.setProperty("extension.distribution.skipWizard", true); executor.saveXWikiProperties(propertiesConfiguration); } }
package org.concord.otrunk.view; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import org.concord.applesupport.AppleApplicationAdapter; import org.concord.applesupport.AppleApplicationUtil; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeListener; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.view.OTExternalAppService; import org.concord.framework.otrunk.view.OTFrameManager; import org.concord.framework.otrunk.view.OTJComponentServiceFactory; import org.concord.framework.otrunk.view.OTUserListService; import org.concord.framework.otrunk.view.OTViewContainer; import org.concord.framework.otrunk.view.OTViewContainerChangeEvent; import org.concord.framework.otrunk.view.OTViewContainerListener; import org.concord.framework.otrunk.view.OTViewContext; import org.concord.framework.otrunk.view.OTViewFactory; import org.concord.framework.text.UserMessageHandler; import org.concord.framework.util.SimpleTreeNode; import org.concord.otrunk.OTMLToXHTMLConverter; import org.concord.otrunk.OTObjectServiceImpl; import org.concord.otrunk.OTStateRoot; import org.concord.otrunk.OTSystem; import org.concord.otrunk.OTrunkImpl; import org.concord.otrunk.OTrunkServiceEntry; import org.concord.otrunk.datamodel.OTDataObject; import org.concord.otrunk.datamodel.OTDatabase; import org.concord.otrunk.user.OTUserObject; import org.concord.otrunk.xml.ExporterJDOM; import org.concord.otrunk.xml.XMLDatabase; import org.concord.otrunk.xml.XMLDatabaseChangeEvent; import org.concord.otrunk.xml.XMLDatabaseChangeListener; import org.concord.swing.CustomDialog; import org.concord.swing.MemoryMonitorPanel; import org.concord.swing.MostRecentFileDialog; import org.concord.swing.StreamRecord; import org.concord.swing.StreamRecordView; import org.concord.swing.util.Util; import org.concord.view.SimpleTreeModel; import org.concord.view.SwingUserMessageHandler; /** * OTViewer Class name and description * * Date created: Dec 14, 2004 * * @author scott * <p> * */ public class OTViewer extends JFrame implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter { /** * first version of this class */ private static final long serialVersionUID = 1L; public final static String TITLE_PROP = "otrunk.view.frame_title"; public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree"; public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console"; public final static String HTTP_PUT = "PUT"; public final static String HTTP_POST = "POST"; private static OTrunkImpl otrunk; private static OTViewFactory otViewFactory; protected int userMode = OTConfig.NO_USER_MODE; OTUserObject currentUser = null; URL currentURL = null; String baseFrameTitle = "OTrunk Viewer"; OTViewContainerPanel bodyPanel; OTFrameManagerImpl frameManager; JTree folderTreeArea; SimpleTreeModel folderTreeModel; JTree dataTreeArea; SimpleTreeModel dataTreeModel; JSplitPane splitPane; JFrame consoleFrame; // Temp, to close the window AbstractAction exitAction; AbstractAction saveAsAction; JMenuBar menuBar; XMLDatabase xmlDB; XMLDatabase userDataDB; File currentAuthoredFile = null; File currentUserFile = null; Hashtable otContainers = new Hashtable(); String startupMessage = ""; boolean justStarted = false; boolean showTree = false; URL remoteURL; private AbstractAction saveUserDataAsAction; private AbstractAction saveUserDataAction; private AbstractAction debugAction; private AbstractAction showConsoleAction; private AbstractAction newUserDataAction; private AbstractAction loadUserDataAction; private AbstractAction loadAction; private AbstractAction reloadWindowAction; private AbstractAction saveAction; private AbstractAction saveRemoteAsAction; private AbstractAction exportImageAction; private AbstractAction exportHiResImageAction; private AbstractAction exportToHtmlAction; private JDialog commDialog; /** * This is true if the user was asked about saving user data after they * initiated a close of the current view. */ private boolean askedAboutSavingUserData = false; /** * This is true if the user was asked about saving the user data, and said * yes */ private boolean needToSaveUserData = false; private boolean useScrollPane; private OTChangeListener systemChangeListener; private OTSystem userSystem; private ArrayList services = new ArrayList(); private JPanel statusPanel; public final static String ANON_SINGLE_USER_NAME = "anon_single_user"; public static void setOTViewFactory(OTViewFactory factory) { otViewFactory = factory; } public OTViewer() { super(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.out.println("Error setting native LAF: " + e); } this.showTree = true; AppleApplicationUtil.registerWithMacOSX(this); try { // this overrides the default base frame title String title = System.getProperty(TITLE_PROP, null); if (title != null) { baseFrameTitle = title; } } catch (Throwable t) { // do nothing, just use the default title } setTitle(baseFrameTitle); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exitAction.actionPerformed(null); } }); consoleFrame = new JFrame("Console"); StreamRecord record = new StreamRecord(50000); StreamRecordView view = new StreamRecordView(record); consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); System.setOut((PrintStream) view.addOutputStream(System.out, "Console")); System.setErr((PrintStream) view.addOutputStream(System.err, System.out)); consoleFrame.getContentPane().add(view); consoleFrame.setSize(800, 600); if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) { consoleFrame.setVisible(true); } commDialog = new JDialog(this, true); // for debugging // add a breakpoint below, run in debugging mode, and then hit Meta-B // the object you're currently focused on will be passed in here and you // can // start exploring the data structures, etc. KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){ public boolean dispatchKeyEvent(KeyEvent e) { if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED) && ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0) && (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) { Object o = e.getSource(); System.out.println(o.toString()); return true; } return false; } }; focusManager.addKeyEventDispatcher(deleteDispatcher); // If the mouse click is a real right click event and alt is pressed // then this code will print // out the toString method of the object which the mouse is over. AWTEventListener awtEventListener = new AWTEventListener(){ public void eventDispatched(AWTEvent event) { if(!(event instanceof MouseEvent)){ return; } MouseEvent mEvent = (MouseEvent) event; if (mEvent.getID() == MouseEvent.MOUSE_CLICKED && (mEvent.getButton() == MouseEvent.BUTTON3) && (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) { System.out.println(event.getSource().toString()); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.MOUSE_EVENT_MASK); } /** * this needs to be called before initialized. * * @param serviceInterface * @param service */ public void addService(Class serviceInterface, Object service) { OTrunkServiceEntry entry = new OTrunkServiceEntry(service, serviceInterface); services.add(entry); } public void setUserMode(int mode) { userMode = mode; } public int getUserMode() { return userMode; } public void updateTreePane() { Dimension minimumSize = new Dimension(100, 50); folderTreeArea = new JTree(folderTreeModel); // we are just disabling this however if we want to // use this tree for authoring, or for managing student // created objects this will need to be some form of option folderTreeArea.setEditable(false); folderTreeArea.addTreeSelectionListener(this); JComponent leftComponent = null; JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea); if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) { // ViewFactory.getComponent(root); dataTreeArea = new JTree(dataTreeModel); dataTreeArea.setEditable(false); dataTreeArea.addTreeSelectionListener(this); JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Folders", folderTreeScrollPane); tabbedPane.add("Resources", dataTreeScrollPane); // Provide minimum sizes for the two components in the split pane folderTreeScrollPane.setMinimumSize(minimumSize); dataTreeScrollPane.setMinimumSize(minimumSize); tabbedPane.setMinimumSize(minimumSize); leftComponent = tabbedPane; } else { leftComponent = folderTreeScrollPane; } if (splitPane == null) { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel); } else { splitPane.setLeftComponent(leftComponent); } splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(200); } public void initArgs(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { currentAuthoredFile = new File(authorOTMLURL.getPath()); } String urlStr = authorOTMLURL.toString(); initWithWizard(urlStr); } /** * @param args * @return */ public String getURL(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { try { URI authorOTMLURI = new URI(authorOTMLURL.toString()); currentAuthoredFile = new File(authorOTMLURI); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return authorOTMLURL.toString(); } public void init(String url) { updateRemoteURL(url); createActions(); updateMenuBar(); setJMenuBar(menuBar); frameManager = new OTFrameManagerImpl(); bodyPanel = new OTViewContainerPanel(frameManager); bodyPanel.addViewContainerListener(this); if (showTree) { dataTreeModel = new SimpleTreeModel(); folderTreeModel = new SimpleTreeModel(); updateTreePane(); getContentPane().add(splitPane); } else { getContentPane().add(bodyPanel); } if (OTConfig.isShowStatus()) { statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1)); final JLabel saveStateLabel = new JLabel("File saved"); statusPanel.add(saveStateLabel); statusPanel.add(Box.createHorizontalStrut(20)); statusPanel.add(new MemoryMonitorPanel()); statusPanel.add(Box.createHorizontalStrut(5)); getContentPane().add(statusPanel, BorderLayout.SOUTH); // It takes a while for xmlDM to be initialized... Thread waitForDB = new Thread() { public void run() { while (xmlDB == null) { try { sleep(1000); } catch (Exception e) { } } xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() { public void stateChanged(XMLDatabaseChangeEvent e) { if (xmlDB.isDirty()) { saveStateLabel.setText("Unsaved changes"); } else { saveStateLabel.setText("File saved"); } statusPanel.repaint(); } }); } }; waitForDB.start(); } SwingUtilities.invokeLater(new Runnable() { public void run() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if (screenSize.width < 1000 || screenSize.height < 700) { setVisible(true); int state = getExtendedState(); // Set the maximized bits state |= Frame.MAXIMIZED_BOTH; // Maximize the frame setExtendedState(state); } else { int cornerX = 100; int cornerY = 100; int sizeX = 725; int sizeY = 500; // OTViewService viewService = otViewFactory. setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); setVisible(true); } } }); if (url == null) { return; } try { initializeURL(new URL(url)); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { // FIXME: this should popup a dialog System.err.println("Can't load url"); e.printStackTrace(); return; } } public void initializeURL(URL url) throws Exception { loadURL(url); OTMainFrame mainFrame = (OTMainFrame) otrunk.getService(OTMainFrame.class); if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false) || !mainFrame.getShowLeftPanel()) { splitPane.getLeftComponent().setVisible(false); } useScrollPane = true; if (mainFrame.getFrame() != null) { if (mainFrame.getFrame().isResourceSet("width") && mainFrame.getFrame().isResourceSet("height")) { int cornerX = 100; int cornerY = 100; int sizeX = mainFrame.getFrame().getWidth(); int sizeY = mainFrame.getFrame().getHeight(); setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); repaint(); } useScrollPane = mainFrame.getFrame().getUseScrollPane(); } bodyPanel.setUseScrollPane(useScrollPane); setupBodyPanel(); } public void initWithWizard(String url) { justStarted = true; init(url); if (userMode == OTConfig.SINGLE_USER_MODE) { SwingUtilities.invokeLater(new Runnable() { public void run() { instructionPanel(); } }); } } public void loadUserDataFile(File file) { currentUserFile = file; try { loadUserDataURL(file.toURL(), file.getName()); } catch (Exception e) { e.printStackTrace(); } } public void loadUserDataURL(URL url, String name) throws Exception { XMLDatabase db = new XMLDatabase(url); db.loadObjects(); loadUserDataDb(db, name); } public void loadUserDataDb(XMLDatabase db, String name) throws Exception { userDataDB = db; currentUser = otrunk.registerUserDataDatabase(userDataDB, name); reloadWindow(); } public void reloadOverlays() { try { otrunk.reloadOverlays(currentUser, userDataDB); reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadFile(File file) { currentAuthoredFile = file; try { initializeURL(currentAuthoredFile.toURL()); } catch (Exception e) { e.printStackTrace(); } } public void loadURL(URL url) throws Exception { XMLDatabase systemDB = null; try { // try loading in the system object if there is one String systemOtmlUrlStr = OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP); if(systemOtmlUrlStr != null){ URL systemOtmlUrl = new URL(systemOtmlUrlStr); systemDB = new XMLDatabase(systemOtmlUrl, System.out); // don't track the resource info on the system db. systemDB.loadObjects(); } } catch (Exception e){ e.printStackTrace(); systemDB = null; } try { xmlDB = new XMLDatabase(url, System.out); // Only track the resource info when there isn't a user. Currently // all classroom uses // of OTViewer has NO_USER_MODE turned off, so using this setting // safe to test // the resource tracking without affecting real users. if (userMode == OTConfig.NO_USER_MODE) { xmlDB.setTrackResourceInfo(true); } xmlDB.loadObjects(); } catch (org.jdom.input.JDOMParseException e) { String xmlWarningTitle = "XML Decoding error"; String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n" + "Please show this error message to one of the workshop leaders. \n\n" + e.getMessage(); JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle, JOptionPane.ERROR_MESSAGE); throw e; } addService(UserMessageHandler.class, new SwingUserMessageHandler(this)); otrunk = new OTrunkImpl(systemDB, xmlDB, services); OTViewFactory myViewFactory = (OTViewFactory) otrunk.getService(OTViewFactory.class); if (myViewFactory != null) { otViewFactory = myViewFactory; } OTViewContext factoryContext = otViewFactory.getViewContext(); factoryContext.addViewService(OTrunk.class, otrunk); factoryContext.addViewService(OTFrameManager.class, frameManager); factoryContext.addViewService(OTJComponentServiceFactory.class, new OTJComponentServiceFactoryImpl()); factoryContext.addViewService(OTExternalAppService.class, new OTExternalAppServiceImpl()); factoryContext.addViewService(OTUserListService.class, new OTUserListService() { public Vector getUserList() { return otrunk.getUsers(); } }); currentURL = url; } // This method was refactored out of loadURL private void setupBodyPanel() throws Exception { bodyPanel.setTopLevelContainer(true); bodyPanel.setOTViewFactory(otViewFactory); // set the current mode from the viewservice to the main bodyPanel // bodyPanel.setViewMode(otViewFactory.getDefaultMode()); // set the viewFactory of the frame manager frameManager.setViewFactory(otViewFactory); xmlDB.setDirty(false); reloadWindow(); } public OTObject getAuthoredRoot() throws Exception { String rootLocalId = OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP); if(rootLocalId != null){ OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId); return otrunk.getOTObject(rootID); } return otrunk.getRoot(); } public OTObject getRoot() throws Exception { switch (userMode) { case OTConfig.NO_USER_MODE: return getAuthoredRoot(); case OTConfig.SINGLE_USER_MODE: if (userDataDB == null) { return null; } OTObject otRoot = getAuthoredRoot(); return otrunk.getUserRuntimeObject(otRoot, currentUser); } return null; } private void reloadWindow() throws Exception { OTObject root = getRoot(); boolean overrideShowTree = false; if (userMode == OTConfig.SINGLE_USER_MODE) { if (root == null) { // FIXME This is an error // the newAnonUserData should have been called before this // method is // called // no user file has been started yet overrideShowTree = true; } else { OTObject realRoot = otrunk.getRealRoot(); if (realRoot instanceof OTSystem) { OTSystem localUserSystem = (OTSystem) otrunk.getUserRuntimeObject(realRoot, currentUser); // FIXME there should be a better way than this because we // have to handle // multiple users. if (localUserSystem != userSystem) { userSystem = localUserSystem; systemChangeListener = new OTChangeListener() { public void stateChanged(OTChangeEvent e) { if ("overlays".equals(e.getProperty())) { reloadOverlays(); } } }; userSystem.addOTChangeListener(systemChangeListener); } } } } if (showTree && !overrideShowTree) { OTDataObject rootDataObject = xmlDB.getRoot(); dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk)); folderTreeModel.setRoot(new OTFolderNode(root)); } bodyPanel.setCurrentObject(root); if (showTree && !overrideShowTree) { folderTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) folderTreeModel.getRoot())); dataTreeModel.fireTreeStructureChanged(new TreePath( (SimpleTreeNode) dataTreeModel.getRoot())); } Frame frame = (Frame) SwingUtilities.getRoot(this); switch (userMode) { case OTConfig.NO_USER_MODE: if (remoteURL != null) { frame.setTitle(baseFrameTitle + ": " + remoteURL.toString()); } else { frame.setTitle(baseFrameTitle + ": " + currentURL.toString()); } break; case OTConfig.SINGLE_USER_MODE: if (currentUserFile != null) { frame.setTitle(baseFrameTitle + ": " + currentUserFile.toString()); } else if (System.getProperty(TITLE_PROP, null) != null) { frame.setTitle(baseFrameTitle); } else if (userDataDB != null) { frame.setTitle(baseFrameTitle + ": Untitled"); } else { frame.setTitle(baseFrameTitle); } break; } saveUserDataAction.setEnabled(userDataDB != null); saveUserDataAsAction.setEnabled(userDataDB != null); } public void reload() throws Exception { initializeURL(currentURL); } public OTDatabase getUserDataDb() { return userDataDB; } /** * You should call reloadWindow after calling this method to make sure the * display reflects this change * * @param userObject */ public void setCurrentUser(OTUserObject userObject) { currentUser = userObject; } public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); OTViewer viewer = new OTViewer(); if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) { viewer.setUserMode(OTConfig.SINGLE_USER_MODE); } else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) { viewer.setUserMode(OTConfig.NO_USER_MODE); } viewer.initArgs(args); } class ExitAction extends AbstractAction { /** * nothing to serialize here. */ private static final long serialVersionUID = 1L; public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent e) { // If this suceeds then the VM will exit so // the window will get disposed exit(); } } /* * (non-Javadoc) * * @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer) */ public void currentObjectChanged(OTViewContainerChangeEvent evt) { final OTViewContainer myContainer = (OTViewContainer) evt.getSource(); // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable() { public void run() { OTObject currentObject = myContainer.getCurrentObject(); if (folderTreeArea != null) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; if (node.getPfObject() != currentObject) { folderTreeArea.setSelectionPath(null); } } } }); } /* * (non-Javadoc) * * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) */ public void valueChanged(TreeSelectionEvent event) { if (event.getSource() == folderTreeArea) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; OTObject pfObject = node.getPfObject(); bodyPanel.setCurrentObject(pfObject); if (splitPane.getRightComponent() != bodyPanel) { splitPane.setRightComponent(bodyPanel); } } else if (event.getSource() == dataTreeArea) { SimpleTreeNode node = (SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent(); Object resourceValue = null; if (node != null) { resourceValue = node.getObject(); if (resourceValue == null) { resourceValue = "null resource value"; } } else { resourceValue = "no selected data object"; } JComponent nodeView = null; if (resourceValue instanceof OTDataObject) { nodeView = new OTDataObjectView((OTDataObject) resourceValue); } else { nodeView = new JTextArea(resourceValue.toString()); } JScrollPane scrollPane = new JScrollPane(nodeView); splitPane.setRightComponent(scrollPane); } } private void updateRemoteURL(String defaultURL) { String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null); try { if (remote == null) { if (defaultURL.startsWith("http:")) { remoteURL = new URL(defaultURL); } } else { remoteURL = new URL(remote); } } catch (Exception e) { remoteURL = null; System.err.println("Remote URL is invalid."); e.printStackTrace(); } } public void remoteSaveData(String method) throws Exception { HttpURLConnection urlConn; DataOutputStream urlDataOut; BufferedReader urlDataIn; // If method isn't "POST" or "PUT", throw an exception if (!(method.compareTo(OTViewer.HTTP_POST) == 0 || method.compareTo(OTViewer.HTTP_PUT) == 0)) { throw new Exception("Invalid HTTP Request method for data saving"); } urlConn = (HttpURLConnection) remoteURL.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setRequestProperty("Content-Type", "application/xml"); // Send POST output. urlDataOut = new DataOutputStream(urlConn.getOutputStream()); ExporterJDOM.export(urlDataOut, xmlDB.getRoot(), xmlDB); urlDataOut.flush(); urlDataOut.close(); // Get response data. urlDataIn = new BufferedReader(new InputStreamReader(new DataInputStream( urlConn.getInputStream()))); String str; String response = ""; while (null != ((str = urlDataIn.readLine()))) { response += str + "\n"; } urlDataIn.close(); // Need to trap non-HTTP 200/300 responses and throw an exception (if an // exception isn't thrown already) and capture the exceptions upstream int code = urlConn.getResponseCode(); if (code >= 400) { throw new Exception("HTTP Response: " + urlConn.getResponseMessage() + "\n\n" + response); } urlConn.disconnect(); xmlDB.setDirty(false); setTitle(remoteURL.toString()); } public void createActions() { newUserDataAction = new AbstractAction("New") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { createNewUser(); } }; loadUserDataAction = new AbstractAction("Open...") { /** * nothing to serialize here. Just the parent class. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { openUserData(); } }; exportToHtmlAction = new AbstractAction("Export to html...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent arg0) { File fileToSave = getReportFile(); OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer()); otxc.setXHTMLParams(fileToSave, 800, 600); (new Thread(otxc)).start(); } }; // Isn't it enabled by default? exportToHtmlAction.setEnabled(true); saveUserDataAction = new AbstractAction("Save") { /** * Nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if (currentUserFile == null || !currentUserFile.exists()) { saveUserDataAsAction.actionPerformed(arg0); return; } if (currentUserFile.exists()) { try { ExporterJDOM.export(currentUserFile, userDataDB.getRoot(), userDataDB); userDataDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } } }; saveUserDataAsAction = new AbstractAction("Save As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentUserFile != null) { mrfd.setCurrentDirectory(currentUserFile.getParentFile()); mrfd.setSelectedFile(currentUserFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); currentUserFile = file; if (!fileName.toLowerCase().endsWith(".otml")) { currentUserFile = new File(currentUserFile.getAbsolutePath() + ".otml"); } try { ExporterJDOM.export(currentUserFile, userDataDB.getRoot(), userDataDB); userDataDB.setDirty(false); setTitle(baseFrameTitle + ": " + currentUserFile.toString()); } catch (Exception e) { e.printStackTrace(); } frame.setTitle(fileName); } } }; loadAction = new AbstractAction("Open Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { System.out.println("load file name: " + file); // if they open an authored file then they are overriding // the remoteURL, // at least for now. This makes the title bar update // correctly, and // fixes a lockup that happens when they have opened a local // file and then // try to save it again. remoteURL = null; loadFile(file); exportToHtmlAction.setEnabled(true); } } }; loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAction = new AbstractAction("Save Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if (OTConfig.isRemoteSaveData() && remoteURL != null) { try { if (OTConfig.isRestEnabled()) { try { remoteSaveData(OTViewer.HTTP_PUT); } catch (Exception e) { remoteSaveData(OTViewer.HTTP_POST); } } else { remoteSaveData(OTViewer.HTTP_POST); } } catch (Exception e) { JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { if (currentAuthoredFile == null) { saveAsAction.actionPerformed(arg0); return; } if (checkForReplace(currentAuthoredFile)) { try { ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } } // end if (remoteUrl == null) } }; saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAsAction = new AbstractAction("Save Authored Content As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentAuthoredFile != null) { mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile()); mrfd.setSelectedFile(currentAuthoredFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".otml")) { file = new File(file.getAbsolutePath() + ".otml"); } if (checkForReplace(file)) { try { ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB); currentAuthoredFile = file; currentURL = file.toURL(); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } frame.setTitle(fileName); remoteURL = null; updateMenuBar(); } } }; saveRemoteAsAction = new AbstractAction("Save Remotely As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { // Pop up a dialog asking for a URL // Post the otml to the url JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setLayout(new BorderLayout()); JLabel prompt = new JLabel("Please enter the URL to which you would like to save:"); prompt.setBorder(new EmptyBorder(0, 0, 10, 0)); JTextField textField = new JTextField(); if (remoteURL == null) { textField.setText("http: } else { textField.setText(remoteURL.toString()); } JPanel checkboxPanel = new JPanel(); JCheckBox restCheckbox = new JCheckBox("REST Enabled?"); restCheckbox.setSelected(OTConfig.isRestEnabled()); checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); checkboxPanel.add(restCheckbox); panel.add(prompt, BorderLayout.NORTH); panel.add(textField, BorderLayout.CENTER); panel.add(checkboxPanel, BorderLayout.SOUTH); int returnVal = CustomDialog.showOKCancelDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), // parent panel, // custom content "Save URL", // title false, // resizeable true // modal ); if (returnVal == 0) { try { remoteURL = new URL(textField.getText()); // WARNING this will cause a security exception if we // are running in a applet or jnlp which // has a security sandbox. System.setProperty(OTConfig.REST_ENABLED_PROP, Boolean.toString(restCheckbox.isSelected())); remoteSaveData(OTViewer.HTTP_POST); updateMenuBar(); } catch (Exception e) { System.err.println("Bad URL. Not saving."); JOptionPane.showMessageDialog( (Frame) SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { // CANCELLED } } }; exportImageAction = new AbstractAction("Export Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { // this introduces a dependency on concord Swing project // instead there needs to be a way to added these actions // through // the xml Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp); } }; exportHiResImageAction = new AbstractAction("Export Hi Res Image...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp, 2, 2); } }; debugAction = new AbstractAction("Debug Mode") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (((JCheckBoxMenuItem) source).isSelected()) { System.setProperty(OTConfig.DEBUG_PROP, "true"); } else { System.setProperty(OTConfig.DEBUG_PROP, "false"); } try { reloadWindow(); } catch (Exception exp) { exp.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateMenuBar(); } }); exportToHtmlAction.setEnabled(true); } }; showConsoleAction = new AbstractAction("Show Console") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (consoleFrame != null) { consoleFrame.setVisible(true); } } }; reloadWindowAction = new AbstractAction("Reload window") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { reload(); } catch (Exception e1) { e1.printStackTrace(); } } }; reloadWindowAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); exitAction = new ExitAction(); } /** * @return Returns the menuBar. */ public JMenuBar updateMenuBar() { JMenu fileMenu = null; if (menuBar == null) { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); menuBar.add(fileMenu); } else { fileMenu = menuBar.getMenu(0); fileMenu.removeAll(); } if (OTConfig.isAuthorMode()) { userMode = OTConfig.NO_USER_MODE; } if (userMode == OTConfig.SINGLE_USER_MODE) { fileMenu.setEnabled(!justStarted); fileMenu.add(newUserDataAction); fileMenu.add(loadUserDataAction); fileMenu.add(saveUserDataAction); fileMenu.add(saveUserDataAsAction); } if (OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Authored Content Remotely As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); fileMenu.add(saveRemoteAsAction); } if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); } if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) { fileMenu.add(exportImageAction); fileMenu.add(exportHiResImageAction); } fileMenu.add(exportToHtmlAction); fileMenu.add(showConsoleAction); if (OTConfig.isAuthorMode() || OTConfig.isDebug()) { fileMenu.add(reloadWindowAction); } JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction); debugItem.setSelected(OTConfig.isDebug()); fileMenu.add(debugItem); fileMenu.add(exitAction); return menuBar; } boolean checkForReplace(File file) { if (file == null){ return false; } if (!file.exists()) { return true; // File doesn't exist, so go ahead and save } if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){ return true; // we're already authoring this file, so no need to // prompt } final Object[] options = { "Yes", "No" }; return javax.swing.JOptionPane.showOptionDialog(null, "The file '" + file.getName() + "' already exists. " + "Replace existing file?", "Warning", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION; } /** * Checks if the user has unsaved work. If they do then it prompts them to * confirm what they are doing. If they cancel then it returns false. * * @return */ public boolean checkForUnsavedUserData() { if (currentUser != null && userDataDB != null) { if (userDataDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; askedAboutSavingUserData = true; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving work"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Set needToSaveUserData true"); needToSaveUserData = true; break; } } } return true; } /** * Checks if the user has unsaved authored data. If they do then it prompts * them to confirm what they are doing. If they cancel then it returns * false. * * @return */ public boolean checkForUnsavedAuthorData() { if (xmlDB != null) { if (xmlDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving authored data"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Saving authored data"); saveAction.actionPerformed(null); break; } } } return true; } /** * This does not check for unsaved user data * */ public void newAnonUserData() { newUserData(ANON_SINGLE_USER_NAME); } /** * This does not check for unsaved user data * */ public void newUserData(String userName) { // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name try { // need to make a brand new stateDB userDataDB = new XMLDatabase(); // System.out.println("otrunk: " + otrunk + " userDatabase: " + // userDataDB); OTObjectService objService = otrunk.createObjectService(userDataDB); OTStateRoot stateRoot = (OTStateRoot) objService.createObject(OTStateRoot.class); userDataDB.setRoot(stateRoot.getGlobalId()); stateRoot.setFormatVersionString("1.0"); OTUserObject userObject = OTViewerHelper.createUser(userName, objService); otrunk.initUserObjectService((OTObjectServiceImpl) objService, userObject, stateRoot); userDataDB.setDirty(false); currentUserFile = null; setCurrentUser(userObject); reloadWindow(); } catch (Exception e) { e.printStackTrace(); } } public boolean exit() { try { if (!checkForUnsavedUserData()) { // the user canceled the operation return false; } if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) { // the user canceled the operation return false; } // FIXME there is a problem with this logic. If the user saved data // just before closing // checkForUnsavedUserData will not see any unsaved data. But if // some view creates // data in the viewClosed method then that data will not get saved // here. // I think the key to solving this is to seperate the // automatic/logging data from the // user visible data. And then make a rule that saving data in the // viewClosed method // is not allowed. bodyPanel.setCurrentObject(null); conditionalSaveUserData(); if (otrunk != null) otrunk.close(); } catch (Exception exp) { exp.printStackTrace(); // exit anyhow } System.exit(0); return true; } protected void conditionalSaveUserData() { if (!askedAboutSavingUserData) { checkForUnsavedUserData(); } if (needToSaveUserData) { saveUserDataAction.actionPerformed(null); } else { System.err.println("Not saving work before closing."); } // Reset these back to false, so if the user is switching to a new // user or loading a new file we are in a clean state, for that file or // user askedAboutSavingUserData = false; needToSaveUserData = false; } public File getReportFile() { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("html"); if (currentUserFile != null) { mrfd.setCurrentDirectory(currentUserFile.getParentFile()); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".html")) { file = new File(file.getAbsolutePath() + ".html"); } return file; } return null; } public void createNewUser() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // This ensures viewClosed is called bodyPanel.setCurrentObject(null); conditionalSaveUserData(); // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name newAnonUserData(); exportToHtmlAction.setEnabled(true); } public void openUserData() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // FIXME Calling the method below would insure the view is closed, and // that any data that is // is modified in that view closed operation will get saved, however if // the user // cancels the open dialog then we would be left in an unknown // state. The current view would be closed which they would want to see // again. // bodyPanel.setCurrentObject(null); conditionalSaveUserData(); Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { loadUserDataFile(file); exportToHtmlAction.setEnabled(true); } } public void instructionPanel() { commDialog.setResizable(false); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setLayout(null); JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:"); JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:"); JButton bNew = new JButton("New"); JButton bOpen = new JButton("Open"); panel.add(lNew); panel.add(lOpen); panel.add(bNew); panel.add(bOpen); lNew.setLocation(50, 100); lOpen.setLocation(50, 150); bNew.setLocation(400, 100); bOpen.setLocation(400, 150); lNew.setSize(340, 30); lOpen.setSize(340, 30); bNew.setSize(70, 25); bOpen.setSize(70, 25); bNew.setOpaque(false); bOpen.setOpaque(false); bNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); createNewUser(); } }); bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); openUserData(); } }); commDialog.getContentPane().add(panel); commDialog.setBounds(200, 200, 500, 300); SwingUtilities.invokeLater(new Runnable() { public void run() { commDialog.setVisible(true); justStarted = false; updateMenuBar(); } }); } public OTViewContainerPanel getViewContainerPanel() { return this.bodyPanel; } public void setExitAction(AbstractAction exitAction) { this.exitAction = exitAction; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#about() */ public void about() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#preferences() */ public void preferences() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#quit() */ public void quit() { exitAction.actionPerformed(null); } public OTrunk getOTrunk() { return otrunk; } } // @jve:decl-index=0:visual-constraint="10,10" class HtmlFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File f) { if (f == null) return false; if (f.isDirectory()) return true; return (f.getName().toLowerCase().endsWith(".html")); } public String getDescription() { return "HTML files"; } } // @jve:decl-index=0:visual-constraint="10,10"
package com.xpn.xwiki.web; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Date; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.util.Util; /** * <p> * Action for serving skin files. It allows skins to be defined using XDocuments as skins, by letting files be placed as * text fields in an XWiki.XWikiSkins object, or as attachments to the document, or as a file in the filesystem. If the * file is not found in the current skin, then it is searched in its base skin, and eventually in the default base * skins, * </p> * <p> * This action indicates that the results should be publicly cacheable for 30 days. * </p> * * @version $Id$ * @since 1.0 */ public class SkinAction extends XWikiAction { /** Logging helper. */ private static final Logger LOGGER = LoggerFactory.getLogger(SkinAction.class); /** Path delimiter. */ private static final String DELIMITER = "/"; /** The directory where the skins are placed in the webapp. */ private static final String SKINS_DIRECTORY = "skins"; /** The directory where resources are placed in the webapp. */ private static final String RESOURCES_DIRECTORY = "resources"; /** The encoding to use when reading text resources from the filesystem and when sending css/javascript responses. */ private static final String ENCODING = "UTF-8"; /** * {@inheritDoc} * * @see XWikiAction#render(XWikiContext) */ @Override public String render(XWikiContext context) throws XWikiException { try { return render(context.getRequest().getPathInfo(), context); } catch (IOException e) { context.getResponse().setStatus(404); return "docdoesnotexist"; } } public String render(String path, XWikiContext context) throws XWikiException, IOException { XWiki xwiki = context.getWiki(); // Since skin paths usually contain the name of skin document, it is likely that the context document belongs to // the current skin. XWikiDocument doc = context.getDoc(); // The base skin could be either a filesystem directory, or an xdocument. String baseskin = xwiki.getBaseSkin(context, true); XWikiDocument baseskindoc = xwiki.getDocument(baseskin, context); // The default base skin is always a filesystem directory. String defaultbaseskin = xwiki.getDefaultBaseSkin(context); LOGGER.debug("document: [{}] ; baseskin: [{}] ; defaultbaseskin: [{}]", new Object[] {doc.getDocumentReference(), baseskin, defaultbaseskin}); // Since we don't know exactly what does the URL point at, meaning that we don't know where the skin identifier // ends and where the path to the file starts, we must try to split at every '/' character. int idx = path.lastIndexOf(DELIMITER); boolean found = false; while (idx > 0) { try { String filename = Util.decodeURI(path.substring(idx + 1), context); LOGGER.debug("Trying [{}]", filename); // Try on the current skin document. if (renderSkin(filename, doc, context)) { found = true; break; } // Try on the base skin document, if it is not the same as above. if (!doc.getName().equals(baseskin)) { if (renderSkin(filename, baseskindoc, context)) { found = true; break; } } // Try on the default base skin, if it wasn't already tested above. if (!(doc.getName().equals(defaultbaseskin) || baseskin.equals(defaultbaseskin))) { // defaultbaseskin can only be on the filesystem, so don't try to use it as a // skin document. if (renderFileFromFilesystem(getSkinFilePath(filename, defaultbaseskin), context)) { found = true; break; } } // Try in the resources directory. if (renderFileFromFilesystem(getResourceFilePath(filename), context)) { found = true; break; } } catch (XWikiException ex) { if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) { // This means that the response couldn't be sent, although the file was // successfully found. Signal this further, and stop trying to render. throw ex; } LOGGER.debug(String.valueOf(idx), ex); } idx = path.lastIndexOf(DELIMITER, idx - 1); } if (!found) { context.getResponse().setStatus(404); return "docdoesnotexist"; } return null; } /** * Get the path for the given skin file in the given skin. * * @param filename Name of the file. * @param skin Name of the skin to search in. * @throws IOException if filename is invalid */ public String getSkinFilePath(String filename, String skin) throws IOException { String path = URI.create(DELIMITER + SKINS_DIRECTORY + DELIMITER + skin + DELIMITER + filename).normalize().toString(); if (!path.startsWith(DELIMITER + SKINS_DIRECTORY)) { LOGGER.warn("Illegal access, tried to use file [{}] as a skin. Possible break-in attempt!", path); throw new IOException("Invalid filename: '" + filename + "' for skin '" + skin + "'"); } return path; } /** * Get the path for the given file in resources. * * @param filename Name of the file. * @throws IOException if filename is invalid */ public String getResourceFilePath(String filename) throws IOException { String path = URI.create(DELIMITER + RESOURCES_DIRECTORY + DELIMITER + filename).normalize().toString(); if (!path.startsWith(DELIMITER + RESOURCES_DIRECTORY)) { LOGGER.warn("Illegal access, tried to use file [{}] as a resource. Possible break-in attempt!", path); throw new IOException("Invalid filename: '" + filename + "'"); } return path; } /** * Tries to serve a skin file using <tt>doc</tt> as a skin document. The file is searched in the following places: * <ol> * <li>As the content of a property with the same name as the requested filename, from an XWikiSkins object attached * to the document.</li> * <li>As the content of an attachment with the same name as the requested filename.</li> * <li>As a file located on the filesystem, in the directory with the same name as the current document (in case the * URL was actually pointing to <tt>/skins/directory/file</tt>).</li> * </ol> * * @param filename The name of the skin file that should be rendered. * @param doc The skin {@link XWikiDocument document}. * @param context The current {@link XWikiContext request context}. * @return <tt>true</tt> if the attachment was found and the content was successfully sent. * @throws XWikiException If the attachment cannot be loaded. * @throws IOException if the filename is invalid */ private boolean renderSkin(String filename, XWikiDocument doc, XWikiContext context) throws XWikiException, IOException { LOGGER.debug("Rendering file [{}] within the [{}] document", filename, doc.getDocumentReference()); try { if (doc.isNew()) { LOGGER.debug("[{}] is not a document", doc.getDocumentReference().getName()); } else { return renderFileFromObjectField(filename, doc, context) || renderFileFromAttachment(filename, doc, context) || (SKINS_DIRECTORY.equals(doc.getSpace()) && renderFileFromFilesystem( getSkinFilePath(filename, doc.getName()), context)); } } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response:", e); } return renderFileFromFilesystem(getSkinFilePath(filename, doc.getName()), context); } /** * Tries to serve a file from the filesystem. * * @param path Path of the file that should be rendered. * @param context The current {@link XWikiContext request context}. * @return <tt>true</tt> if the file was found and its content was successfully sent. * @throws XWikiException If the response cannot be sent. */ private boolean renderFileFromFilesystem(String path, XWikiContext context) throws XWikiException { LOGGER.debug("Rendering filesystem file from path [{}]", path); XWikiResponse response = context.getResponse(); try { byte[] data; data = context.getWiki().getResourceContentAsBytes(path); if (data != null && data.length > 0) { String filename = path.substring(path.lastIndexOf("/") + 1, path.length()); String mimetype = context.getEngineContext().getMimeType(filename.toLowerCase()); Date modified = null; if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) { // Always force UTF-8, as this is the assumed encoding for text files. String rawContent = new String(data, ENCODING); byte[] newdata = context.getWiki().parseContent(rawContent, context).getBytes(ENCODING); // If the content contained velocity code, then it should not be cached if (Arrays.equals(newdata, data)) { modified = context.getWiki().getResourceLastModificationDate(path); } else { modified = new Date(); data = newdata; } response.setCharacterEncoding(ENCODING); } else { modified = context.getWiki().getResourceLastModificationDate(path); } setupHeaders(response, mimetype, modified, data.length); try { response.getOutputStream().write(data); } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e); } return true; } } catch (IOException ex) { LOGGER.info("Skin file [{}] does not exist or cannot be accessed", path); } return false; } /** * Tries to serve the content of an XWikiSkins object field as a skin file. * * @param filename The name of the skin file that should be rendered. * @param doc The skin {@link XWikiDocument document}. * @param context The current {@link XWikiContext request context}. * @return <tt>true</tt> if the object exists, and the field is set to a non-empty value, and its content was * successfully sent. * @throws IOException If the response cannot be sent. */ public boolean renderFileFromObjectField(String filename, XWikiDocument doc, XWikiContext context) throws IOException { LOGGER.debug("... as object property"); BaseObject object = doc.getObject("XWiki.XWikiSkins"); String content = null; if (object != null) { content = object.getStringValue(filename); } if (!StringUtils.isBlank(content)) { XWiki xwiki = context.getWiki(); XWikiResponse response = context.getResponse(); String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase()); // Since object fields are read as unicode strings, the result does not depend on the wiki encoding. Force // the output to UTF-8. response.setCharacterEncoding(ENCODING); if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) { content = context.getWiki().parseContent(content, context); } byte[] data = content.getBytes(ENCODING); setupHeaders(response, mimetype, doc.getDate(), data.length); response.getOutputStream().write(data); return true; } else { LOGGER.debug("Object field not found or empty"); } return false; } /** * Tries to serve the content of an attachment as a skin file. * * @param filename The name of the skin file that should be rendered. * @param doc The skin {@link XWikiDocument document}. * @param context The current {@link XWikiContext request context}. * @return <tt>true</tt> if the attachment was found and its content was successfully sent. * @throws IOException If the response cannot be sent. * @throws XWikiException If the attachment cannot be loaded. */ public boolean renderFileFromAttachment(String filename, XWikiDocument doc, XWikiContext context) throws IOException, XWikiException { LOGGER.debug("... as attachment"); XWikiAttachment attachment = doc.getAttachment(filename); if (attachment != null) { XWiki xwiki = context.getWiki(); XWikiResponse response = context.getResponse(); String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase()); if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) { byte[] data = attachment.getContent(context); // Always force UTF-8, as this is the assumed encoding for text files. data = context.getWiki().parseContent(new String(data, ENCODING), context).getBytes(ENCODING); response.setCharacterEncoding(ENCODING); setupHeaders(response, mimetype, attachment.getDate(), data.length); response.getOutputStream().write(data); } else { setupHeaders(response, mimetype, attachment.getDate(), attachment.getContentSize(context)); IOUtils.copy(attachment.getContentInputStream(context), response.getOutputStream()); } return true; } else { LOGGER.debug("Attachment not found"); } return false; } /** * Checks if a mimetype indicates a javascript file. * * @param mimetype The mime type to check. * @return <tt>true</tt> if the mime type represents a javascript file. */ public boolean isJavascriptMimeType(String mimetype) { boolean result = "text/javascript".equalsIgnoreCase(mimetype) || "application/x-javascript".equalsIgnoreCase(mimetype) || "application/javascript".equalsIgnoreCase(mimetype); result |= "application/ecmascript".equalsIgnoreCase(mimetype) || "text/ecmascript".equalsIgnoreCase(mimetype); return result; } /** * Checks if a mimetype indicates a CSS file. * * @param mimetype The mime type to check. * @return <tt>true</tt> if the mime type represents a css file. */ public boolean isCssMimeType(String mimetype) { return "text/css".equalsIgnoreCase(mimetype); } /** * Sets several headers to properly identify the response. * * @param response The servlet response object, where the headers should be set. * @param mimetype The mimetype of the file. Used in the "Content-Type" header. * @param lastChanged The date of the last change of the file. Used in the "Last-Modified" header. * @param length The length of the content (in bytes). Used in the "Content-Length" header. */ protected void setupHeaders(XWikiResponse response, String mimetype, Date lastChanged, int length) { if (!StringUtils.isBlank(mimetype)) { response.setContentType(mimetype); } else { response.setContentType("application/octet-stream"); } response.setDateHeader("Last-Modified", lastChanged.getTime()); // Cache for one month (30 days) response.setHeader("Cache-Control", "public"); response.setDateHeader("Expires", (new Date()).getTime() + 30 * 24 * 3600 * 1000L); response.setContentLength(length); } }
package org.concord.otrunk.view; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import org.concord.applesupport.AppleApplicationAdapter; import org.concord.applesupport.AppleApplicationUtil; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeListener; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.OTUser; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.view.OTExternalAppService; import org.concord.framework.otrunk.view.OTFrameManager; import org.concord.framework.otrunk.view.OTJComponentServiceFactory; import org.concord.framework.otrunk.view.OTUserListService; import org.concord.framework.otrunk.view.OTViewContainer; import org.concord.framework.otrunk.view.OTViewContainerChangeEvent; import org.concord.framework.otrunk.view.OTViewContainerListener; import org.concord.framework.otrunk.view.OTViewContext; import org.concord.framework.otrunk.view.OTViewFactory; import org.concord.framework.text.UserMessageHandler; import org.concord.framework.util.IResourceLoader; import org.concord.framework.util.SimpleTreeNode; import org.concord.otrunk.OTMLToXHTMLConverter; import org.concord.otrunk.OTSystem; import org.concord.otrunk.OTrunkImpl; import org.concord.otrunk.OTrunkServiceEntry; import org.concord.otrunk.datamodel.OTDataObject; import org.concord.otrunk.overlay.OTOverlayGroup; import org.concord.otrunk.user.OTUserObject; import org.concord.otrunk.xml.ExporterJDOM; import org.concord.otrunk.xml.XMLDatabase; import org.concord.otrunk.xml.XMLDatabaseChangeEvent; import org.concord.otrunk.xml.XMLDatabaseChangeListener; import org.concord.swing.CustomDialog; import org.concord.swing.MemoryMonitorPanel; import org.concord.swing.MostRecentFileDialog; import org.concord.swing.StreamRecord; import org.concord.swing.StreamRecordView; import org.concord.swing.util.Util; import org.concord.view.SimpleTreeModel; import org.concord.view.SwingUserMessageHandler; /** * OTViewer Class name and description * * Date created: Dec 14, 2004 * * @author scott * */ public class OTViewer extends JFrame implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter { /** * first version of this class */ private static final long serialVersionUID = 1L; public final static String TITLE_PROP = "otrunk.view.frame_title"; public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree"; public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console"; public final static String DEMO_ONLY_PROP = "otrunk.view.demo"; public final static String OTML_URL_PROP = "otrunk.otmlurl"; public final static String HTTP_PUT = "PUT"; public final static String HTTP_POST = "POST"; public final static String HTTP_HEAD = "HEAD"; final static String DEFAULT_BASE_FRAME_TITLE = "OTrunk Viewer"; private static OTViewFactory otViewFactory; OTFrameManagerImpl frameManager; JSplitPane splitPane; OTViewContainerPanel bodyPanel; SimpleTreeModel folderTreeModel; SimpleTreeModel dataTreeModel; JTree folderTreeArea; JTree dataTreeArea; /** * Dialog used for instruction panel that shows when the program starts * Prompts "new" or "open" portfolio */ private JDialog commDialog; JFrame consoleFrame; JMenuBar menuBar; private JPanel statusPanel; String baseFrameTitle; boolean showTree = false; private boolean useScrollPane; boolean justStarted = false; protected int userMode = OTConfig.NO_USER_MODE; File currentAuthoredFile = null; URL currentURL = null; URL remoteURL; OTUserSession userSession; private static OTrunkImpl otrunk; XMLDatabase xmlDB; private OTSystem userSystem; private ArrayList<OTrunkServiceEntry<?>> services = new ArrayList<OTrunkServiceEntry<?>>(); private OTChangeListener systemChangeListener; /** * This is true if the user was asked about saving user data after they * initiated a close of the current view. */ private boolean askedAboutSavingUserData = false; /** * This is true if the user was asked about saving the user data, and said * yes */ private boolean needToSaveUserData = false; /** * This is true if the SailOTViewer created this OTViewer */ private boolean launchedBySailOTViewer = false; private boolean sailSaveEnabled = true; private IResourceLoader rrLoader = null; // Temp, to close the window AbstractAction exitAction; AbstractAction saveAsAction; private AbstractAction saveUserDataAsAction; private AbstractAction saveUserDataAction; private AbstractAction debugAction; private AbstractAction showConsoleAction; private AbstractAction newUserDataAction; private AbstractAction loadUserDataAction; private AbstractAction loadAction; private AbstractAction reloadWindowAction; private AbstractAction saveAction; private AbstractAction saveRemoteAsAction; private AbstractAction exportImageAction; private AbstractAction exportHiResImageAction; private AbstractAction exportToHtmlAction; public OTViewer() { super(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.out.println("Error setting native LAF: " + e); } this.showTree = true; AppleApplicationUtil.registerWithMacOSX(this); baseFrameTitle = DEFAULT_BASE_FRAME_TITLE; try { // this overrides the default base frame title String title = System.getProperty(TITLE_PROP, null); if (title != null) { baseFrameTitle = title; } } catch (Throwable t) { // do nothing, just use the default title } setTitle(baseFrameTitle); // If "otrunk.view.demo" is true, closing frame will just dispose // the frame, not exit. if (!Boolean.getBoolean(DEMO_ONLY_PROP)){ setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { exitAction.actionPerformed(null); } }); } createConsoleFrame(); commDialog = new JDialog(this, true); registerDebugEventListeners(); } private void createConsoleFrame() { consoleFrame = new JFrame("Console"); StreamRecord record = new StreamRecord(50000); StreamRecordView view = new StreamRecordView(record); consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); System.setOut((PrintStream) view.addOutputStream(System.out, "Console")); System.setErr((PrintStream) view.addOutputStream(System.err, System.out)); consoleFrame.getContentPane().add(view); consoleFrame.setSize(800, 600); if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) { consoleFrame.setVisible(true); } } private void registerDebugEventListeners() { // for debugging // add a breakpoint below, run in debugging mode, and then hit Meta-B // the object you're currently focused on will be passed in here and you // can // start exploring the data structures, etc. KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){ public boolean dispatchKeyEvent(KeyEvent e) { if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED) && ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0) && (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) { Object o = e.getSource(); System.out.println(o.toString()); return true; } return false; } }; focusManager.addKeyEventDispatcher(deleteDispatcher); // If the mouse click is a right click event and alt is pressed // or on a Mac the ctrl and option keys are down // then this code will print out the toString method of the // object which the mouse is over to the console. AWTEventListener awtEventListener = new AWTEventListener(){ public void eventDispatched(AWTEvent event) { if(!(event instanceof MouseEvent)){ return; } MouseEvent mEvent = (MouseEvent) event; if (mEvent.getID() == MouseEvent.MOUSE_CLICKED && (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) { System.out.println(event.getSource().toString()); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.MOUSE_EVENT_MASK); } /** * this needs to be called before initialized. * * @param serviceInterface * @param service */ public <T> void addService(Class<T> serviceInterface, T service) { OTrunkServiceEntry<T> entry = new OTrunkServiceEntry<T>(service, serviceInterface); services.add(entry); } public void setUserMode(int mode) { userMode = mode; } public int getUserMode() { return userMode; } public void updateTreePane() { Dimension minimumSize = new Dimension(100, 50); folderTreeArea = new JTree(folderTreeModel); // we are just disabling this however if we want to // use this tree for authoring, or for managing student // created objects this will need to be some form of option folderTreeArea.setEditable(false); folderTreeArea.addTreeSelectionListener(this); JComponent leftComponent = null; JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea); if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) { // ViewFactory.getComponent(root); dataTreeArea = new JTree(dataTreeModel); dataTreeArea.setEditable(false); dataTreeArea.addTreeSelectionListener(this); JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Folders", folderTreeScrollPane); tabbedPane.add("Resources", dataTreeScrollPane); // Provide minimum sizes for the two components in the split pane folderTreeScrollPane.setMinimumSize(minimumSize); dataTreeScrollPane.setMinimumSize(minimumSize); tabbedPane.setMinimumSize(minimumSize); leftComponent = tabbedPane; } else { leftComponent = folderTreeScrollPane; } if (splitPane == null) { splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel); } else { splitPane.setLeftComponent(leftComponent); } splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(200); } public void initArgs(String[] args) { // We need to add protocol handler early, before resources are loaded if (System.getProperty("java.protocol.handler.pkgs") == null){ System.setProperty("java.protocol.handler.pkgs", "org.concord.otrunk.handlers"); } URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if (authorOTMLURL == null && System.getProperty(OTML_URL_PROP, null) != null) { try { authorOTMLURL = new URL(System.getProperty(OTML_URL_PROP, null)); } catch (MalformedURLException e) { e.printStackTrace(); } } if (authorOTMLURL == null) { authorOTMLURL = OTViewer.class.getResource("no-arguments-page.otml"); } if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { currentAuthoredFile = new File(authorOTMLURL.getPath()); } String urlStr = authorOTMLURL.toString(); initWithWizard(urlStr); } /** * @param args * @return */ public String getURL(String[] args) { URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args); if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) { try { URI authorOTMLURI = new URI(authorOTMLURL.toString()); currentAuthoredFile = new File(authorOTMLURI); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return authorOTMLURL.toString(); } public void init(String url) { updateRemoteURL(url); createActions(); updateMenuBar(); setJMenuBar(menuBar); frameManager = new OTFrameManagerImpl(); bodyPanel = new OTViewContainerPanel(frameManager); bodyPanel.addViewContainerListener(this); if (showTree) { dataTreeModel = new SimpleTreeModel(); folderTreeModel = new SimpleTreeModel(); updateTreePane(); getContentPane().add(splitPane); } else { getContentPane().add(bodyPanel); } if (OTConfig.isShowStatus() || noClassAssignedForStudent()) { initStatusBar(); } initFrameDimensions(); if (url == null) { return; } try { initializeURL(new URL(url)); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { // FIXME: this should popup a dialog System.err.println("Can't load url"); e.printStackTrace(); return; } } /* * Test to determine whether to display warning that the student may not * be running the activity with correct portal settings. * * Shoud return true when the activity is not run in student mode and * is not assigned a class and a teacher through the portal. */ private boolean noClassAssignedForStudent() { return getUserMode() == OTConfig.SINGLE_USER_MODE && ! isSailSaveEnabled(); } private void initStatusBar() { statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1)); if (OTConfig.isShowStatus()) { final JLabel saveStateLabel = new JLabel("File saved"); statusPanel.add(saveStateLabel); statusPanel.add(Box.createHorizontalStrut(20)); statusPanel.add(new MemoryMonitorPanel()); statusPanel.add(Box.createHorizontalStrut(5)); // It takes a while for xmlDM to be initialized... Thread waitForDB = new Thread() { @Override public void run() { while (xmlDB == null) { try { sleep(1000); } catch (Exception e) { } } xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() { public void stateChanged(XMLDatabaseChangeEvent e) { if (xmlDB.isDirty()) { saveStateLabel.setText("Unsaved changes"); } else { saveStateLabel.setText("File saved"); } statusPanel.repaint(); } }); } }; waitForDB.start(); } if (noClassAssignedForStudent()) { JLabel readOnlyLabel = new JLabel("User Data Will Not Be Saved!"); statusPanel.setBackground(Color.RED); statusPanel.add(readOnlyLabel); statusPanel.add(Box.createHorizontalStrut(5)); } getContentPane().add(statusPanel, BorderLayout.SOUTH); } private void initFrameDimensions() { SwingUtilities.invokeLater(new Runnable() { public void run() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if (screenSize.width < 1000 || screenSize.height < 700) { setVisible(true); int state = getExtendedState(); // Set the maximized bits state |= Frame.MAXIMIZED_BOTH; // Maximize the frame setExtendedState(state); } else { int cornerX = 50; int cornerY = 50; int sizeX = 800; int sizeY = 500; // OTViewService viewService = otViewFactory. setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); setVisible(true); } } }); } public void initializeURL(URL url) throws Exception { loadURL(url); otrunk.setSailSavingDisabled(noClassAssignedForStudent()); OTMainFrame mainFrame = otrunk.getService(OTMainFrame.class); if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false) || !mainFrame.getShowLeftPanel()) { splitPane.getLeftComponent().setVisible(false); } useScrollPane = true; if (mainFrame.getFrame() != null) { if (mainFrame.getFrame().isResourceSet("width") && mainFrame.getFrame().isResourceSet("height")) { int cornerX = mainFrame.getFrame().getPositionX(); int cornerY = mainFrame.getFrame().getPositionY(); int sizeX = mainFrame.getFrame().getWidth(); int sizeY = mainFrame.getFrame().getHeight(); // See if title is set for main frame (only if name is // still default, so that jnlp prop will still // overrides this) if (baseFrameTitle == DEFAULT_BASE_FRAME_TITLE && mainFrame.getFrame().isResourceSet("title")){ System.out.println("change"); baseFrameTitle = mainFrame.getFrame().getTitle(); setTitle(baseFrameTitle); } setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY); repaint(); } useScrollPane = mainFrame.getFrame().getUseScrollPane(); } bodyPanel.setUseScrollPane(useScrollPane); setupBodyPanel(); } public void initWithWizard(String url) { justStarted = true; init(url); if (userMode == OTConfig.SINGLE_USER_MODE) { SwingUtilities.invokeLater(new Runnable() { public void run() { instructionPanel(); } }); } } public void loadUserDataFile(File file) { try { OTMLUserSession xmlUserSession = new OTMLUserSession(file, null); loadUserSession(xmlUserSession); } catch (Exception e) { e.printStackTrace(); } } /** * This method just sets the viewers userSession without loading it. * This is useful if a user needs to select the data they want to use * when the load method is called. Currently this is used by the "wizard" in * the ot viewer. * * @param userSession */ public void setUserSession(OTUserSession userSession) { this.userSession = userSession; userSession.setOTrunk(otrunk); } /** * This method loads in a user session, and reloads the window. * * @param userSession * @throws Exception */ public void loadUserSession(OTUserSession userSession) throws Exception { this.userSession = userSession; otrunk.registerUserSession(userSession); reloadWindow(); } public void updateOverlayGroupListeners() { OTObjectList overlays = userSystem.getOverlays(); for(int i=0; i<overlays.size(); i++){ OTObject item = overlays.get(i); if(item instanceof OTOverlayGroup){ ((OTOverlayGroup) item).addOTChangeListener(systemChangeListener); } } } public void reloadOverlays() { try { otrunk.reloadOverlays(userSession); updateOverlayGroupListeners(); reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void loadFile(File file) { currentAuthoredFile = file; try { initializeURL(currentAuthoredFile.toURL()); } catch (Exception e) { e.printStackTrace(); } } public void loadURL(URL url) throws Exception { IResourceLoader oldRRLoader = XMLDatabase.getRequiredResourceLoader(); XMLDatabase.setRequiredResourceLoader(rrLoader); XMLDatabase systemDB = null; try { // try loading in the system object if there is one String systemOtmlUrlStr = OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP); if(systemOtmlUrlStr != null){ URL systemOtmlUrl = new URL(systemOtmlUrlStr); systemDB = new XMLDatabase(systemOtmlUrl, System.out); // don't track the resource info on the system db. systemDB.loadObjects(); } } catch (Exception e){ e.printStackTrace(); systemDB = null; } try { xmlDB = new XMLDatabase(url, System.out); // Only track the resource info when there isn't a user. Currently // all classroom uses // of OTViewer has NO_USER_MODE turned off, so using this setting // safe to test // the resource tracking without affecting real users. if (userMode == OTConfig.NO_USER_MODE) { xmlDB.setTrackResourceInfo(true); } xmlDB.loadObjects(); } catch (org.jdom.input.JDOMParseException e) { String xmlWarningTitle = "XML Decoding error"; String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n" + "Please show this error message to one of the workshop leaders. \n\n" + e.getMessage(); JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle, JOptionPane.ERROR_MESSAGE); throw e; } addService(UserMessageHandler.class, new SwingUserMessageHandler(this)); otrunk = new OTrunkImpl(systemDB, xmlDB, services); OTViewFactory myViewFactory = otrunk.getService(OTViewFactory.class); if (myViewFactory != null) { otViewFactory = myViewFactory; } OTViewContext factoryContext = otViewFactory.getViewContext(); factoryContext.addViewService(OTrunk.class, otrunk); factoryContext.addViewService(OTFrameManager.class, frameManager); factoryContext.addViewService(OTJComponentServiceFactory.class, new OTJComponentServiceFactoryImpl()); factoryContext.addViewService(OTExternalAppService.class, new OTExternalAppServiceImpl()); factoryContext.addViewService(OTUserListService.class, new OTUserListService() { public Vector<OTUser> getUserList() { return otrunk.getUsers(); } }); ((OTViewFactoryImpl)otViewFactory).contextSetupComplete(); currentURL = url; XMLDatabase.setRequiredResourceLoader(oldRRLoader); } // This method was refactored out of loadURL private void setupBodyPanel() throws Exception { bodyPanel.setTopLevelContainer(true); bodyPanel.setOTViewFactory(otViewFactory); // set the current mode from the viewservice to the main bodyPanel // bodyPanel.setViewMode(otViewFactory.getDefaultMode()); // set the viewFactory of the frame manager frameManager.setViewFactory(otViewFactory); xmlDB.setDirty(false); reloadWindow(); } public OTObject getAuthoredRoot() throws Exception { String rootLocalId = OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP); if(rootLocalId != null){ OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId); return otrunk.getOTObject(rootID); } return otrunk.getRoot(); } public OTObject getRoot() throws Exception { switch (userMode) { case OTConfig.NO_USER_MODE: return getAuthoredRoot(); case OTConfig.SINGLE_USER_MODE: if (userSession == null) { return null; } OTObject otRoot = getAuthoredRoot(); return otrunk.getUserRuntimeObject(otRoot, getCurrentUser()); } return null; } public void reloadWindow() throws Exception { OTObject root = getRoot(); boolean overrideShowTree = false; if (userMode == OTConfig.SINGLE_USER_MODE) { if (root == null) { // FIXME This is an error // the newAnonUserData should have been called before this // method is // called // no user file has been started yet overrideShowTree = true; } else { OTObject realRoot = otrunk.getRealRoot(); if (realRoot instanceof OTSystem) { OTSystem localUserSystem = (OTSystem) otrunk.getUserRuntimeObject(realRoot, getCurrentUser()); // FIXME there should be a better way than this because we // have to handle // multiple users. if (localUserSystem != userSystem) { userSystem = localUserSystem; systemChangeListener = new OTChangeListener() { public void stateChanged(OTChangeEvent e) { if ("overlays".equals(e.getProperty())) { reloadOverlays(); } } }; updateOverlayGroupListeners(); userSystem.addOTChangeListener(systemChangeListener); } } } } if (showTree && !overrideShowTree) { OTDataObject rootDataObject = xmlDB.getRoot(); dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk)); folderTreeModel.setRoot(new OTFolderNode(root)); } bodyPanel.setCurrentObject(root); if (showTree && !overrideShowTree) { folderTreeModel.fireTreeStructureChanged(new TreePath( folderTreeModel.getRoot())); dataTreeModel.fireTreeStructureChanged(new TreePath( dataTreeModel.getRoot())); } Frame frame = (Frame) SwingUtilities.getRoot(this); switch (userMode) { case OTConfig.NO_USER_MODE: if (remoteURL != null) { frame.setTitle(baseFrameTitle + ": " + remoteURL.toString()); } else { frame.setTitle(baseFrameTitle + ": " + currentURL.toString()); } break; case OTConfig.SINGLE_USER_MODE: String userSessionLabel = null; if (userSession != null) { userSessionLabel = userSession.getLabel(); } if(userSessionLabel != null){ frame.setTitle(baseFrameTitle + ": " + userSessionLabel); } else { frame.setTitle(baseFrameTitle); } break; } if(userSession == null){ saveUserDataAction.setEnabled(false); saveUserDataAsAction.setEnabled(false); } else { saveUserDataAction.setEnabled(userSession.allowSave()); saveUserDataAsAction.setEnabled(userSession.allowSaveAs()); } } public void reload() throws Exception { initializeURL(currentURL); } public OTUserSession getUserSession() { return userSession; } public OTUserObject getCurrentUser() { if(userSession == null){ return null; } return userSession.getUserObject(); } /* * (non-Javadoc) * * @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer) */ public void currentObjectChanged(OTViewContainerChangeEvent evt) { final OTViewContainer myContainer = (OTViewContainer) evt.getSource(); // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable() { public void run() { OTObject currentObject = myContainer.getCurrentObject(); if (folderTreeArea != null) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; if (node.getPfObject() != currentObject) { folderTreeArea.setSelectionPath(null); } } } }); } /* * (non-Javadoc) * * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) */ public void valueChanged(TreeSelectionEvent event) { if (event.getSource() == folderTreeArea) { OTFolderNode node = (OTFolderNode) folderTreeArea.getLastSelectedPathComponent(); if (node == null) return; OTObject pfObject = node.getPfObject(); bodyPanel.setCurrentObject(pfObject); if (splitPane.getRightComponent() != bodyPanel) { splitPane.setRightComponent(bodyPanel); } } else if (event.getSource() == dataTreeArea) { SimpleTreeNode node = (SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent(); Object resourceValue = null; if (node != null) { resourceValue = node.getObject(); if (resourceValue == null) { resourceValue = "null resource value"; } } else { resourceValue = "no selected data object"; } JComponent nodeView = null; if (resourceValue instanceof OTDataObject) { nodeView = new OTDataObjectView((OTDataObject) resourceValue); } else { nodeView = new JTextArea(resourceValue.toString()); } JScrollPane scrollPane = new JScrollPane(nodeView); splitPane.setRightComponent(scrollPane); } } private void updateRemoteURL(String defaultURL) { String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null); try { if (remote == null) { if (defaultURL != null && defaultURL.startsWith("http:")) { remoteURL = new URL(defaultURL); } } else { remoteURL = new URL(remote); } } catch (Exception e) { remoteURL = null; System.err.println("Remote URL is invalid."); e.printStackTrace(); } } /** * @return Returns the menuBar. */ public JMenuBar updateMenuBar() { JMenu fileMenu = null; if (menuBar == null) { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); menuBar.add(fileMenu); } else { fileMenu = menuBar.getMenu(0); fileMenu.removeAll(); } if (OTConfig.isAuthorMode()) { userMode = OTConfig.NO_USER_MODE; } if (userMode == OTConfig.SINGLE_USER_MODE) { fileMenu.setEnabled(!justStarted); // we add new and load ("open") menu items only if this is NOT launched // by sail or if otrunk.view.destructive_menu is set to true if (!isLaunchedBySailOTViewer() || (OTConfig.isShowDestructiveMenuItems())){ fileMenu.add(newUserDataAction); fileMenu.add(loadUserDataAction); } fileMenu.add(saveUserDataAction); fileMenu.add(saveUserDataAsAction); } if (OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Authored Content Remotely As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); fileMenu.add(saveRemoteAsAction); } if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) { if (userMode == OTConfig.SINGLE_USER_MODE) { loadAction.putValue(Action.NAME, "Open Authored Content..."); saveAction.putValue(Action.NAME, "Save Authored Content"); saveAsAction.putValue(Action.NAME, "Save Authored Content As..."); } else { loadAction.putValue(Action.NAME, "Open..."); saveAction.putValue(Action.NAME, "Save"); saveAsAction.putValue(Action.NAME, "Save As..."); } fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.add(saveAsAction); } if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) { fileMenu.add(exportImageAction); fileMenu.add(exportHiResImageAction); } fileMenu.add(exportToHtmlAction); fileMenu.add(showConsoleAction); if (OTConfig.isAuthorMode() || OTConfig.isDebug()) { fileMenu.add(reloadWindowAction); } JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction); debugItem.setSelected(OTConfig.isDebug()); fileMenu.add(debugItem); fileMenu.add(exitAction); return menuBar; } boolean checkForReplace(File file) { if (file == null){ return false; } if (!file.exists()) { return true; // File doesn't exist, so go ahead and save } if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){ return true; // we're already authoring this file, so no need to // prompt } final Object[] options = { "Yes", "No" }; return javax.swing.JOptionPane.showOptionDialog(null, "The file '" + file.getName() + "' already exists. " + "Replace existing file?", "Warning", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION; } /** * FIXME This method name is confusing. The method first checks for unsaved * changes, and if there are unsaved changes it asks the user if they want to * "don't save", "cancel" or "save" * * @return */ public boolean checkForUnsavedUserData() { if(userSession == null){ return true; } if(userSession.hasUnsavedChanges()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; askedAboutSavingUserData = true; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving work"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Set needToSaveUserData true"); needToSaveUserData = true; break; } } return true; } /** * Checks if the user has unsaved authored data. If they do then it prompts * them to confirm what they are doing. If they cancel then it returns * false. * * @return */ public boolean checkForUnsavedAuthorData() { if (xmlDB != null) { if (xmlDB.isDirty()) { // show dialog message telling them they haven't // saved their work // FIXME String options[] = { "Don't Save", "Cancel", "Save" }; int chosenOption = JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); switch (chosenOption) { case 0: System.err.println("Not saving authored data"); break; case 1: System.err.println("Canceling close"); return false; case 2: System.err.println("Saving authored data"); saveAction.actionPerformed(null); break; } } } return true; } /** * This does not check for unsaved user data * */ public void newAnonUserData() { newUserData(OTViewerHelper.ANON_SINGLE_USER_NAME); } public void newUserData(String userName) { // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name if(userSession == null) { throw new IllegalStateException("a OTUserSession must be supplied before newUserData can be called"); } try { userSession.newLayer(); OTUserObject userObject = userSession.getUserObject(); if(userName != null){ userObject.setName(userName); } // This will request the label from the userSession reloadWindow(); } catch (Exception e) { e.printStackTrace(); } } public boolean exit() { try { if (!checkForUnsavedUserData()) { // the user canceled the operation return false; } if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) { // the user canceled the operation return false; } // FIXME there is a problem with this logic. If the user saved data // just before closing // checkForUnsavedUserData will not see any unsaved data. But if // some view creates // data in the viewClosed method then that data will not get saved // here. // I think the key to solving this is to separate the // automatic/logging data from the // user visible data. And then make a rule that saving data in the // viewClosed method // is not allowed. bodyPanel.setCurrentObject(null); conditionalSaveUserData(); if (otrunk != null) otrunk.close(); } catch (Exception exp) { exp.printStackTrace(); // exit anyhow } System.exit(0); return true; } protected void conditionalSaveUserData() { if (!askedAboutSavingUserData) { checkForUnsavedUserData(); } if (needToSaveUserData) { saveUserDataAction.actionPerformed(null); } else { System.err.println("Not saving work before closing."); } // Reset these back to false, so if the user is switching to a new // user or loading a new file we are in a clean state, for that file or // user askedAboutSavingUserData = false; needToSaveUserData = false; } public File getReportFile() { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("html"); if (userSession instanceof OTMLUserSession){ OTMLUserSession otmlUserSession = (OTMLUserSession) userSession; if(otmlUserSession.currentUserFile != null){ mrfd.setCurrentDirectory(otmlUserSession.currentUserFile.getParentFile()); } } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".html")) { file = new File(file.getAbsolutePath() + ".html"); } return file; } return null; } public void createNewUser() { if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // This ensures viewClosed is called bodyPanel.setCurrentObject(null); conditionalSaveUserData(); // call some new method for creating a new un-saved user state // this should set the currentUserFile to null, so the save check // prompts // for a file name newAnonUserData(); exportToHtmlAction.setEnabled(true); } public void openUserData(boolean saveCurrentData) { if(saveCurrentData){ if (!checkForUnsavedUserData()) { // the user canceled the operation return; } // FIXME Calling the method below would insure the view is closed, and // that any data that is // is modified in that view closed operation will get saved, however if // the user // cancels the open dialog then we would be left in an unknown // state. The current view would be closed which they would want to see // again. // bodyPanel.setCurrentObject(null); conditionalSaveUserData(); } if(userSession == null){ throw new IllegalStateException("can't open user data without a userSession"); } boolean success = userSession.open(); try { reloadWindow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(success){ exportToHtmlAction.setEnabled(true); } } public void instructionPanel() { commDialog.setResizable(false); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.5; c.insets = new Insets(5,10,5,10); JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:"); JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:"); JButton bNew = new JButton("New"); JButton bOpen = new JButton("Open"); c.gridx = 0; c.gridy = 0; panel.add(lNew, c); c.gridx = 1; panel.add(bNew, c); c.gridx = 0; c.gridy = 1; panel.add(lOpen, c); c.gridx = 1; panel.add(bOpen, c); bNew.setOpaque(false); bOpen.setOpaque(false); setUserSession(new OTMLUserSession()); bNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); newAnonUserData(); exportToHtmlAction.setEnabled(true); } }); bOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { commDialog.setVisible(false); openUserData(false); } }); commDialog.getContentPane().add(panel); commDialog.setBounds(200, 200, 450, 200); SwingUtilities.invokeLater(new Runnable() { public void run() { commDialog.setVisible(true); justStarted = false; updateMenuBar(); } }); } public OTViewContainerPanel getViewContainerPanel() { return this.bodyPanel; } public void setExitAction(AbstractAction exitAction) { this.exitAction = exitAction; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#about() */ public void about() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#preferences() */ public void preferences() { // TODO Auto-generated method stub } public void setLaunchedBySailOTViewer(boolean launchedBySailOTViewer){ this.launchedBySailOTViewer = launchedBySailOTViewer; } public boolean isLaunchedBySailOTViewer(){ return launchedBySailOTViewer; } public void setRequiredResourceLoader(IResourceLoader loader) { this.rrLoader = loader; } /* * (non-Javadoc) * * @see org.concord.applesupport.AppleApplicationAdapter#quit() */ public void quit() { exitAction.actionPerformed(null); } public OTrunk getOTrunk() { return otrunk; } /** * @param sailSaveEnabled the sailSaveEnabled to set */ public void setSailSaveEnabled(boolean sailSaveEnabled) { this.sailSaveEnabled = sailSaveEnabled; } /** * True is sail saving is enabled * @return the sailSaveEnabled */ public boolean isSailSaveEnabled() { return sailSaveEnabled; } public static void setOTViewFactory(OTViewFactory factory) { otViewFactory = factory; } public void createActions() { newUserDataAction = new AbstractAction("New") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { createNewUser(); } }; loadUserDataAction = new AbstractAction("Open...") { /** * nothing to serialize here. Just the parent class. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { openUserData(true); } }; exportToHtmlAction = new AbstractAction("Export to html...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent arg0) { File fileToSave = getReportFile(); OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer()); otxc.setXHTMLParams(fileToSave, 800, 600); (new Thread(otxc)).start(); } }; // Isn't it enabled by default? exportToHtmlAction.setEnabled(true); saveUserDataAction = new AbstractAction("Save") { /** * Nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { userSession.save(); // the save operation might change the label used by the session setTitle(baseFrameTitle + ": " + userSession.getLabel()); } }; saveUserDataAsAction = new AbstractAction("Save As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if(userSession instanceof OTMLUserSession){ ((OTMLUserSession)userSession).setDialogParent(SwingUtilities.getRoot(OTViewer.this)); } userSession.saveAs(); } }; loadAction = new AbstractAction("Open Authored Content...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.openotml"); mrfd.setFilenameFilter("otml"); int retval = mrfd.showOpenDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); } if (file != null && file.exists()) { System.out.println("load file name: " + file); // if they open an authored file then they are overriding // the remoteURL, // at least for now. This makes the title bar update // correctly, and // fixes a lockup that happens when they have opened a local // file and then // try to save it again. remoteURL = null; loadFile(file); exportToHtmlAction.setEnabled(true); } } }; loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAction = new AbstractAction("Save Authored Content...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if (OTConfig.isRemoteSaveData() && remoteURL != null) { try { if (OTConfig.isRestEnabled()) { try { otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_PUT); setTitle(remoteURL.toString()); } catch (Exception e) { otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST); setTitle(remoteURL.toString()); } } else { otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST); setTitle(remoteURL.toString()); } } catch (Exception e) { JOptionPane.showMessageDialog( SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { if (currentAuthoredFile == null) { saveAsAction.actionPerformed(arg0); return; } if (checkForReplace(currentAuthoredFile)) { try { ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(), xmlDB); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } } // end if (remoteUrl == null) } }; saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAsAction = new AbstractAction("Save Authored Content As...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this); MostRecentFileDialog mrfd = new MostRecentFileDialog("org.concord.otviewer.saveotml"); mrfd.setFilenameFilter("otml"); if (currentAuthoredFile != null) { mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile()); mrfd.setSelectedFile(currentAuthoredFile); } int retval = mrfd.showSaveDialog(frame); File file = null; if (retval == MostRecentFileDialog.APPROVE_OPTION) { file = mrfd.getSelectedFile(); String fileName = file.getPath(); if (!fileName.toLowerCase().endsWith(".otml")) { file = new File(file.getAbsolutePath() + ".otml"); } if (checkForReplace(file)) { try { ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB); currentAuthoredFile = file; currentURL = file.toURL(); xmlDB.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } frame.setTitle(fileName); remoteURL = null; updateMenuBar(); } } }; saveRemoteAsAction = new AbstractAction("Save Remotely As...") { /** * nothing to serizile here */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { // Pop up a dialog asking for a URL // Post the otml to the url JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setLayout(new BorderLayout()); JLabel prompt = new JLabel("Please enter the URL to which you would like to save:"); prompt.setBorder(new EmptyBorder(0, 0, 10, 0)); JTextField textField = new JTextField(); if (remoteURL == null) { textField.setText("http: } else { textField.setText(remoteURL.toString()); } JPanel checkboxPanel = new JPanel(); JCheckBox restCheckbox = new JCheckBox("REST Enabled?"); restCheckbox.setSelected(OTConfig.isRestEnabled()); checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); checkboxPanel.add(restCheckbox); panel.add(prompt, BorderLayout.NORTH); panel.add(textField, BorderLayout.CENTER); panel.add(checkboxPanel, BorderLayout.SOUTH); int returnVal = CustomDialog.showOKCancelDialog( SwingUtilities.getRoot(OTViewer.this), // parent panel, // custom content "Save URL", // title false, // resizeable true // modal ); if (returnVal == 0) { try { remoteURL = new URL(textField.getText()); // WARNING this will cause a security exception if we // are running in a applet or jnlp which // has a security sandbox. System.setProperty(OTConfig.REST_ENABLED_PROP, Boolean.toString(restCheckbox.isSelected())); otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST); setTitle(remoteURL.toString()); updateMenuBar(); } catch (Exception e) { System.err.println("Bad URL. Not saving."); JOptionPane.showMessageDialog( SwingUtilities.getRoot(OTViewer.this), "There was an error saving. Check your URL and try again.", "Error Saving", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } else { // CANCELLED } } }; exportImageAction = new AbstractAction("Export Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { // this introduces a dependency on concord Swing project // instead there needs to be a way to added these actions // through // the xml Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp); } }; exportHiResImageAction = new AbstractAction("Export Hi Res Image...") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component currentComp = bodyPanel.getCurrentComponent(); Util.makeScreenShot(currentComp, 2, 2); } }; debugAction = new AbstractAction("Debug Mode") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (((JCheckBoxMenuItem) source).isSelected()) { System.setProperty(OTConfig.DEBUG_PROP, "true"); } else { System.setProperty(OTConfig.DEBUG_PROP, "false"); } try { reloadWindow(); } catch (Exception exp) { exp.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { updateMenuBar(); } }); exportToHtmlAction.setEnabled(true); } }; showConsoleAction = new AbstractAction("Show Console") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (consoleFrame != null) { consoleFrame.setVisible(true); } } }; reloadWindowAction = new AbstractAction("Reload window") { /** * nothing to serialize here */ private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { reload(); } catch (Exception e1) { e1.printStackTrace(); } } }; reloadWindowAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); exitAction = new ExitAction(); } public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); OTViewer viewer = new OTViewer(); if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) { viewer.setUserMode(OTConfig.SINGLE_USER_MODE); } else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) { viewer.setUserMode(OTConfig.NO_USER_MODE); } viewer.initArgs(args); } class ExitAction extends AbstractAction { /** * nothing to serialize here. */ private static final long serialVersionUID = 1L; public ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent e) { // If this suceeds then the VM will exit so // the window will get disposed exit(); } } } // @jve:decl-index=0:visual-constraint="10,10" class HtmlFileFilter extends javax.swing.filechooser.FileFilter { @Override public boolean accept(File f) { if (f == null) return false; if (f.isDirectory()) return true; return (f.getName().toLowerCase().endsWith(".html")); } @Override public String getDescription() { return "HTML files"; } } // @jve:decl-index=0:visual-constraint="10,10"
package zephyr.plugin.core.internal.synchronization.binding; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.ui.IViewReference; import zephyr.plugin.core.api.codeparser.interfaces.CodeNode; import zephyr.plugin.core.api.synchronization.Clock; import zephyr.plugin.core.internal.ZephyrPluginCore; import zephyr.plugin.core.internal.synchronization.providers.ViewProviderReference; import zephyr.plugin.core.internal.synchronization.providers.ViewProviders; import zephyr.plugin.core.internal.synchronization.tasks.ViewReference; import zephyr.plugin.core.internal.synchronization.viewfinder.ViewFinder; import zephyr.plugin.core.views.SyncView; public class ViewBinder { protected final Map<Clock, ClockViews> clockToView = Collections.synchronizedMap(new HashMap<Clock, ClockViews>()); private final ViewProviders viewProviders = new ViewProviders(); private void bindWithNewView(CodeNode[] codeNodes, ViewFinder viewFinder) { CodeNode[] remainToDisplay = codeNodes; while (remainToDisplay.length > 0) { ViewReference viewRef = viewFinder.provideNewView(); if (viewRef == null) return; boolean[] displayed = viewRef.provide(remainToDisplay); int nbToDisplay = remainToDisplay.length; remainToDisplay = removeDisplayed(displayed, remainToDisplay); if (nbToDisplay == remainToDisplay.length) break; } } private CodeNode[] bindWithOpenedViews(CodeNode[] codeNodes, ViewFinder viewFinder) { CodeNode[] remainToDisplay = codeNodes; for (IViewReference reference : viewFinder.existingViews()) { ViewReference viewRef = viewFinder.showView(reference); if (viewRef == null) continue; boolean[] displayed = viewRef.provide(remainToDisplay); remainToDisplay = removeDisplayed(displayed, remainToDisplay); if (remainToDisplay.length == 0) break; } return remainToDisplay; } private CodeNode[] removeDisplayed(boolean[] displayed, CodeNode[] codeNodes) { List<CodeNode> remainToDisplay = new ArrayList<CodeNode>(); for (int i = 0; i < codeNodes.length; i++) if (!displayed[i]) remainToDisplay.add(codeNodes[i]); CodeNode[] result = new CodeNode[remainToDisplay.size()]; remainToDisplay.toArray(result); return result; } // displayAndBindView need to call the ViewBinder from within // a UI thread inside a syncExec. Therefore, this method cannot be // synchronized public void displayAndBindView(CodeNode[] codeNodes, String viewID) { ViewFinder viewFinder = new ViewFinder(viewID); CodeNode[] remainToDisplay = bindWithOpenedViews(codeNodes, viewFinder); if (remainToDisplay.length == 0) return; bindWithNewView(codeNodes, viewFinder); } public void displayAndBindView(CodeNode codeNodes, String viewID) { displayAndBindView(new CodeNode[] { codeNodes }, viewID); } public List<ViewProviderReference> findViewProviders(CodeNode codeNode) { return viewProviders.findViews(codeNode); } void register(ClockViews clockViews) { ClockViews previous = clockToView.put(clockViews.clock(), clockViews); assert previous == null; } public ClockViews removeClock(Clock clock) { return clockToView.remove(clock); } public void bind(Clock clock, SyncView view) { ClockViews clockViews = clockToView.get(clock); if (clockViews == null) return; clockViews.addView(view); } public void unbind(Clock clock, SyncView view) { ClockViews clockViews = clockToView.get(clock); if (clockViews == null) return; clockViews.removeView(view); } public void disposeView(SyncView view) { synchronized (clockToView) { for (Map.Entry<Clock, ClockViews> entry : clockToView.entrySet()) entry.getValue().removeView(view); } ZephyrPluginCore.viewScheduler().disposeView(view); } }
package org.joda.time.format; import java.io.IOException; import java.io.Writer; /** * Utility methods used by formatters. * <p> * FormatUtils is thread-safe and immutable. * * @author Brian S O'Neill * @since 1.0 */ public class FormatUtils { private static final double LOG_10 = Math.log(10); /** * Restricted constructor. */ private FormatUtils() { } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and appends it to the given buffer. * * <p>This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void appendPaddedInteger(StringBuffer buf, int value, int size) { if (value < 0) { buf.append('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { for (; size > 10; size buf.append('0'); } buf.append("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { for (; size > 1; size buf.append('0'); } buf.append((char)(value + '0')); } else if (value < 100) { for (; size > 2; size buf.append('0'); } // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; buf.append((char) (d + '0')); // Append remainder by calculating (value - d * 10). buf.append((char) (value - (d << 3) - (d << 1) + '0')); } else { int digits; if (value < 1000) { digits = 3; } else if (value < 10000) { digits = 4; } else { digits = (int)(Math.log(value) / LOG_10) + 1; } for (; size > digits; size buf.append('0'); } buf.append(Integer.toString(value)); } } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and appends it to the given buffer. * * <p>This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void appendPaddedInteger(StringBuffer buf, long value, int size) { int intValue = (int)value; if (intValue == value) { appendPaddedInteger(buf, intValue, size); } else if (size <= 19) { buf.append(Long.toString(value)); } else { if (value < 0) { buf.append('-'); if (value != Long.MIN_VALUE) { value = -value; } else { for (; size > 19; size buf.append('0'); } buf.append("9223372036854775808"); return; } } int digits = (int)(Math.log(value) / LOG_10) + 1; for (; size > digits; size buf.append('0'); } buf.append(Long.toString(value)); } } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and writes it to the given writer. * * <p>This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void writePaddedInteger(Writer out, int value, int size) throws IOException { if (value < 0) { out.write('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { for (; size > 10; size out.write('0'); } out.write("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { for (; size > 1; size out.write('0'); } out.write(value + '0'); } else if (value < 100) { for (; size > 2; size out.write('0'); } // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; out.write(d + '0'); // Append remainder by calculating (value - d * 10). out.write(value - (d << 3) - (d << 1) + '0'); } else { int digits; if (value < 1000) { digits = 3; } else if (value < 10000) { digits = 4; } else { digits = (int)(Math.log(value) / LOG_10) + 1; } for (; size > digits; size out.write('0'); } out.write(Integer.toString(value)); } } /** * Converts an integer to a string, prepended with a variable amount of '0' * pad characters, and writes it to the given writer. * * <p>This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string * @param size minumum amount of digits to append */ public static void writePaddedInteger(Writer out, long value, int size) throws IOException { int intValue = (int)value; if (intValue == value) { writePaddedInteger(out, intValue, size); } else if (size <= 19) { out.write(Long.toString(value)); } else { if (value < 0) { out.write('-'); if (value != Long.MIN_VALUE) { value = -value; } else { for (; size > 19; size out.write('0'); } out.write("9223372036854775808"); return; } } int digits = (int)(Math.log(value) / LOG_10) + 1; for (; size > digits; size out.write('0'); } out.write(Long.toString(value)); } } /** * Converts an integer to a string, and appends it to the given buffer. * * <p>This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string */ public static void appendUnpaddedInteger(StringBuffer buf, int value) { if (value < 0) { buf.append('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { buf.append("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { buf.append((char)(value + '0')); } else if (value < 100) { // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; buf.append((char) (d + '0')); // Append remainder by calculating (value - d * 10). buf.append((char) (value - (d << 3) - (d << 1) + '0')); } else { buf.append(Integer.toString(value)); } } /** * Converts an integer to a string, and appends it to the given buffer. * * <p>This method is optimized for converting small values to strings. * * @param buf receives integer converted to a string * @param value value to convert to a string */ public static void appendUnpaddedInteger(StringBuffer buf, long value) { int intValue = (int)value; if (intValue == value) { appendUnpaddedInteger(buf, intValue); } else { buf.append(Long.toString(value)); } } /** * Converts an integer to a string, and writes it to the given writer. * * <p>This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string */ public static void writeUnpaddedInteger(Writer out, int value) throws IOException { if (value < 0) { out.write('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { out.write("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { out.write(value + '0'); } else if (value < 100) { // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; out.write(d + '0'); // Append remainder by calculating (value - d * 10). out.write(value - (d << 3) - (d << 1) + '0'); } else { out.write(Integer.toString(value)); } } /** * Converts an integer to a string, and writes it to the given writer. * * <p>This method is optimized for converting small values to strings. * * @param out receives integer converted to a string * @param value value to convert to a string */ public static void writeUnpaddedInteger(Writer out, long value) throws IOException { int intValue = (int)value; if (intValue == value) { writeUnpaddedInteger(out, intValue); } else { out.write(Long.toString(value)); } } /** * Calculates the number of decimal digits for the given value, * including the sign. */ public static int calculateDigitCount(long value) { if (value < 0) { if (value != Long.MIN_VALUE) { return calculateDigitCount(-value) + 1; } else { return 20; } } return (value < 10 ? 1 : (value < 100 ? 2 : (value < 1000 ? 3 : (value < 10000 ? 4 : ((int)(Math.log(value) / LOG_10) + 1))))); } static int parseTwoDigits(String text, int position) { int value = text.charAt(position) - '0'; return ((value << 3) + (value << 1)) + text.charAt(position + 1) - '0'; } static String createErrorMessage(final String text, final int errorPos) { int sampleLen = errorPos + 20; String sampleText; if (text.length() <= sampleLen + 3) { sampleText = text; } else { sampleText = text.substring(0, sampleLen).concat("..."); } if (errorPos <= 0) { return "Invalid format: \"" + sampleText + '"'; } if (errorPos >= text.length()) { return "Invalid format: \"" + sampleText + "\" is too short"; } return "Invalid format: \"" + sampleText + "\" is malformed at \"" + sampleText.substring(errorPos) + '"'; } }
package org.jaxen.dom; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jaxen.JaxenException; import org.jaxen.XPath; import org.w3c.dom.Attr; import org.w3c.dom.Element; import junit.framework.TestCase; public class NamespaceTest extends TestCase { private org.w3c.dom.Document doc; public NamespaceTest(String name) { super(name); } protected void setUp() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); doc = factory.newDocumentBuilder().newDocument(); } public void testMultipleNamespaceAxis() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: child.setAttributeNS("http: root.appendChild(child); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(child); assertEquals(3, result.size()); } public void testNumberOfNamespaceNodes() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); XPath xpath = new DOMXPath("//namespace::node()"); List result = xpath.selectNodes(doc); assertEquals(3, result.size()); // 1 for xml prefix on root; 1 for foo prefix on child; 1 for xml prefix on child } public void testNamespaceAxis() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(child); assertEquals(2, result.size()); } public void testUnprefixedNamespaceAxis() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(child); assertEquals(2, result.size()); } public void testNamespaceNodesReadFromAttributes() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Attr a = doc.createAttributeNS("http: a.setNodeValue("value"); root.setAttributeNode(a); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(root); // one for the xml prefix; one from the attribute node assertEquals(2, result.size()); } }
package org.firstinspires.ftc.team7316.util.hardware; import android.graphics.Color; import android.webkit.CookieManager; import com.qualcomm.robotcore.hardware.AnalogInput; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.DistanceSensor; import com.qualcomm.robotcore.hardware.GyroSensor; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.LightSensor; import com.qualcomm.robotcore.hardware.OpticalDistanceSensor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.TouchSensor; import com.qualcomm.robotcore.hardware.UltrasonicSensor; import org.firstinspires.ftc.robotcore.external.Telemetry; //MAKE SURE TO CALL setHardwareMap AT LEAST ONCE public class Hardware { public static Hardware instance = null; public static final String tag = "IronPanthers"; private static Telemetry telemetry; private static final String LEFT_DRIVE_MOTOR_NAME = "mdl"; private static final String RIGHT_DRIVE_MOTOR_NAME = "mdr"; private static final String INTAKE_MOTOR_NAME = "im"; private static final String CATAPULT_MOTOR_NAME = "cm"; private static final String CAP_BALL_MOTOR_NAME = "cpm"; private static final String LEFT_BEACON_SERVO_NAME = "leftServo"; private static final String RIGHT_BEACON_SERVO_NAME = "rightServo"; private static final String CATAPULT_SENSOR_NAME = "cat"; private static final String GYRO_SENSOR_NAME = "gyro"; private static final String COLOR_SENSOR_NAME = "color"; private static final String LIGHT_SENSOR_NAME_RIGHT = "lir"; private static final String LIGHT_SENSOR_NAME_LEFT = "lil"; private static final String TOUCH_SENSOR_NAME = "touch"; private static final String INTAKE_UP_SERVO_NAME = "inUp"; private static final String FRONT_SIDE_IR_NAME = "fi"; private static final String BACK_SIDE_IR_NAME = "bi"; public DcMotor leftDriveMotor; public DcMotor rightDriveMotor; //boosted motor public DcMotor catapultMotor; public DcMotor intakeMotor; public Servo leftBeaconServo, rightBeaconServo, intakeUpServo; public OpticalDistanceSensor catapultSensor, lightSensorLeft, lightSensorRight; public GyroSensor gyroSensor; public DcMotor capBallMotor; public ColorSensor colorSensor; public TouchSensor touchSensor; public SharpIRSensor frontSideInfaredSensor, backSideInfaredSensor; public double jankDelta = 0; public double jankSum = 0; public Hardware (HardwareMap map) { leftDriveMotor = map.dcMotor.get(LEFT_DRIVE_MOTOR_NAME); leftDriveMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); leftDriveMotor.setDirection(DcMotorSimple.Direction.REVERSE); DcMotor rightMotor = map.dcMotor.get(RIGHT_DRIVE_MOTOR_NAME); rightMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); rightDriveMotor = new BoostedMotor(rightMotor, 1.05); /*rightDriveMotor = map.dcMotor.get(RIGHT_DRIVE_MOTOR_NAME); rightDriveMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);*/ //leftCatcherServo = map.servo.get(LEFT_CATCHER_SERVO_NAME); //rightCatcherServo = map.servo.get(RIGHT_CATCHER_SERVO_NAME); catapultMotor = map.dcMotor.get(CATAPULT_MOTOR_NAME); catapultMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); catapultSensor = map.opticalDistanceSensor.get(CATAPULT_SENSOR_NAME); intakeMotor = map.dcMotor.get(INTAKE_MOTOR_NAME); intakeMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); leftBeaconServo = map.servo.get(LEFT_BEACON_SERVO_NAME); rightBeaconServo = map.servo.get(RIGHT_BEACON_SERVO_NAME); lightSensorLeft = map.opticalDistanceSensor.get(LIGHT_SENSOR_NAME_LEFT); lightSensorRight = map.opticalDistanceSensor.get(LIGHT_SENSOR_NAME_RIGHT); gyroSensor = map.gyroSensor.get(GYRO_SENSOR_NAME); colorSensor = map.colorSensor.get(COLOR_SENSOR_NAME); //distanceSensor = map.ultrasonicSensor.get(DISTANCE_SENSOR_NAME); intakeUpServo = map.servo.get(INTAKE_UP_SERVO_NAME); touchSensor = map.touchSensor.get(TOUCH_SENSOR_NAME); capBallMotor = map.dcMotor.get(CAP_BALL_MOTOR_NAME); frontSideInfaredSensor = new SharpIRSensor(map.analogInput.get(FRONT_SIDE_IR_NAME)); backSideInfaredSensor = new SharpIRSensor(map.analogInput.get(BACK_SIDE_IR_NAME)); } public static void setHardwareMap(HardwareMap map) { instance = new Hardware(map); } public static void setTelemetry(Telemetry telemetry) { Hardware.telemetry = telemetry; } public static void log(String caption, Object value) { if (telemetry != null) { telemetry.addData(caption, value); } } }
package jmetest.renderer.loader; import com.jme.app.SimpleGame; import com.jme.scene.model.XMLparser.*; import com.jme.scene.Node; import com.jme.scene.state.TextureState; import com.jme.scene.shape.Box; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.util.TextureManager; import com.jme.image.Texture; import java.net.URL; import java.io.*; public class TestBinaryXML extends SimpleGame{ public static void main(String[] args) { TestBinaryXML app=new TestBinaryXML(); app.setDialogBehaviour(SimpleGame.FIRSTRUN_OR_NOCONFIGFILE_SHOW_PROPS_DIALOG); app.start(); } protected void simpleInitGame() { try { doSimple(); } catch (IOException e) { System.out.println("Send error: " + e.getMessage()); System.exit(0); } } private void doSimple() throws IOException{ // Send XML file to jME binary XMLtoBinary c1=new XMLtoBinary(); URL xmldoc=TestBinaryXML.class.getClassLoader().getResource("jmetest/data/XML documents/newSampleScene.xml"); ByteArrayOutputStream BO1=new ByteArrayOutputStream(); c1.sendXMLtoBinary(xmldoc.openStream(),BO1); // Send jME binary to a jME Scene Graph JmeBinaryReader jbr=new JmeBinaryReader(); Node fileScene=jbr.loadBinaryFormat(new ByteArrayInputStream(BO1.toByteArray())); // Send a jME SceneGraph to jME Binary JmeBinaryWriter jbw=new JmeBinaryWriter(); ByteArrayOutputStream BO2=new ByteArrayOutputStream(); long time=System.currentTimeMillis(); jbw.writeScene(fileScene,BO2); System.out.println("Finished Writting time:" + (System.currentTimeMillis()-time)); // Send the new jME binary to a jME SceneGraph and attach it. fileScene=jbr.loadBinaryFormat(new ByteArrayInputStream(BO2.toByteArray())); rootNode.attachChild(fileScene); } }
package uk.ac.cam.cstibhotel.otcanalyser.communicationlayer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import uk.ac.cam.cstibhotel.otcanalyser.database.Database; import uk.ac.cam.cstibhotel.otcanalyser.gui.SearchWindow; import uk.ac.cam.cstibhotel.otcanalyser.gui.StatusBar; import uk.ac.cam.cstibhotel.otcanalyser.trade.AssetClass; import uk.ac.cam.cstibhotel.otcanalyser.trade.TradeType; import uk.ac.cam.cstibhotel.otcanalyser.trade.UPIStrings; public class CommunicationLayer { // A list of all components expecting the results of a search query private static ArrayList<SearchListener> searchListeners; // Singleton instance of the communication layer private static CommunicationLayer communicationLayer; public static CommunicationLayer getInstance() { if (communicationLayer == null) { communicationLayer = new CommunicationLayer(); } return communicationLayer; } private CommunicationLayer() { searchListeners = new ArrayList<SearchListener>(); } // Adds a listener to the list of searchListeners to allow them to // receive results of a query public static void registerListener(SearchListener s) { searchListeners.add(s); } // Creates a Search and then sends it to the database public static void search() throws ParseException { Search s = new Search(); String tradeType = (String) SearchWindow.getInstance().TradeType.getSelectedItem(); if (tradeType.equals("Swap")) { s.setTradeType(TradeType.SWAP); } else if (tradeType.equals("Option")) { s.setTradeType(TradeType.OPTION); } s.setAsset(SearchWindow.getInstance().UnderLyingAsset.getText()); try { s.setMinPrice(Integer.toUnsignedLong( (int) SearchWindow.getInstance().minValue.getValue())); s.setMaxPrice(Integer.toUnsignedLong( (int) SearchWindow.getInstance().maxValue.getValue())); } catch (NumberFormatException e) { StatusBar.setMessage("Error: Price fields must contain integers", 1); } s.setCurrency(SearchWindow.getInstance().currency.getText()); int day = (int) SearchWindow.getInstance().StartDate.Day.getSelectedItem(); String monthString = (String) SearchWindow.getInstance().StartDate.Months.getSelectedItem(); Calendar cal = Calendar.getInstance(); cal.setTime(new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthString)); int month = cal.get(Calendar.MONTH); int year = (int) SearchWindow.getInstance().StartDate.Year.getSelectedItem(); cal.set(year, month, day); Date startTime = cal.getTime(); s.setStartTime(startTime); day = (int) SearchWindow.getInstance().EndDate.Day.getSelectedItem(); monthString = (String) SearchWindow.getInstance().EndDate.Months.getSelectedItem(); cal.setTime(new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthString)); month = cal.get(Calendar.MONTH); year = (int) SearchWindow.getInstance().EndDate.Year.getSelectedItem(); cal.set(year, month, day); Date endTime = cal.getTime(); s.setEndTime(endTime); String fullTaxonomy = ""; String selectedAsset = (String) SearchWindow.getInstance().tax.Asset.getSelectedItem(); int assetIndex = SearchWindow.getInstance().tax.Asset.getSelectedIndex(); int baseIndex = SearchWindow.getInstance().tax.BaseClass.getSelectedIndex(); int subIndex = SearchWindow.getInstance().tax.SubClass.getSelectedIndex(); // Add the Asset to the taxonomy string fullTaxonomy += UPIStrings.Assets[assetIndex]; fullTaxonomy += ":"; /* * Add the Base Product and Sub-product to the taxonomy string * Also set the AssetClass while we're here to make code slightly neater */ switch (selectedAsset) { case "Credit": s.setAssetClass(AssetClass.CREDIT); fullTaxonomy += UPIStrings.CreditBaseProducts[baseIndex]; fullTaxonomy += ":"; if (UPIStrings.CreditSubProducts[baseIndex].length != 0) { fullTaxonomy += UPIStrings.CreditSubProducts[baseIndex][subIndex]; } break; case "Interest": s.setAssetClass(AssetClass.RATES); fullTaxonomy += UPIStrings.InterestBaseProducts[baseIndex]; fullTaxonomy += ":"; if (UPIStrings.InterestSubProducts[baseIndex].length != 0) { fullTaxonomy += UPIStrings.InterestSubProducts[baseIndex][subIndex]; } break; case "Commodity": s.setAssetClass(AssetClass.COMMODITY); fullTaxonomy += UPIStrings.CommodityBaseProducts[baseIndex]; fullTaxonomy += ":"; if (UPIStrings.CommoditySubProducts[baseIndex].length != 0) { fullTaxonomy += UPIStrings.CommoditySubProducts[baseIndex][subIndex]; } break; case "Foreign Exchange": s.setAssetClass(AssetClass.FOREX); fullTaxonomy += UPIStrings.ForexBaseProducts[baseIndex]; fullTaxonomy += ":"; if (UPIStrings.ForexSubProducts[baseIndex].length != 0) { fullTaxonomy += UPIStrings.ForexSubProducts[baseIndex][subIndex]; } break; case "Equity": s.setAssetClass(AssetClass.EQUITY); fullTaxonomy += UPIStrings.EquityBaseProducts[baseIndex]; fullTaxonomy += ":"; if (UPIStrings.EquitySubProducts[baseIndex].length != 0) { fullTaxonomy += UPIStrings.EquitySubProducts[baseIndex][subIndex]; } break; } s.setUPI(fullTaxonomy); // Get the result from the database SearchResult result = Database.getDB().search(s); // Send it to each member of searchListeners for (SearchListener l : searchListeners) { l.getSearchResult(result); } } }
import org.junit.Test; import java.util.LinkedList; import java.util.Queue; import static org.junit.Assert.*; public class UserGraphTest { private UserGraph generateTestUserGraph() { User coach1 = new User.Builder().build("Coach1"); User coach2 = new User.Builder().build("Coach2"); User student1 = new User.Builder().addCoach(coach1).build("Student1"); User student2 = new User.Builder().addCoach(coach1).build("Student2"); User student3 = new User.Builder().addCoach(coach1).addCoach(coach2).build("Student3"); User student4 = new User.Builder().addCoach(coach2).build("Student4"); User student5 = new User.Builder().addCoach(coach2).build("Student5"); User student6 = new User.Builder().build("Student6"); return new UserGraph.Builder() .addUser(coach1) .addUser(coach2) .addUser(student1) .addUser(student2) .addUser(student3) .addUser(student4) .addUser(student5) .addUser(student6) .build(); } @Test public void testInfectSingleUser() { User user1 = new User.Builder().build("TestUser"); Queue<User> infectQueue = new LinkedList<>(); Version newVersion = new Version(1, 1, 1); UserGraph testGraph = new UserGraph.Builder().addUser(user1).build(); testGraph.infectUser(user1, infectQueue, newVersion); assertEquals("Version updated correctly", new Version(1, 1, 1), user1.getCurrentVersion()); assertEquals("No users added to queue", new LinkedList<User>(), infectQueue); } @Test public void testInfectSeveralUsers() { UserGraph testGraph = generateTestUserGraph(); testGraph.getUser("Student5").addStudent(testGraph.getUser("Student1")); Queue<User> infectQueue = new LinkedList<>(); Version newVersion = new Version(1, 1, 1); testGraph.infectUser(testGraph.getUser("Student5"), infectQueue, newVersion); Queue<User> expectedQueue = new LinkedList<>(); expectedQueue.add(testGraph.getUser("Coach2")); expectedQueue.add(testGraph.getUser("Student1")); assertEquals("Version updated correctly", new Version(1, 1, 1), testGraph.getUser("Student5").getCurrentVersion()); assertEquals("No users added to queue", expectedQueue, infectQueue); } @Test public void testTotalInfection() { UserGraph testGraph = generateTestUserGraph(); Version newVersion = new Version(1, 1, 1); testGraph.totalInfection(testGraph.getUser("Student1"), newVersion); for (String username : testGraph.getUsers().keySet()) { User user = testGraph.getUser(username); if (!username.equals("Student6")) { assertEquals("User not infected", new Version(1, 1, 1), user.getCurrentVersion()); } else { assertEquals("User infected but shouldn't be", new Version(1, 0, 0), user.getCurrentVersion()); } } } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.util.DateFormat; import net.fortuna.ical4j.util.DateTimeFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Defines a recurrence. * * @author benfortuna */ public class Recur implements Serializable { private static final long serialVersionUID = -7333226591784095142L; private static final String FREQ = "FREQ"; private static final String UNTIL = "UNTIL"; private static final String COUNT = "COUNT"; private static final String INTERVAL = "INTERVAL"; private static final String BYSECOND = "BYSECOND"; private static final String BYMINUTE = "BYMINUTE"; private static final String BYHOUR = "BYHOUR"; private static final String BYDAY = "BYDAY"; private static final String BYMONTHDAY = "BYMONTHDAY"; private static final String BYYEARDAY = "BYYEARDAY"; private static final String BYWEEKNO = "BYWEEKNO"; private static final String BYMONTH = "BYMONTH"; private static final String BYSETPOS = "BYSETPOS"; private static final String WKST = "WKST"; // frequencies.. public static final String SECONDLY = "SECONDLY"; public static final String MINUTELY = "MINUTELY"; public static final String HOURLY = "HOURLY"; public static final String DAILY = "DAILY"; public static final String WEEKLY = "WEEKLY"; public static final String MONTHLY = "MONTHLY"; public static final String YEARLY = "YEARLY"; private static Log log = LogFactory.getLog(Recur.class); private String frequency; private Date until; private int count = -1; private int interval = -1; private NumberList secondList; private NumberList minuteList; private NumberList hourList; private WeekDayList dayList; private NumberList monthDayList; private NumberList yearDayList; private NumberList weekNoList; private NumberList monthList; private NumberList setPosList; private String weekStartDay; private Map experimentalValues = new HashMap(); // The order, or layout, of the date as it appears in a string // e.g. 20050415T093000 (April 15th, 9:30:00am) private static final int[] DATE_ORDER = {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND}; /** * Constructor. * * @param aValue * a string representation of a recurrence. * @throws ParseException * thrown when the specified string contains an invalid * representation of an UNTIL date value */ public Recur(final String aValue) throws ParseException { for (StringTokenizer t = new StringTokenizer(aValue, ";="); t .hasMoreTokens();) { String token = t.nextToken(); if (FREQ.equals(token)) { frequency = t.nextToken(); } else if (UNTIL.equals(token)) { String untilString = t.nextToken(); try { until = DateFormat.getInstance().parse(untilString); } catch (ParseException pe) { until = DateTimeFormat.getInstance().parse(untilString); } } else if (COUNT.equals(token)) { count = Integer.parseInt(t.nextToken()); } else if (INTERVAL.equals(token)) { interval = Integer.parseInt(t.nextToken()); } else if (BYSECOND.equals(token)) { secondList = new NumberList(t.nextToken()); } else if (BYMINUTE.equals(token)) { minuteList = new NumberList(t.nextToken()); } else if (BYHOUR.equals(token)) { hourList = new NumberList(t.nextToken()); } else if (BYDAY.equals(token)) { dayList = new WeekDayList(t.nextToken()); } else if (BYMONTHDAY.equals(token)) { monthDayList = new NumberList(t.nextToken()); } else if (BYYEARDAY.equals(token)) { yearDayList = new NumberList(t.nextToken()); } else if (BYWEEKNO.equals(token)) { weekNoList = new NumberList(t.nextToken()); } else if (BYMONTH.equals(token)) { monthList = new NumberList(t.nextToken()); } else if (BYSETPOS.equals(token)) { setPosList = new NumberList(t.nextToken()); } else if (WKST.equals(token)) { weekStartDay = t.nextToken(); } // assume experimental value.. else { experimentalValues.put(token, t.nextToken()); } } } /** * @param frequency * @param until */ public Recur(final String frequency, final Date until) { this.frequency = frequency; this.until = until; } /** * @param frequency * @param count */ public Recur(final String frequency, final int count) { this.frequency = frequency; this.count = count; } /** * @return Returns the dayList. */ public final WeekDayList getDayList() { if (dayList == null) { dayList = new WeekDayList(); } return dayList; } /** * @return Returns the hourList. */ public final NumberList getHourList() { if (hourList == null) { hourList = new NumberList(); } return hourList; } /** * @return Returns the minuteList. */ public final NumberList getMinuteList() { if (minuteList == null) { minuteList = new NumberList(); } return minuteList; } /** * @return Returns the monthDayList. */ public final NumberList getMonthDayList() { if (monthDayList == null) { monthDayList = new NumberList(); } return monthDayList; } /** * @return Returns the monthList. */ public final NumberList getMonthList() { if (monthList == null) { monthList = new NumberList(); } return monthList; } /** * @return Returns the secondList. */ public final NumberList getSecondList() { if (secondList == null) { secondList = new NumberList(); } return secondList; } /** * @return Returns the setPosList. */ public final NumberList getSetPosList() { if (setPosList == null) { setPosList = new NumberList(); } return setPosList; } /** * @return Returns the weekNoList. */ public final NumberList getWeekNoList() { if (weekNoList == null) { weekNoList = new NumberList(); } return weekNoList; } /** * @return Returns the yearDayList. */ public final NumberList getYearDayList() { if (yearDayList == null) { yearDayList = new NumberList(); } return yearDayList; } /** * @return Returns the count. */ public final int getCount() { return count; } /** * @return Returns the experimentalValues. */ public final Map getExperimentalValues() { return experimentalValues; } /** * @return Returns the frequency. */ public final String getFrequency() { return frequency; } /** * @return Returns the interval. */ public final int getInterval() { return interval; } /** * @return Returns the until. */ public final Date getUntil() { return until; } /** * @return Returns the weekStartDay. */ public final String getWeekStartDay() { return weekStartDay; } /** * @param weekStartDay The weekStartDay to set. */ public final void setWeekStartDay(final String weekStartDay) { this.weekStartDay = weekStartDay; } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); b.append(FREQ); b.append('='); b.append(frequency); if (weekStartDay != null) { b.append(';'); b.append(WKST); b.append('='); b.append(weekStartDay); } if (interval >= 1) { b.append(';'); b.append(INTERVAL); b.append('='); b.append(interval); } if (until != null) { b.append(';'); b.append(UNTIL); b.append('='); // although UNTIL may be either date or date-time, // for now we'll assume its a date and output as such.. b.append(DateFormat.getInstance().format(until)); // TODO: Implement option for date-time until. Note: date-time // representations should always be in UTC time. } if (count >= 1) { b.append(';'); b.append(COUNT); b.append('='); b.append(count); } if (!getMonthList().isEmpty()) { b.append(';'); b.append(BYMONTH); b.append('='); b.append(monthList); } if (!getWeekNoList().isEmpty()) { b.append(';'); b.append(BYWEEKNO); b.append('='); b.append(weekNoList); } if (!getYearDayList().isEmpty()) { b.append(';'); b.append(BYYEARDAY); b.append('='); b.append(yearDayList); } if (!getMonthDayList().isEmpty()) { b.append(';'); b.append(BYMONTHDAY); b.append('='); b.append(monthDayList); } if (!getDayList().isEmpty()) { b.append(';'); b.append(BYDAY); b.append('='); b.append(dayList); } if (!getHourList().isEmpty()) { b.append(';'); b.append(BYHOUR); b.append('='); b.append(hourList); } if (!getMinuteList().isEmpty()) { b.append(';'); b.append(BYMINUTE); b.append('='); b.append(minuteList); } if (!getSecondList().isEmpty()) { b.append(';'); b.append(BYSECOND); b.append('='); b.append(secondList); } if (!getSetPosList().isEmpty()) { b.append(';'); b.append(BYSETPOS); b.append('='); b.append(setPosList); } return b.toString(); } /** * Returns a list of start dates in the specified period represented by this recur. * Any date fields not specified by this recur are retained from the period start, * and as such you should ensure the period start is initialised correctly. * @param periodStart the start of the period * @param periodEnd the end of the period * @param value the type of dates to generate (i.e. date/date-time) * @return a list of dates */ public final DateList getDates(final Date periodStart, final Date periodEnd, final Value value) { return getDates(periodStart, periodStart, periodEnd, value); } /** * Returns a list of start dates in the specified period represented * by this recur. This method includes a base date argument, which * indicates the start of the fist occurrence of this recurrence. * * The base date is used to inject default values to return a set of dates in * the correct format. For example, if the search start date (start) is * Wed, Mar 23, 12:19PM, but the recurrence is Mon - Fri, 9:00AM - 5:00PM, * the start dates returned should all be at 9:00AM, and not 12:19PM. * * @return a list of dates represented by this recur instance * @param base the start date of this Recurrence's first instance * @param periodStart the start of the period * @param periodEnd the end of the period * @param value the type of dates to generate (i.e. date/date-time) */ public final DateList getDates(final Date base, final Date periodStart, final Date periodEnd, final Value value) { DateList dates = new DateList(value); Date start = (Date) periodStart.clone(); // Should never happen! base is always required! if (base == null) { return dates; } // We don't want to see or search any dates that occurr before the // first instance of this recurrence. if (start.before(base)) { start = base; } int lowestVariableField = 9999; if (YEARLY.equals(frequency)) { lowestVariableField = Calendar.YEAR; } else if (MONTHLY.equals(frequency)) { lowestVariableField = Calendar.MONTH; } else if (WEEKLY.equals(frequency)) { lowestVariableField = Calendar.DAY_OF_MONTH; } else if (DAILY.equals(frequency)) { lowestVariableField = Calendar.DAY_OF_MONTH; } else if (HOURLY.equals(frequency)) { lowestVariableField = Calendar.HOUR_OF_DAY; } else if (MINUTELY.equals(frequency)) { lowestVariableField = Calendar.MINUTE; } else if (SECONDLY.equals(frequency)) { lowestVariableField = Calendar.SECOND; } Calendar baseCalendar = Calendar.getInstance(); baseCalendar.setTime(base); Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.MILLISECOND, 0); // reset fields where BY* rules apply.. if (!getMonthList().isEmpty()) { //cal.set(Calendar.MONTH, 0); lowestVariableField = Calendar.MONTH < lowestVariableField ? Calendar.MONTH : lowestVariableField; } if (!getWeekNoList().isEmpty()) { //cal.set(Calendar.WEEK_OF_YEAR, 1); lowestVariableField = Calendar.DAY_OF_MONTH < lowestVariableField ? Calendar.DAY_OF_MONTH : lowestVariableField; } if (!getYearDayList().isEmpty()) { //cal.set(Calendar.DAY_OF_YEAR, 1); lowestVariableField = Calendar.DAY_OF_MONTH < lowestVariableField ? Calendar.DAY_OF_MONTH : lowestVariableField; } if (!getMonthDayList().isEmpty()) { //cal.set(Calendar.DAY_OF_MONTH, 1); lowestVariableField = Calendar.DAY_OF_MONTH < lowestVariableField ? Calendar.DAY_OF_MONTH : lowestVariableField; } if (!getDayList().isEmpty()) { //cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); lowestVariableField = Calendar.DAY_OF_MONTH < lowestVariableField ? Calendar.DAY_OF_MONTH : lowestVariableField; } if (!getHourList().isEmpty()) { //cal.set(Calendar.HOUR_OF_DAY, 0); lowestVariableField = Calendar.HOUR_OF_DAY < lowestVariableField ? Calendar.HOUR_OF_DAY : lowestVariableField; } if (!getMinuteList().isEmpty()) { //cal.set(Calendar.MINUTE, 0); lowestVariableField = Calendar.MINUTE < lowestVariableField ? Calendar.MINUTE : lowestVariableField; } if (!getSecondList().isEmpty()) { //cal.set(Calendar.SECOND, 0); lowestVariableField = Calendar.SECOND < lowestVariableField ? Calendar.SECOND : lowestVariableField; } // Set everything to the right of the LVF to match the DTSTART. // Everything else comes from the query start date. int[] matchFields = getMatchFields(lowestVariableField); for (int i = 0; i < matchFields.length; i++) { cal.set(matchFields[i], baseCalendar.get(matchFields[i])); } // Deal with rolling over to the next time period if necessary. if (cal.getTime().before(periodStart)) { cal.add(lowestVariableField, 1); } // Weekly frequencies need to match up the week day. (i.e. if it's // Friday, and that's not part of our criteria, keep adding a day // until they match). /*if (getFrequency().equals(WEEKLY)) { while (cal.get(Calendar.DAY_OF_WEEK) != dtStartCalendar.get(Calendar.DAY_OF_WEEK)) { cal.add(Calendar.DAY_OF_MONTH, 1); } }*/ // apply frequency/interval rules.. if (getUntil() != null) { while (!cal.getTime().after(getUntil()) && !(periodEnd != null && cal.getTime().after(periodEnd))) { dates.add(cal.getTime()); increment(cal); } } else if (getCount() >= 1) { for (int i = 0; i < getCount() && !(periodEnd != null && cal.getTime().after(periodEnd)); i++) { dates.add(cal.getTime()); increment(cal); } } else if (periodEnd != null) { while (!cal.getTime().after(periodEnd)) { dates.add(cal.getTime()); increment(cal); } } else { // if no end-point specified we can't calculate a finite // set of dates.. return dates; } // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after FREQUENCY/INTERVAL processing: " + dates); } dates = getMonthVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMONTH processing: " + dates); } dates = getWeekNoVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYWEEKNO processing: " + dates); } dates = getYearDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYYEARDAY processing: " + dates); } dates = getMonthDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMONTHDAY processing: " + dates); } dates = getDayVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYDAY processing: " + dates); } dates = getHourVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYHOUR processing: " + dates); } dates = getMinuteVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYMINUTE processing: " + dates); } dates = getSecondVariants(dates); // debugging.. if (log.isDebugEnabled()) { log.debug("Dates after BYSECOND processing: " + dates); } // final processing.. for (int i = 0; i < dates.size(); i++) { Date date = (Date) dates.get(i); if (date.before(start)) { dates.remove(date); i } else if (periodEnd != null && date.after(periodEnd)) { dates.remove(date); i } else if (getUntil() != null && date.after(getUntil())) { dates.remove(date); i } else if (getCount() >= 1 && i >= getCount()) { dates.remove(date); i } } return dates; } /** * Return all the items to the right of LVF in a date string. * * @param lowestVariableField * @return */ private int[] getMatchFields(int lowestVariableField) { int[] matchFields = new int[0]; int lvfIndex = getDateOrderIndex(lowestVariableField); for (int i = 0; i < DATE_ORDER.length; i++) { int nextItem = DATE_ORDER[i]; if (i > lvfIndex) { int[] tmpArray = matchFields; matchFields = new int[tmpArray.length + 1]; System.arraycopy(tmpArray, 0, matchFields, 0, tmpArray.length); matchFields[matchFields.length - 1] = nextItem; } } return matchFields; } /** * Return the index of this item in the DATE_ORDER array. * * @param val * @return */ private int getDateOrderIndex(int val) { for (int i = 0; i < DATE_ORDER.length; i++) { int nextVal = DATE_ORDER[i]; if (nextVal == val) { return i; } } return -1; } /** * Increments the specified calendar according to the * frequency and interval specified in this recurrence * rule. * @param cal a java.util.Calendar to increment */ private void increment(final Calendar cal) { // initialise interval.. int calInterval = (getInterval() >= 1) ? getInterval() : 1; if (getFrequency() == SECONDLY) { cal.add(Calendar.SECOND, calInterval); } else if (MINUTELY.equals(getFrequency())) { cal.add(Calendar.MINUTE, calInterval); } else if (HOURLY.equals(getFrequency())) { cal.add(Calendar.HOUR_OF_DAY, calInterval); } else if (DAILY.equals(getFrequency())) { cal.add(Calendar.DAY_OF_YEAR, calInterval); } else if (WEEKLY.equals(getFrequency())) { cal.add(Calendar.WEEK_OF_YEAR, calInterval); } else if (MONTHLY.equals(getFrequency())) { cal.add(Calendar.MONTH, calInterval); } else if (YEARLY.equals(getFrequency())) { cal.add(Calendar.YEAR, calInterval); } } /** * Applies BYMONTH rules specified in this Recur instance to the * specified date list. If no BYMONTH rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMonthVariants(final DateList dates) { if (getMonthList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList monthlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getMonthList().iterator(); j.hasNext();) { Integer month = (Integer) j.next(); // Java months are zero-based.. cal.set(Calendar.MONTH, month.intValue() - 1); monthlyDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getWeekNoList().isEmpty() && getYearDayList().isEmpty() && getMonthDayList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(monthlyDates.get(setPos.intValue())); } else { setPosDates.add(monthlyDates.get(monthlyDates.size() + setPos.intValue())); } } return setPosDates; } return monthlyDates; } /** * Applies BYWEEKNO rules specified in this Recur instance to the * specified date list. If no BYWEEKNO rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getWeekNoVariants(final DateList dates) { if (getWeekNoList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList weekNoDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getWeekNoList().iterator(); j.hasNext();) { Integer weekNo = (Integer) j.next(); cal.set(Calendar.WEEK_OF_YEAR, getAbsWeekNo(cal.getTime(), weekNo.intValue())); weekNoDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getYearDayList().isEmpty() && getMonthDayList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(weekNoDates.get(setPos.intValue())); } else { setPosDates.add(weekNoDates.get(weekNoDates.size() + setPos.intValue())); } } return setPosDates; } return weekNoDates; } private int getAbsWeekNo(final Date date, final int weekNo) { if (weekNo == 0 || weekNo < -53 || weekNo > 53) { throw new IllegalArgumentException("Invalid week number [" + weekNo + "]"); } if (weekNo > 0) { return weekNo; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); // construct a list of possible week numbers.. List weeks = new ArrayList(); cal.set(Calendar.WEEK_OF_YEAR, 1); while (cal.get(Calendar.YEAR) == year) { weeks.add(new Integer(cal.get(Calendar.WEEK_OF_YEAR))); cal.add(Calendar.WEEK_OF_YEAR, 1); } return ((Integer) weeks.get(weeks.size() + weekNo)).intValue(); } /** * Applies BYYEARDAY rules specified in this Recur instance to the * specified date list. If no BYYEARDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getYearDayVariants(final DateList dates) { if (getYearDayList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList yearDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getYearDayList().iterator(); j.hasNext();) { Integer yearDay = (Integer) j.next(); cal.set(Calendar.DAY_OF_YEAR, getAbsYearDay(cal.getTime(), yearDay.intValue())); yearDayDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getMonthDayList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(yearDayDates.get(setPos.intValue())); } else { setPosDates.add(yearDayDates.get(yearDayDates.size() + setPos.intValue())); } } return setPosDates; } return yearDayDates; } private int getAbsYearDay(final Date date, final int yearDay) { if (yearDay == 0 || yearDay < -366 || yearDay > 366) { throw new IllegalArgumentException("Invalid year day [" + yearDay + "]"); } if (yearDay > 0) { return yearDay; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); // construct a list of possible year days.. List days = new ArrayList(); cal.set(Calendar.DAY_OF_YEAR, 1); while (cal.get(Calendar.YEAR) == year) { days.add(new Integer(cal.get(Calendar.DAY_OF_YEAR))); cal.add(Calendar.DAY_OF_YEAR, 1); } return ((Integer) days.get(days.size() + yearDay)).intValue(); } /** * Applies BYMONTHDAY rules specified in this Recur instance to the * specified date list. If no BYMONTHDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMonthDayVariants(final DateList dates) { if (getMonthDayList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList monthDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getMonthDayList().iterator(); j.hasNext();) { Integer monthDay = (Integer) j.next(); cal.set(Calendar.DAY_OF_YEAR, getAbsMonthDay(cal.getTime(), monthDay.intValue())); monthDayDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getDayList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(monthDayDates.get(setPos.intValue())); } else { setPosDates.add(monthDayDates.get(monthDayDates.size() + setPos.intValue())); } } return setPosDates; } return monthDayDates; } private int getAbsMonthDay(final Date date, final int monthDay) { if (monthDay == 0 || monthDay < -31 || monthDay > 31) { throw new IllegalArgumentException("Invalid month day [" + monthDay + "]"); } if (monthDay > 0) { return monthDay; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // construct a list of possible month days.. List days = new ArrayList(); cal.set(Calendar.DAY_OF_MONTH, 1); while (cal.get(Calendar.MONTH) == month) { days.add(new Integer(cal.get(Calendar.DAY_OF_MONTH))); cal.add(Calendar.DAY_OF_MONTH, 1); } return ((Integer) days.get(days.size() + monthDay)).intValue(); } /** * Applies BYDAY rules specified in this Recur instance to the * specified date list. If no BYDAY rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getDayVariants(final DateList dates) { if (getDayList().isEmpty()) { return dates; } DateList weekDayDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); for (Iterator j = getDayList().iterator(); j.hasNext();) { WeekDay weekDay = (WeekDay) j.next(); weekDayDates.addAll(getAbsWeekDays(date, weekDay)); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getHourList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(weekDayDates.get(setPos.intValue())); } else { setPosDates.add(weekDayDates.get(weekDayDates.size() + setPos.intValue())); } } return setPosDates; } return weekDayDates; } /** * Returns a list of applicable dates corresponding to the specified * week day in accordance with the frequency specified by this recurrence * rule. * @param date * @param weekDay * @return */ private List getAbsWeekDays(final Date date, final WeekDay weekDay) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int calDay = -1; if (WeekDay.SU.equals(weekDay)) { calDay = Calendar.SUNDAY; } else if (WeekDay.MO.equals(weekDay)) { calDay = Calendar.MONDAY; } else if (WeekDay.TU.equals(weekDay)) { calDay = Calendar.TUESDAY; } else if (WeekDay.WE.equals(weekDay)) { calDay = Calendar.WEDNESDAY; } else if (WeekDay.TH.equals(weekDay)) { calDay = Calendar.THURSDAY; } else if (WeekDay.FR.equals(weekDay)) { calDay = Calendar.FRIDAY; } else if (WeekDay.SA.equals(weekDay)) { calDay = Calendar.SATURDAY; } List days = new ArrayList(); if (WEEKLY.equals(getFrequency()) || !getWeekNoList().isEmpty()) { //int weekNo = cal.get(Calendar.WEEK_OF_YEAR); // construct a list of possible week days.. // cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_WEEK, 1); } int weekNo = cal.get(Calendar.WEEK_OF_YEAR); while (cal.get(Calendar.WEEK_OF_YEAR) == weekNo) { days.add(cal.getTime()); cal.add(Calendar.DAY_OF_WEEK, 7); } } else if (MONTHLY.equals(getFrequency()) || !getMonthList().isEmpty()) { int month = cal.get(Calendar.MONTH); // construct a list of possible month days.. cal.set(Calendar.DAY_OF_MONTH, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_MONTH, 1); } while (cal.get(Calendar.MONTH) == month) { days.add(cal.getTime()); cal.add(Calendar.DAY_OF_MONTH, 7); } } else if (YEARLY.equals(getFrequency())) { int year = cal.get(Calendar.YEAR); // construct a list of possible year days.. cal.set(Calendar.DAY_OF_YEAR, 1); while (cal.get(Calendar.DAY_OF_WEEK) != calDay) { cal.add(Calendar.DAY_OF_YEAR, 1); } while (cal.get(Calendar.YEAR) == year) { days.add(cal.getTime()); cal.add(Calendar.DAY_OF_YEAR, 7); } } List weekDays = new ArrayList(); if (weekDay.getOffset() < 0) { weekDays.add(days.get(days.size() + weekDay.getOffset())); } else if (weekDay.getOffset() > 0) { weekDays.add(days.get(weekDay.getOffset() + 1)); } else { weekDays.addAll(days); } return weekDays; } /** * Applies BYHOUR rules specified in this Recur instance to the * specified date list. If no BYHOUR rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getHourVariants(final DateList dates) { if (getHourList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList hourlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getHourList().iterator(); j.hasNext();) { Integer hour = (Integer) j.next(); cal.set(Calendar.HOUR_OF_DAY, hour.intValue()); hourlyDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getMinuteList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(hourlyDates.get(setPos.intValue())); } else { setPosDates.add(hourlyDates.get(hourlyDates.size() + setPos.intValue())); } } return setPosDates; } return hourlyDates; } /** * Applies BYMINUTE rules specified in this Recur instance to the * specified date list. If no BYMINUTE rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getMinuteVariants(final DateList dates) { if (getMinuteList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList minutelyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getMinuteList().iterator(); j.hasNext();) { Integer minute = (Integer) j.next(); cal.set(Calendar.MINUTE, minute.intValue()); minutelyDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty() && getSecondList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(minutelyDates.get(setPos.intValue())); } else { setPosDates.add(minutelyDates.get(minutelyDates.size() + setPos.intValue())); } } return setPosDates; } return minutelyDates; } /** * Applies BYSECOND rules specified in this Recur instance to the * specified date list. If no BYSECOND rules are specified the * date list is returned unmodified. * @param dates * @return */ private DateList getSecondVariants(final DateList dates) { if (getSecondList().isEmpty()) { return dates; } Calendar cal = Calendar.getInstance(); DateList secondlyDates = new DateList(dates.getType()); for (Iterator i = dates.iterator(); i.hasNext();) { Date date = (Date) i.next(); cal.setTime(date); for (Iterator j = getSecondList().iterator(); j.hasNext();) { Integer second = (Integer) j.next(); cal.set(Calendar.SECOND, second.intValue()); secondlyDates.add(cal.getTime()); } } // apply BYSETPOS rules.. if (!getSetPosList().isEmpty()) { DateList setPosDates = new DateList(dates.getType()); for (Iterator i = getSetPosList().iterator(); i.hasNext();) { Integer setPos = (Integer) i.next(); if (setPos.intValue() > 0) { setPosDates.add(secondlyDates.get(setPos.intValue())); } else { setPosDates.add(secondlyDates.get(secondlyDates.size() + setPos.intValue())); } } return setPosDates; } return secondlyDates; } /** * @param count The count to set. */ public final void setCount(final int count) { this.count = count; this.until = null; } /** * @param frequency The frequency to set. */ public final void setFrequency(final String frequency) { this.frequency = frequency; } /** * @param interval The interval to set. */ public final void setInterval(final int interval) { this.interval = interval; } /** * @param until The until to set. */ public final void setUntil(final Date until) { this.until = until; this.count = -1; } }
package org.jasig.portal; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.text.*; import java.sql.*; import java.net.*; import com.objectspace.xml.*; import org.jasig.portal.layout.*; import org.jasig.portal.GenericPortalBean; /** * Provides methods associated with publishing a channel. * This includes naming and defining characteristics. * Channel may then be subject for approval and added to a registry. * @author John Laker * @version $Revision$ */ public class PublisherBean extends GenericPortalBean{ org.jasig.portal.layout.IChannel chan; IXml chanXml; String sPubEmail; String sChanName; public PublisherBean() { } /** * Method creates an instance of the channel class * and then writes the fields needed to set the channel parameters * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ public void writeParamFields(HttpServletRequest req, HttpServletResponse res, JspWriter out) { try { Object channelObject = Class.forName("org.jasig.portal.channels."+req.getParameter("chan_type")).newInstance(); org.jasig.portal.IChannel ch = (org.jasig.portal.IChannel) channelObject; Vector v = ch.getParameters(); Enumeration enum = v.elements(); while(enum.hasMoreElements()) { String [] param = new String[5]; param = (String[])enum.nextElement(); out.println(param[4]+ "<br>"); out.println("<table width=\"40%\" border=\"0\">"); out.println("<tr>"); out.println("<td width=\"19%\">"+param[0]+":</td>"); out.println("<td width=\"81%\">"); out.println("<input type=\"text\" name=\""+param[1]+"\" size=\""+param[2]+"\" maxlength=\""+param[3]+"\" >"); out.println("</td>"); out.println("</tr>"); out.println("</table>"); out.println("<br>"); } } catch (Exception e) { Logger.log (Logger.ERROR, e); } } /** * Creates a new channel object * @param the servlet request object */ public void createChannel (HttpServletRequest req) { try { // Get a new channel and set its parameters chanXml = Xml.newDocument("org.jasig.portal.layout", new File("layout.dtd"),"channel"); chan = (org.jasig.portal.layout.IChannel) chanXml.getRoot (); chan.setClassAttribute("org.jasig.portal.channels."+req.getParameter("chan_type")); Enumeration enum = req.getParameterNames(); while (enum.hasMoreElements()) { String name = (String)enum.nextElement(); IParameter param = Factory.newParameter(); param.setNameAttribute(name); param.setValueAttribute(req.getParameter(name)); chan.addParameter(param); } } catch (Exception e) { Logger.log (Logger.ERROR, e); } } /** * displays a preview of the channel * for the user to see before subscribing * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ public void previewChannel(HttpServletRequest req, HttpServletResponse res, JspWriter out) { try{ sPubEmail = req.getParameter("pub_email"); LayoutBean layoutbean = new LayoutBean(); createChannel(req); org.jasig.portal.IChannel ch = layoutbean.getChannelInstance(chan); sChanName = ch.getName(); out.println ("<table border=0 cellpadding=1 cellspacing=4 width=100%>"); out.println (" <tr>"); out.println (" <td bgcolor=cccccc>"); // Channel heading out.println (" <table border=0 cellpadding=0 cellspacing=0 width=100% bgcolor=#83a3b8>"); out.println (" <tr>"); out.println (" <td>"); out.println (" <font face=arial color=#000000><b>&nbsp;" + sChanName + "</b></font>"); out.println (" </td>"); out.println (" <td nowrap valign=center align=right>"); out.println (" &nbsp;"); // Channel control buttons if (ch.isMinimizable ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/minimize.gif\" alt=\"Minimize\">"); if (ch.isDetachable ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/detach.gif\" alt=\"Detach\">"); if (ch.isRemovable ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/remove.gif\" alt=\"Remove\">"); if (ch.isEditable ()) out.println ("<img border=0 width=\"28\" height=\"15\" src=\"images/edit.gif\" alt=\"Edit\">"); if (ch.hasHelp ()) out.println ("<img border=0 width=\"18\" height=\"15\" src=\"images/help.gif\" alt=\"Help\">"); out.println (" &nbsp;"); out.println (" </td>"); out.println (" </tr>"); out.println (" </table>"); // Channel body out.println (" <table border=0 cellpadding=0 cellspacing=0 width=100%>"); out.println (" <tr>"); out.println (" <td bgcolor=#ffffff>"); out.println (" <table border=0 cellpadding=3 cellspacing=0 width=100% bgcolor=#ffffff>"); out.println (" <tr>"); out.println (" <td valign=top>"); // Render channel contents ch.render (req, res, out); out.println (" </td>"); out.println (" </tr>"); out.println (" </table>"); out.println (" </td>"); out.println (" </tr>"); out.println (" </table>"); out.println (" </td>"); out.println (" </tr>"); out.println ("</table>"); } catch (Exception e){ Logger.log (Logger.ERROR, e); } } /** * Saves channel to database * @param the servlet request object */ public boolean registerChannel (HttpServletRequest req) { RdbmServices rdbmService = new RdbmServices (); Connection con = null; ResultSet rs = null; boolean status = false; try { con = rdbmService.getConnection (); Statement stmt = con.createStatement(); String sQuery = "SELECT max(chan_id)+1 FROM PORTAL_CHANNELS"; rs = stmt.executeQuery(sQuery); rs.next(); int nextID = rs.getInt(1); debug("nextID: "+nextID); StringWriter sw = new StringWriter (); chanXml.saveDocument(sw); String sChanXml = sw.toString(); int trim = sChanXml.indexOf("<channel"); sChanXml = sChanXml.substring(trim); String sInsert = "INSERT INTO PORTAL_CHANNELS (CHAN_ID, TITLE, PUB_EMAIL, CHANNEL_XML) VALUES ("+nextID+",'" + sChanName + "','"+ sPubEmail +"','" + sChanXml + "')"; int iInserted = stmt.executeUpdate (sInsert); if (iInserted == 1) status = true; Logger.log (Logger.DEBUG, "Saving channel xml for " + sChanName + ". Inserted " + iInserted + " rows."); stmt.close (); status = setChannelCats(req, nextID); return status; } catch (Exception e) { Logger.log (Logger.ERROR, e); return status; } finally { rdbmService.releaseConnection (con); } } /** * Relates channel to classifications * @param the servlet request object */ public boolean setChannelCats (HttpServletRequest req, int id) { RdbmServices rdbmService = new RdbmServices (); Connection con = null; boolean status = false; try { con = rdbmService.getConnection (); Statement stmt = con.createStatement(); String[] cats = req.getParameterValues("class"); for(int i=0; i<cats.length; i++){ String sInsert = "INSERT INTO PORTAL_CHAN_CLASS (CLASS_ID, CHAN_ID) VALUES ("+cats[i]+","+ id + ")"; Logger.log (Logger.DEBUG, sInsert); int iInserted = stmt.executeUpdate (sInsert); if (iInserted == 1) status = true; } stmt.close (); return status; } catch (Exception e) { Logger.log (Logger.ERROR, e); return false; } finally { rdbmService.releaseConnection (con); } } /** * Writes a list of publishable channel types * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ public void writeChannelTypes (HttpServletRequest req, HttpServletResponse res, JspWriter out) { RdbmServices rdbmService = new RdbmServices (); Connection con = null; ResultSet rs = null; Statement stmt = null; try { con = rdbmService.getConnection (); stmt = con.createStatement(); String sQuery = "SELECT TYPE, NAME, DESC FROM PORTAL_CHAN_TYPES"; Logger.log (Logger.DEBUG, sQuery); rs = stmt.executeQuery (sQuery); while(rs.next()) { out.println("<tr valign=\"top\">"); out.println("<td width=\"26%\" height=\"37\">"); out.println("<input type=\"radio\" name=\"chan_type\" value=\""+rs.getString("TYPE")+"\">"+rs.getString("NAME")+"</td>"); out.println("<td width=\"3%\" height=\"37\">&nbsp;</td>"); out.println("<td width=\"71%\" height=\"37\"><font size=\"2\">"+rs.getString("DESC")+"</font></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td width=\"26%\" height=\"2\">&nbsp;</td>"); out.println("<td width=\"3%\" height=\"2\">&nbsp;</td>"); out.println("<td width=\"71%\" height=\"2\">&nbsp;</td>"); out.println("</tr>"); } stmt.close(); } catch (Exception e) { Logger.log (Logger.ERROR, e); } finally { rdbmService.releaseConnection (con); } } /** * Writes a list of channel classifications for publishing. * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ public void writeChannelCats (HttpServletRequest req, HttpServletResponse res, JspWriter out) { RdbmServices rdbmService = new RdbmServices (); Connection con = null; ResultSet rs = null; Statement stmt = null; try { con = rdbmService.getConnection (); stmt = con.createStatement(); String sQuery = "SELECT CLASS_ID, NAME FROM PORTAL_CLASS"; Logger.log (Logger.DEBUG, sQuery); rs = stmt.executeQuery (sQuery); while(rs.next()) { out.println("<input name=class type=checkbox value="+rs.getString("CLASS_ID")+">"+rs.getString("NAME")+"<br>"); } stmt.close(); } catch (Exception e) { Logger.log (Logger.ERROR, e); } finally { rdbmService.releaseConnection (con); } } /** * Allows admin to approve channel for subscription * @param the servlet request object */ public void approveChannel (HttpServletRequest req) { RdbmServices rdbmService = new RdbmServices (); Connection con = null; String sChanId = req.getParameter("chan_id"); try { con = rdbmService.getConnection (); Statement stmt = con.createStatement(); String sUpdate = "UPDATE PORTAL_CHANNELS SET APPROVED = 1 WHERE CHAN_ID = "+ sChanId; int iUpdated = stmt.executeUpdate (sUpdate); Logger.log (Logger.DEBUG, "Updating channel xml for " + sChanId + ". Updated " + iUpdated + " rows."); stmt.close (); } catch (Exception e) { Logger.log (Logger.ERROR, e); } finally { rdbmService.releaseConnection (con); } } }
package org.jasig.portal.tools; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.jasig.portal.PortalException; import org.jasig.portal.utils.XSLT; /** * Title: Run XSLT * Description: applies an xsl stylesheet to an xml file * Company: * @author Susan Bramhall * $Revision$ */ public class RunXSLT { public static void main(String[] args) { File xmlSourceFile = null; FileOutputStream ostream = null; File XslOutputFile = null; String xslUri = null; if (args.length < 3) { System.err.println("Usage \"runXSLT <xmlSource> <xslUri> <outFile>\""); return; } for (int i = 0; i < args.length; i++) { if (!args[i].startsWith("-")) { xmlSourceFile = new File(args[i].trim()); System.out.println("xmlSourceFile is "+xmlSourceFile.getAbsolutePath()); xslUri = args[++i].trim(); System.out.println("xslUri is "+xslUri); XslOutputFile = new File(args[++i].trim()); System.out.println("XslOutputFile is "+XslOutputFile.getAbsolutePath()); } } XSLT xslt = XSLT.getTransformer(RunXSLT.class); try { ostream = new FileOutputStream(XslOutputFile); } catch (IOException ioe) { System.err.println("Unable to create output file "+ XslOutputFile.getName()); return; } try { xslt.setXML(xmlSourceFile); xslt.setXSL(xslUri); xslt.setTarget(ostream); xslt.transform(); } catch (PortalException pe) { System.err.println("RunXSLT: Error on transform"); pe.printStackTrace(); } } }
package im.actor.core.js.modules; import com.google.gwt.core.client.JsArray; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import im.actor.core.entity.Avatar; import im.actor.core.entity.Contact; import im.actor.core.entity.Dialog; import im.actor.core.entity.Message; import im.actor.core.entity.Peer; import im.actor.core.entity.PeerType; import im.actor.core.entity.SearchEntity; import im.actor.core.entity.content.DocumentContent; import im.actor.core.entity.content.FileRemoteSource; import im.actor.core.js.JsMessenger; import im.actor.core.js.entity.JsContact; import im.actor.core.js.entity.JsCounter; import im.actor.core.js.entity.JsDialog; import im.actor.core.js.entity.JsDialogGroup; import im.actor.core.js.entity.JsDialogShort; import im.actor.core.js.entity.JsGroup; import im.actor.core.js.entity.JsMessage; import im.actor.core.js.entity.JsOnlineGroup; import im.actor.core.js.entity.JsOnlineUser; import im.actor.core.js.entity.JsPeerInfo; import im.actor.core.js.entity.JsSearchEntity; import im.actor.core.js.entity.JsTyping; import im.actor.core.js.entity.JsUser; import im.actor.core.modules.AbsModule; import im.actor.core.modules.Modules; import im.actor.core.viewmodel.AppStateVM; import im.actor.core.viewmodel.DialogGroup; import im.actor.core.viewmodel.DialogSmall; import im.actor.core.viewmodel.GroupTypingVM; import im.actor.core.viewmodel.GroupVM; import im.actor.core.viewmodel.UserPresence; import im.actor.core.viewmodel.UserTypingVM; import im.actor.core.viewmodel.UserVM; import im.actor.runtime.js.mvvm.JsDisplayList; import im.actor.runtime.mvvm.ModelChangedListener; import im.actor.runtime.mvvm.Value; import im.actor.runtime.mvvm.ValueChangedListener; import im.actor.runtime.mvvm.ValueModel; public class JsBindingModule extends AbsModule implements JsFileLoadedListener { private JsMessenger messenger; private JsFilesModule filesModule; private HashMap<Integer, JsBindedValue<JsUser>> users = new HashMap<Integer, JsBindedValue<JsUser>>(); private HashMap<Integer, JsBindedValue<JsGroup>> groups = new HashMap<Integer, JsBindedValue<JsGroup>>(); private HashMap<Integer, JsBindedValue<JsOnlineUser>> usersOnlines = new HashMap<Integer, JsBindedValue<JsOnlineUser>>(); private HashMap<Integer, JsBindedValue<JsOnlineGroup>> groupOnlines = new HashMap<Integer, JsBindedValue<JsOnlineGroup>>(); private HashMap<Peer, JsBindedValue<JsTyping>> typing = new HashMap<Peer, JsBindedValue<JsTyping>>(); private JsBindedValue<String> onlineState; private JsDisplayList<JsDialog, Dialog> dialogsList; private JsDisplayList<JsContact, Contact> contactsList; private JsDisplayList<JsSearchEntity, SearchEntity> searchList; private HashMap<Peer, JsDisplayList<JsMessage, Message>> messageLists = new HashMap<Peer, JsDisplayList<JsMessage, Message>>(); private JsBindedValue<JsCounter> globalCounter; private JsBindedValue<JsCounter> tempGlobalCounter; private JsBindedValue<JsArray<JsDialogGroup>> dialogsGroupedList; public JsBindingModule(JsMessenger messenger, JsFilesModule filesModule, Modules modules) { super(modules); this.filesModule = filesModule; this.messenger = messenger; this.filesModule.registerListener(this); } public JsBindedValue<JsArray<JsDialogGroup>> getDialogsGroupedList() { if (dialogsGroupedList == null) { ValueModel<ArrayList<DialogGroup>> dialogGroups = context().getMessagesModule().getDialogGroupsVM().getGroupsValueModel(); dialogsGroupedList = new JsBindedValue<JsArray<JsDialogGroup>>(); dialogGroups.subscribe(new ValueChangedListener<ArrayList<DialogGroup>>() { @Override public void onChanged(ArrayList<DialogGroup> val, Value<ArrayList<DialogGroup>> valueModel) { if (val == null) { dialogsGroupedList.changeValue(JsArray.createArray().<JsArray<JsDialogGroup>>cast()); } else { JsArray<JsDialogGroup> res = JsArray.createArray().cast(); for (DialogGroup g : val) { JsArray<JsDialogShort> resd = JsArray.createArray().cast(); for (DialogSmall ds : g.getDialogs()) { resd.push(JsDialogShort.create(messenger.buildPeerInfo(ds.getPeer()), ds.getCounter())); } res.push(JsDialogGroup.create(g.getTitle(), g.getKey(), resd)); } dialogsGroupedList.changeValue(res); } } }); } return dialogsGroupedList; } public JsBindedValue<String> getOnlineStatus() { if (onlineState == null) { final AppStateVM vm = context().getAppStateModule().getAppStateVM(); onlineState = new JsBindedValue<String>("online"); vm.getIsConnecting().subscribe(new ValueChangedListener<Boolean>() { @Override public void onChanged(Boolean val, Value<Boolean> valueModel) { if (val) { onlineState.changeValue("connecting"); } else { if (vm.getIsSyncing().get()) { onlineState.changeValue("updating"); } else { onlineState.changeValue("online"); } } } }); vm.getIsSyncing().subscribe(new ValueChangedListener<Boolean>() { @Override public void onChanged(Boolean val, Value<Boolean> valueModel) { if (vm.getIsConnecting().get()) { onlineState.changeValue("connecting"); } else { if (val) { onlineState.changeValue("updating"); } else { onlineState.changeValue("online"); } } } }); } return onlineState; } public JsBindedValue<JsUser> getUser(int uid) { if (!users.containsKey(uid)) { final UserVM userVM = context().getUsersModule().getUsers().get(uid); final JsBindedValue<JsUser> value = new JsBindedValue<JsUser>(JsUser.fromUserVM(userVM, messenger)); // Bind updates userVM.subscribe(new ModelChangedListener<UserVM>() { @Override public void onChanged(UserVM model) { value.changeValue(JsUser.fromUserVM(userVM, messenger)); } }, false); // Sign for presence separately // userVM.getPresence().subscribe(new ValueChangedListener<UserPresence>() { // @Override // public void onChanged(UserPresence val, Value<UserPresence> valueModel) { // value.changeValue(JsUser.fromUserVM(userVM, messenger)); // }, false); // Sign for contact separately userVM.isContact().subscribe(new ValueChangedListener<Boolean>() { @Override public void onChanged(Boolean val, Value<Boolean> valueModel) { value.changeValue(JsUser.fromUserVM(userVM, messenger)); } }); users.put(uid, value); } return users.get(uid); } public JsBindedValue<JsOnlineUser> getUserOnline(int uid) { if (!usersOnlines.containsKey(uid)) { final JsBindedValue<JsOnlineUser> value = new JsBindedValue<JsOnlineUser>(); final UserVM userVM = context().getUsersModule().getUsers().get(uid); userVM.getPresence().subscribe(new ValueChangedListener<UserPresence>() { @Override public void onChanged(UserPresence val, Value<UserPresence> valueModel) { if (val.getState() == UserPresence.State.UNKNOWN) { value.changeValue(null); } else { String presenceString = messenger.getFormatter().formatPresence(val, userVM.getSex()); if (userVM.isBot()) { presenceString = "bot"; } value.changeValue(JsOnlineUser.create(presenceString, val.getState() == UserPresence.State.ONLINE)); } } }); usersOnlines.put(uid, value); } return usersOnlines.get(uid); } public JsBindedValue<JsGroup> getGroup(int gid) { if (!groups.containsKey(gid)) { final GroupVM groupVM = context().getGroupsModule().getGroupsCollection().get(gid); final JsBindedValue<JsGroup> value = new JsBindedValue<JsGroup>(JsGroup.fromGroupVM(groupVM, messenger)); // Bind updates groupVM.subscribe(new ModelChangedListener<GroupVM>() { @Override public void onChanged(GroupVM model) { value.changeValue(JsGroup.fromGroupVM(groupVM, messenger)); } }, false); // Sign for presence separately // groupVM.getPresence().subscribe(new ValueChangedListener<Integer>() { // @Override // public void onChanged(Integer val, Value<Integer> valueModel) { // value.changeValue(JsGroup.fromGroupVM(groupVM, messenger)); // }, false); groups.put(gid, value); } return groups.get(gid); } public JsBindedValue<JsOnlineGroup> getGroupOnline(int gid) { if (!groupOnlines.containsKey(gid)) { final JsBindedValue<JsOnlineGroup> value = new JsBindedValue<JsOnlineGroup>(); final GroupVM groupVM = context().getGroupsModule().getGroupsCollection().get(gid); groupVM.getPresence().subscribe(new ValueChangedListener<Integer>() { @Override public void onChanged(Integer val, Value<Integer> valueModel) { if (groupVM.isMember().get()) { if (val == null) { value.changeValue(null); return; } String presence = messenger.getFormatter().formatGroupMembers(groupVM.getMembersCount()); if (val > 0) { presence += ", " + messenger.getFormatter().formatGroupOnline(val); } value.changeValue(JsOnlineGroup.create(groupVM.getMembersCount(), val, presence, false)); } else { value.changeValue(JsOnlineGroup.create(0, 0, "Not member", false)); } } }); groupOnlines.put(gid, value); } return groupOnlines.get(gid); } public JsBindedValue<JsTyping> getTyping(final Peer peer) { if (!typing.containsKey(peer)) { if (peer.getPeerType() == PeerType.PRIVATE) { UserTypingVM userTypingVM = context().getTypingModule().getTyping(peer.getPeerId()); final JsBindedValue<JsTyping> value = new JsBindedValue<JsTyping>(); userTypingVM.getTyping().subscribe(new ValueChangedListener<Boolean>() { @Override public void onChanged(Boolean val, Value<Boolean> valueModel) { String typingValue = null; if (val) { typingValue = messenger.getFormatter().formatTyping(""); } value.changeValue(JsTyping.create(typingValue)); } }); typing.put(peer, value); } else if (peer.getPeerType() == PeerType.GROUP) { GroupTypingVM groupTypingVM = context().getTypingModule().getGroupTyping(peer.getPeerId()); final JsBindedValue<JsTyping> value = new JsBindedValue<JsTyping>(); groupTypingVM.getActive().subscribe(new ValueChangedListener<int[]>() { @Override public void onChanged(int[] val, Value<int[]> valueModel) { String typingValue = null; if (val.length == 1) { typingValue = messenger.getFormatter().formatTyping(context() .getUsersModule() .getUsers() .get(val[0]) .getName() .get()); } else if (val.length > 1) { typingValue = messenger.getFormatter().formatTyping(val.length); } value.changeValue(JsTyping.create(typingValue)); } }); typing.put(peer, value); } else { throw new RuntimeException(); } } return typing.get(peer); } public JsDisplayList<JsSearchEntity, SearchEntity> getSharedSearchList() { if (searchList == null) { searchList = (JsDisplayList<JsSearchEntity, SearchEntity>) context().getDisplayListsModule().buildSearchList(true); } return searchList; } public JsDisplayList<JsContact, Contact> getSharedContactList() { if (contactsList == null) { contactsList = (JsDisplayList<JsContact, Contact>) context().getDisplayListsModule().getContactsSharedList(); } return contactsList; } public JsDisplayList<JsDialog, Dialog> getSharedDialogList() { if (dialogsList == null) { dialogsList = (JsDisplayList<JsDialog, Dialog>) context().getDisplayListsModule().getDialogsSharedList(); } return dialogsList; } public JsDisplayList<JsMessage, Message> getSharedMessageList(Peer peer) { if (!messageLists.containsKey(peer)) { messageLists.put(peer, (JsDisplayList<JsMessage, Message>) context().getDisplayListsModule().getMessagesSharedList(peer)); } return messageLists.get(peer); } public JsBindedValue<JsCounter> getGlobalCounter() { if (globalCounter == null) { ValueModel<Integer> counter = context().getAppStateModule().getAppStateVM().getGlobalCounter(); globalCounter = new JsBindedValue<JsCounter>(JsCounter.create(counter.get())); counter.subscribe(new ValueChangedListener<Integer>() { @Override public void onChanged(Integer val, Value<Integer> valueModel) { globalCounter.changeValue(JsCounter.create(val)); } }, false); } return globalCounter; } public JsBindedValue<JsCounter> getTempGlobalCounter() { if (tempGlobalCounter == null) { ValueModel<Integer> counter = context().getAppStateModule().getAppStateVM().getGlobalTempCounter(); tempGlobalCounter = new JsBindedValue<JsCounter>(JsCounter.create(counter.get())); counter.subscribe(new ValueChangedListener<Integer>() { @Override public void onChanged(Integer val, Value<Integer> valueModel) { tempGlobalCounter.changeValue(JsCounter.create(val)); } }, false); } return tempGlobalCounter; } @Override public void onFileLoaded(HashSet<Long> fileId) { // Dialogs List if (dialogsList != null) { dialogsList.startReconverting(); for (Dialog dialog : dialogsList.getRawItems()) { if (checkAvatar(dialog.getDialogAvatar(), fileId)) { dialogsList.forceReconvert(dialog.getEngineId()); } } dialogsList.stopReconverting(); } // Grouped Dialogs if (dialogsGroupedList != null) { ArrayList<DialogGroup> groups = context().getMessagesModule().getDialogGroupsVM().getGroupsValueModel().get(); if (groups != null) { outer: for (DialogGroup g : groups) { for (DialogSmall ds : g.getDialogs()) { if (checkAvatar(ds.getAvatar(), fileId)) { context().getMessagesModule().getDialogGroupsVM().getGroupsValueModel().forceNotify(); break outer; } } } } } // Contacts List if (contactsList != null) { contactsList.startReconverting(); for (Contact contact : contactsList.getRawItems()) { if (checkAvatar(contact.getAvatar(), fileId)) { contactsList.forceReconvert(contact.getEngineId()); } } contactsList.stopReconverting(); } // Message Contents for (JsDisplayList<JsMessage, Message> messageList : messageLists.values()) { messageList.startReconverting(); for (Message message : messageList.getRawItems()) { UserVM user = context().getUsersModule().getUsers().get(message.getSenderId()); if (checkAvatar(user.getAvatar().get(), fileId)) { messageList.forceReconvert(message.getEngineId()); continue; } if (message.getContent() instanceof DocumentContent) { DocumentContent doc = (DocumentContent) message.getContent(); if (doc.getSource() instanceof FileRemoteSource) { if (fileId.contains(((FileRemoteSource) doc.getSource()).getFileReference().getFileId())) { messageList.forceReconvert(message.getEngineId()); } } } } messageList.stopReconverting(); } // Users for (JsBindedValue<JsUser> u : users.values()) { int uid = u.get().getUid(); UserVM userVM = context().getUsersModule().getUsers().get(uid); if (checkAvatar(userVM.getAvatar().get(), fileId)) { u.changeValue(JsUser.fromUserVM(userVM, messenger)); } } // Groups for (JsBindedValue<JsGroup> g : groups.values()) { int gid = g.get().getGid(); GroupVM groupVM = context().getGroupsModule().getGroupsCollection().get(gid); if (checkAvatar(groupVM.getAvatar().get(), fileId)) { g.changeValue(JsGroup.fromGroupVM(groupVM, messenger)); } } } protected boolean checkAvatar(Avatar avatar, HashSet<Long> fileIds) { if (avatar == null) { return false; } if (avatar.getSmallImage() != null && fileIds.contains(avatar.getSmallImage().getFileReference().getFileId())) { return true; } if (avatar.getFullImage() != null && fileIds.contains(avatar.getFullImage().getFileReference().getFileId())) { return true; } if (avatar.getLargeImage() != null && fileIds.contains(avatar.getLargeImage().getFileReference().getFileId())) { return true; } return false; } }
package nu.studer.teamcity.buildscan.agent; import jetbrains.buildServer.agent.AgentLifeCycleAdapter; import jetbrains.buildServer.agent.AgentLifeCycleListener; import jetbrains.buildServer.agent.BuildRunnerContext; import jetbrains.buildServer.util.EventDispatcher; import jetbrains.buildServer.util.FileUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This class is responsible for injecting a Gradle init script into all Gradle build runners. This init script itself registers a callback on the build scan plugin for any * published build scans and emits a TeamCity {@link jetbrains.buildServer.messages.serviceMessages.ServiceMessage} containing the scan URL. * <p> * In the presence of certain configuration parameters, this class will also inject Gradle Enterprise and Common Custom User Data plugins and extensions into Gradle and Maven * builds. */ public final class BuildScanServiceMessageInjector extends AgentLifeCycleAdapter { // TeamCity Gradle runner private static final String GRADLE_RUNNER = "gradle-runner"; private static final String GRADLE_CMD_PARAMS = "ui.gradleRunner.additional.gradle.cmd.params"; private static final String BUILD_SCAN_INIT_GRADLE = "build-scan-init.gradle"; // TeamCity Maven runner private static final String MAVEN_RUNNER = "Maven2"; private static final String MAVEN_CMD_PARAMS = "runnerArgs"; private static final String BUILD_SCAN_EXT_MAVEN = "service-message-maven-extension-1.0.jar"; private static final String GRADLE_ENTERPRISE_EXT_MAVEN = "gradle-enterprise-maven-extension-1.14.1.jar"; private static final String COMMON_CUSTOM_USER_DATA_EXT_MAVEN = "common-custom-user-data-maven-extension-1.10.1.jar"; // Gradle TeamCity Build Scan plugin private static final String GRADLE_BUILDSCAN_TEAMCITY_PLUGIN = "GRADLE_BUILDSCAN_TEAMCITY_PLUGIN"; // TeamCity GE configuration parameters private static final String GE_URL_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.url"; private static final String GE_PLUGIN_VERSION_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.plugin.version"; private static final String CCUD_PLUGIN_VERSION_CONFIG_PARAM = "buildScanPlugin.ccud.plugin.version"; private static final String GE_EXTENSION_VERSION_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.extension.version"; private static final String CCUD_EXTENSION_VERSION_CONFIG_PARAM = "buildScanPlugin.ccud.extension.version"; // Gradle properties and Maven system properties passed to the artifact instrumenting the Gradle / Maven build private static final String GE_URL_GRADLE_PROPERTY = "teamCityBuildScanPlugin.gradle-enterprise.url"; private static final String GE_PLUGIN_VERSION_GRADLE_PROPERTY = "teamCityBuildScanPlugin.gradle-enterprise.plugin.version"; private static final String CCUD_PLUGIN_VERSION_GRADLE_PROPERTY = "teamCityBuildScanPlugin.ccud.plugin.version"; private static final String GE_URL_MAVEN_PROPERTY = "gradle.enterprise.url"; private static final MavenCoordinates GE_EXTENSION_MAVEN_COORDINATES = new MavenCoordinates("com.gradle", "gradle-enterprise-maven-extension"); private static final MavenCoordinates CCUD_EXTENSION_MAVEN_COORDINATES = new MavenCoordinates("com.gradle", "common-custom-user-data-maven-extension"); public BuildScanServiceMessageInjector(@NotNull EventDispatcher<AgentLifeCycleListener> eventDispatcher) { eventDispatcher.addListener(this); } @Override public void beforeRunnerStart(@NotNull BuildRunnerContext runner) { if (runner.getRunType().equalsIgnoreCase(GRADLE_RUNNER)) { addGradleSysPropIfSet(GE_URL_CONFIG_PARAM, GE_URL_GRADLE_PROPERTY, runner); addGradleSysPropIfSet(GE_PLUGIN_VERSION_CONFIG_PARAM, GE_PLUGIN_VERSION_GRADLE_PROPERTY, runner); addGradleSysPropIfSet(CCUD_PLUGIN_VERSION_CONFIG_PARAM, CCUD_PLUGIN_VERSION_GRADLE_PROPERTY, runner); String initScriptParam = "--init-script " + getInitScript(runner).getAbsolutePath(); addGradleCmdParam(initScriptParam, runner); addEnvVar(GRADLE_BUILDSCAN_TEAMCITY_PLUGIN, "1", runner); } else if (runner.getRunType().equalsIgnoreCase(MAVEN_RUNNER)) { // for now, this intentionally ignores the configured extension versions and applies the bundled jars String extJarParam = "-Dmaven.ext.class.path=" + getExtensionsClasspath(runner); addMavenCmdParam(extJarParam, runner); addEnvVar(GRADLE_BUILDSCAN_TEAMCITY_PLUGIN, "1", runner); } } private File getInitScript(BuildRunnerContext runner) { File initScript = new File(runner.getBuild().getAgentTempDirectory(), BUILD_SCAN_INIT_GRADLE); FileUtil.copyResourceIfNotExists(BuildScanServiceMessageInjector.class, "/" + BUILD_SCAN_INIT_GRADLE, initScript); return initScript; } private String getExtensionsClasspath(BuildRunnerContext runner) { List<File> extensionJars = new ArrayList<File>(); // add extension to capture build scan URL extensionJars.add(getExtensionJar(BUILD_SCAN_EXT_MAVEN, runner)); // optionally add extensions that connect the Maven build with Gradle Enterprise MavenExtensions extensions = getMavenExtensions(runner); String geExtensionVersion = getOptionalConfigParam(GE_EXTENSION_VERSION_CONFIG_PARAM, runner); if (geExtensionVersion != null) { if (!extensions.hasExtension(GE_EXTENSION_MAVEN_COORDINATES)) { extensionJars.add(getExtensionJar(GRADLE_ENTERPRISE_EXT_MAVEN, runner)); addMavenSysPropIfSet(GE_URL_CONFIG_PARAM, GE_URL_MAVEN_PROPERTY, runner); } } String ccudExtensionVersion = getOptionalConfigParam(CCUD_EXTENSION_VERSION_CONFIG_PARAM, runner); if (ccudExtensionVersion != null) { if (!extensions.hasExtension(CCUD_EXTENSION_MAVEN_COORDINATES)) { extensionJars.add(getExtensionJar(COMMON_CUSTOM_USER_DATA_EXT_MAVEN, runner)); } } return asClassPath(extensionJars); } private File getExtensionJar(String name, BuildRunnerContext runner) { File extensionJar = new File(runner.getBuild().getAgentTempDirectory(), name); FileUtil.copyResourceIfNotExists(BuildScanServiceMessageInjector.class, "/" + name, extensionJar); return extensionJar; } private MavenExtensions getMavenExtensions(BuildRunnerContext runner) { Map<String, String> parameters = runner.getRunnerParameters(); String workingDirParam = parameters.get("teamcity.build.workingDir"); String pomLocation = parameters.get("pomLocation"); String checkoutDirParam = parameters.get("teamcity.build.checkoutDir"); File workingDir; if (pomLocation != null && checkoutDirParam != null && !checkoutDirParam.isEmpty()) { File checkoutDir = new File(checkoutDirParam); workingDir = new File(checkoutDir, pomLocation).getParentFile(); } else { workingDir = new File(workingDirParam); } File extensionFile = new File(workingDir, ".mvn/extensions.xml"); return MavenExtensions.fromFile(extensionFile); } @SuppressWarnings("SameParameterValue") private static void addEnvVar(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) { runner.addEnvironmentVariable(key, value); } private static void addGradleSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) { String value = getOptionalConfigParam(configParameter, runner); if (value != null) { addGradleSysProp(property, value, runner); } } private static void addGradleSysProp(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) { String systemProp = String.format("-D%s=%s", key, value); addGradleCmdParam(systemProp, runner); } private static void addGradleCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) { String existingParams = getOrDefault(GRADLE_CMD_PARAMS, runner); runner.addRunnerParameter(GRADLE_CMD_PARAMS, param + " " + existingParams); } private static void addMavenSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) { String value = getOptionalConfigParam(configParameter, runner); if (value != null) { addMavenSysProp(property, value, runner); } } private static void addMavenSysProp(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) { String systemProp = String.format("-D%s=%s", key, value); addMavenCmdParam(systemProp, runner); } private static void addMavenCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) { String existingParams = getOrDefault(MAVEN_CMD_PARAMS, runner); runner.addRunnerParameter(MAVEN_CMD_PARAMS, param + " " + existingParams); } @Nullable private static String getOptionalConfigParam(@NotNull String paramName, @NotNull BuildRunnerContext runner) { Map<String, String> configParameters = runner.getConfigParameters(); if (!configParameters.containsKey(paramName)) { return null; } String value = configParameters.get(paramName).trim(); return value.isEmpty() ? null : value; } private static String getOrDefault(@NotNull String paramName, @NotNull BuildRunnerContext runner) { Map<String, String> runnerParameters = runner.getRunnerParameters(); return runnerParameters.containsKey(paramName) ? runnerParameters.get(paramName) : ""; } @NotNull private static String asClassPath(List<File> files) { StringBuilder sb = new StringBuilder(); for (File file : files) { if (sb.length() > 0) { sb.append(File.pathSeparator); } sb.append(file.getAbsolutePath()); } return sb.toString(); } }
package com.continuuity.internal.app.services; import com.continuuity.api.ApplicationSpecification; import com.continuuity.api.ProgramSpecification; import com.continuuity.api.annotation.ProcessInput; import com.continuuity.api.batch.MapReduceSpecification; import com.continuuity.api.data.OperationException; import com.continuuity.api.flow.FlowSpecification; import com.continuuity.api.flow.FlowletDefinition; import com.continuuity.api.flow.flowlet.AbstractFlowlet; import com.continuuity.api.flow.flowlet.OutputEmitter; import com.continuuity.api.flow.flowlet.StreamEvent; import com.continuuity.api.procedure.ProcedureSpecification; import com.continuuity.api.workflow.WorkflowSpecification; import com.continuuity.app.Id; import com.continuuity.app.authorization.AuthorizationFactory; import com.continuuity.app.deploy.Manager; import com.continuuity.app.deploy.ManagerFactory; import com.continuuity.app.program.Program; import com.continuuity.app.program.Programs; import com.continuuity.app.program.RunRecord; import com.continuuity.app.program.Type; import com.continuuity.app.queue.QueueSpecification; import com.continuuity.app.queue.QueueSpecificationGenerator; import com.continuuity.app.runtime.ProgramController; import com.continuuity.app.runtime.ProgramRuntimeService; import com.continuuity.app.services.ActiveProgram; import com.continuuity.app.services.AppFabricService; import com.continuuity.app.services.AppFabricServiceException; import com.continuuity.app.services.ArchiveId; import com.continuuity.app.services.ArchiveInfo; import com.continuuity.app.services.AuthToken; import com.continuuity.app.services.DeployStatus; import com.continuuity.app.services.DeploymentStatus; import com.continuuity.app.services.EntityType; import com.continuuity.app.services.ProgramDescriptor; import com.continuuity.app.services.ProgramId; import com.continuuity.app.services.ProgramRunRecord; import com.continuuity.app.services.ProgramStatus; import com.continuuity.app.services.RunIdentifier; import com.continuuity.app.services.ScheduleId; import com.continuuity.app.services.ScheduleRunTime; import com.continuuity.app.store.Store; import com.continuuity.app.store.StoreFactory; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.discovery.RandomEndpointStrategy; import com.continuuity.common.discovery.TimeLimitEndpointStrategy; import com.continuuity.data.DataSetAccessor; import com.continuuity.data2.transaction.queue.QueueAdmin; import com.continuuity.internal.UserErrors; import com.continuuity.internal.UserMessages; import com.continuuity.internal.app.deploy.SessionInfo; import com.continuuity.internal.app.deploy.pipeline.ApplicationWithPrograms; import com.continuuity.internal.app.queue.SimpleQueueSpecificationGenerator; import com.continuuity.internal.app.runtime.AbstractListener; import com.continuuity.internal.app.runtime.BasicArguments; import com.continuuity.internal.app.runtime.ProgramOptionConstants; import com.continuuity.internal.app.runtime.SimpleProgramOptions; import com.continuuity.internal.app.runtime.schedule.ScheduledRuntime; import com.continuuity.internal.app.runtime.schedule.Scheduler; import com.continuuity.internal.app.services.legacy.ConnectionDefinitionImpl; import com.continuuity.internal.app.services.legacy.FlowDefinitionImpl; import com.continuuity.internal.app.services.legacy.FlowStreamDefinitionImpl; import com.continuuity.internal.app.services.legacy.FlowletDefinitionImpl; import com.continuuity.internal.app.services.legacy.FlowletStreamDefinitionImpl; import com.continuuity.internal.app.services.legacy.FlowletType; import com.continuuity.internal.app.services.legacy.MetaDefinitionImpl; import com.continuuity.internal.app.services.legacy.QueryDefinitionImpl; import com.continuuity.internal.app.services.legacy.StreamNamerImpl; import com.continuuity.internal.filesystem.LocationCodec; import com.continuuity.internal.io.ReflectionSchemaGenerator; import com.continuuity.internal.io.UnsupportedTypeException; import com.continuuity.metadata.MetaDataStore; import com.continuuity.metadata.MetadataServiceException; import com.continuuity.metadata.types.Application; import com.continuuity.weave.api.RunId; import com.continuuity.weave.common.Threads; import com.continuuity.weave.discovery.Discoverable; import com.continuuity.weave.discovery.DiscoveryServiceClient; import com.continuuity.weave.filesystem.Location; import com.continuuity.weave.filesystem.LocationFactory; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Table; import com.google.common.io.Closeables; import com.google.common.io.InputSupplier; import com.google.common.io.OutputSupplier; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.Service; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Inject; import com.ning.http.client.Body; import com.ning.http.client.BodyGenerator; import com.ning.http.client.Response; import com.ning.http.client.SimpleAsyncHttpClient; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * This is a concrete implementation of AppFabric thrift Interface. */ public class DefaultAppFabricService implements AppFabricService.Iface { /** * Log handler. */ private static final Logger LOG = LoggerFactory.getLogger(DefaultAppFabricService.class); /** * Number of seconds for timing out a service endpoint discovery. */ private static final long DISCOVERY_TIMEOUT_SECONDS = 3; /** * Maintains a mapping of transient session state. The state is stored in memory, * in case of failure, all the current running sessions will be terminated. As * per the current implementation only connection per account is allowed to upload. */ private final Map<String, SessionInfo> sessions = Maps.newConcurrentMap(); /** * Metadata Service instance is used to interact with the metadata store. */ private final MetaDataStore mds; /** * Used to manage datasets. TODO: implement and use DataSetService instead */ private final DataSetAccessor dataSetAccessor; /** * Configuration object passed from higher up. */ private final CConfiguration configuration; /** * Factory for handling the location - can do both in either Distributed or Local mode. */ private final LocationFactory locationFactory; /** * DeploymentManager responsible for running pipeline. */ private final ManagerFactory managerFactory; /** * Authorization Factory used to create handler used for authroizing use of endpoints. */ private final AuthorizationFactory authFactory; /** * Runtime program service for running and managing programs. */ private final ProgramRuntimeService runtimeService; /** * Discovery service client to discover other services. */ private final DiscoveryServiceClient discoveryServiceClient; /** * Store manages non-runtime lifecycle. */ private final Store store; /** * The directory where the uploaded files would be placed. */ private final String archiveDir; /** * App fabric output directory. */ private final String appFabricDir; // We need it here now to be able to reset queues data private final QueueAdmin queueAdmin; /** * Timeout to upload to remote app fabric. */ private static final long UPLOAD_TIMEOUT = TimeUnit.MILLISECONDS.convert(10, TimeUnit.MINUTES); /** * Timeout to get response from metrics system. */ private static final long METRICS_SERVER_RESPONSE_TIMEOUT = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES); private final Scheduler scheduler; /** * Constructs an new instance. Parameters are binded by Guice. */ @Inject public DefaultAppFabricService(CConfiguration configuration, DataSetAccessor dataSetAccessor, MetaDataStore mds, LocationFactory locationFactory, ManagerFactory managerFactory, AuthorizationFactory authFactory, StoreFactory storeFactory, ProgramRuntimeService runtimeService, DiscoveryServiceClient discoveryServiceClient, QueueAdmin queueAdmin, Scheduler scheduler) { this.dataSetAccessor = dataSetAccessor; this.locationFactory = locationFactory; this.configuration = configuration; this.managerFactory = managerFactory; this.authFactory = authFactory; this.runtimeService = runtimeService; this.discoveryServiceClient = discoveryServiceClient; this.queueAdmin = queueAdmin; this.store = storeFactory.create(); this.appFabricDir = configuration.get(Constants.AppFabric.OUTPUT_DIR, System.getProperty("java.io.tmpdir")); this.archiveDir = this.appFabricDir + "/archive"; this.mds = mds; this.scheduler = scheduler; // Note: This is hacky to start service like this. if (this.runtimeService.state() != Service.State.RUNNING) { this.runtimeService.startAndWait(); } } private Type entityTypeToType(ProgramId identifier) { return Type.valueOf(identifier.getType().name()); } private EntityType typeToEntityType(Type type) { return EntityType.valueOf(type.name()); } /** * Starts a Program. * * @param token * @param descriptor */ @Override public synchronized RunIdentifier start(AuthToken token, ProgramDescriptor descriptor) throws AppFabricServiceException, TException { try { ProgramId id = descriptor.getIdentifier(); ProgramRuntimeService.RuntimeInfo existingRuntimeInfo = findRuntimeInfo(id); Preconditions.checkArgument(existingRuntimeInfo == null, UserMessages.getMessage(UserErrors.ALREADY_RUNNING)); final Id.Program programId = Id.Program.from(id.getAccountId(), id.getApplicationId(), id.getFlowId()); Program program = store.loadProgram(programId, entityTypeToType(id)); BasicArguments userArguments = new BasicArguments(); if (descriptor.isSetArguments()) { userArguments = new BasicArguments(descriptor.getArguments()); } ProgramRuntimeService.RuntimeInfo runtimeInfo = runtimeService.run(program, new SimpleProgramOptions(id.getFlowId(), new BasicArguments(), userArguments)); ProgramController controller = runtimeInfo.getController(); final String runId = controller.getRunId().getId(); controller.addListener(new AbstractListener() { @Override public void stopped() { store.setStop(programId, runId, TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS), ProgramController.State.STOPPED.toString()); } @Override public void error(Throwable cause) { LOG.info("Program stopped with error {}, {}", programId, runId, cause); store.setStop(programId, runId, TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS), ProgramController.State.ERROR.toString()); } }, Threads.SAME_THREAD_EXECUTOR); store.setStart(programId, runId, TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)); return new RunIdentifier(runId); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Checks the status of a Program. * * @param token * @param id */ @Override public synchronized ProgramStatus status(AuthToken token, ProgramId id) throws AppFabricServiceException, TException { try { ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(id); int version = 1; // Note, how to get version? if (runtimeInfo == null) { return new ProgramStatus(id.getApplicationId(), id.getFlowId(), null, ProgramController.State.STOPPED.toString()); } Id.Program programId = runtimeInfo.getProgramId(); RunIdentifier runId = new RunIdentifier(runtimeInfo.getController().getRunId().getId()); // NOTE: This was a temporary hack done to map the status to something that is // UI friendly. Internal states of program controller are reasonable and hence // no point in changing them. String status = controllerStateToString(runtimeInfo.getController().getState()); return new ProgramStatus(programId.getApplicationId(), programId.getId(), runId, status); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } private String controllerStateToString(ProgramController.State state) { if (state == ProgramController.State.ALIVE) { return "RUNNING"; } if (state == ProgramController.State.ERROR) { return "FAILED"; } return state.toString(); } /** * Stops a Program. * * @param token * @param identifier */ @Override public synchronized RunIdentifier stop(AuthToken token, ProgramId identifier) throws AppFabricServiceException, TException { try { ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(identifier); Preconditions.checkNotNull(runtimeInfo, UserMessages.getMessage(UserErrors.RUNTIME_INFO_NOT_FOUND), identifier.getApplicationId(), identifier.getFlowId()); ProgramController controller = runtimeInfo.getController(); RunId runId = controller.getRunId(); controller.stop().get(); return new RunIdentifier(runId.getId()); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Set number of instance of a flowlet. * * @param token * @param identifier * @param flowletId * @param instances */ @Override public void setInstances(AuthToken token, ProgramId identifier, String flowletId, short instances) throws AppFabricServiceException, TException { // storing the info about instances count after increasing the count of running flowlets: even if it fails, we // can at least set instances count for this session try { store.setFlowletInstances(Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()), flowletId, instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(identifier); if (runtimeInfo != null) { runtimeInfo.getController().command(ProgramOptionConstants.INSTANCES, ImmutableMap.of(flowletId, (int) instances)).get(); } } catch (Throwable throwable) { LOG.warn("Exception when setting instances for {}.{} to {}. {}", identifier.getFlowId(), flowletId, instances, throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Get number of instance of a flowlet. * * @param token * @param identifier * @param flowletId */ @Override public int getInstances(AuthToken token, ProgramId identifier, String flowletId) throws AppFabricServiceException, TException { try { return store.getFlowletInstances(Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()), flowletId); } catch (Throwable throwable) { LOG.warn("Exception when getting instances for {}.{} to {}. {}", identifier.getFlowId(), flowletId, throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Returns the state of flows within a given account id. * * @param accountId */ @Override public List<ActiveProgram> getPrograms(String accountId) throws AppFabricServiceException, TException { try { Table<Type, Id.Program, List<RunRecord>> histories = store.getAllRunHistory(Id.Account.from(accountId)); List<ActiveProgram> result = Lists.newLinkedList(); for (Table.Cell<Type, Id.Program, List<RunRecord>> cell : histories.cellSet()) { Id.Program programId = cell.getColumnKey(); for (RunRecord runRecord : cell.getValue()) { ActiveProgram activeProgram = new ActiveProgram(programId.getApplicationId(), programId.getId(), typeToEntityType(cell.getRowKey()), runRecord.getStopTs(), runRecord.getStartTs(), null, // TODO 0 // TODO ); result.add(activeProgram); } } return result; } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException("Exception while retrieving the run history. " + throwable.getMessage()); } } private ProgramRuntimeService.RuntimeInfo findRuntimeInfo(ProgramId identifier) { Type type = Type.valueOf(identifier.getType().name()); Collection<ProgramRuntimeService.RuntimeInfo> runtimeInfos = runtimeService.list(type).values(); Preconditions.checkNotNull(runtimeInfos, UserMessages.getMessage(UserErrors.RUNTIME_INFO_NOT_FOUND), identifier.getAccountId(), identifier.getFlowId()); Id.Program programId = Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()); for (ProgramRuntimeService.RuntimeInfo info : runtimeInfos) { if (programId.equals(info.getProgramId())) { return info; } } return null; } /** * Returns definition of a flow. * * @param id */ @Override public String getSpecification(ProgramId id) throws AppFabricServiceException, TException { ApplicationSpecification appSpec; try { appSpec = store.getApplication(new Id.Application(new Id.Account(id.getAccountId()), id.getApplicationId())); if (appSpec == null) { return ""; } String runnableId = id.getFlowId(); if (id.getType() == EntityType.FLOW) { if (appSpec.getFlows().containsKey(runnableId)) { FlowSpecification specification = appSpec.getFlows().get(id.getFlowId()); return new Gson().toJson(specification); } } else if (id.getType() == EntityType.PROCEDURE) { if (appSpec.getProcedures().containsKey(runnableId)) { ProcedureSpecification specification = appSpec.getProcedures().get(id.getFlowId()); return new Gson().toJson(specification); } } else if (id.getType() == EntityType.MAPREDUCE) { if (appSpec.getMapReduces().containsKey(runnableId)) { MapReduceSpecification specification = appSpec.getMapReduces().get(id.getFlowId()); return new Gson().toJson(specification); } } else if (id.getType() == EntityType.WORKFLOW) { if (appSpec.getWorkflows().containsKey(runnableId)) { WorkflowSpecification specification = appSpec.getWorkflows().get(id.getFlowId()); return new Gson().toJson(specification); } } } catch (OperationException e) { LOG.warn(e.getMessage(), e); throw new AppFabricServiceException("Could not retrieve application spec for " + id.toString() + ", reason: " + e.getMessage()); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } return null; } private QueryDefinitionImpl getQueryDefn(final ProgramId identifier) throws AppFabricServiceException { ApplicationSpecification appSpec; try { appSpec = store.getApplication(new Id.Application(new Id.Account(identifier.getAccountId()), identifier.getApplicationId())); } catch (OperationException e) { LOG.warn(e.getMessage(), e); throw new AppFabricServiceException("Could not retrieve application spec for " + identifier.toString() + ", reason: " + e.getMessage()); } ProcedureSpecification procedureSpec = appSpec.getProcedures().get(identifier.getFlowId()); QueryDefinitionImpl queryDef = new QueryDefinitionImpl(); // TODO: fill values (incl. list of datasets ) once they are added to ProcedureSpecification queryDef.setServiceName(procedureSpec.getName()); return queryDef; } private FlowDefinitionImpl getFlowDef4Flow(ProgramId id, FlowSpecification flowSpec) { FlowDefinitionImpl flowDef = new FlowDefinitionImpl(); MetaDefinitionImpl metaDefinition = new MetaDefinitionImpl(); metaDefinition.setApp(id.getApplicationId()); metaDefinition.setName(flowSpec.getName()); flowDef.setMeta(metaDefinition); fillFlowletsAndDataSets(flowSpec, flowDef); fillConnectionsAndStreams(id, flowSpec, flowDef); return flowDef; } // we re-use the ability of existing UI to display flows as a way to display and run mapreduce jobs (for now) private FlowDefinitionImpl getFlowDef4MapReduce(ProgramId id, MapReduceSpecification spec) throws UnsupportedTypeException { FlowSpecification flowSpec = FlowSpecification.Builder.with() .setName(spec.getName()) .setDescription(spec.getDescription()) .withFlowlets() .add("Mapper", new AbstractFlowlet() { public void process(StreamEvent event) {} private OutputEmitter<String> output; }) .add("Reducer", new AbstractFlowlet() { @ProcessInput public void process(String item) {} }) .connect() .fromStream("Input").to("Mapper") .from("Mapper").to("Reducer") .build(); for (FlowletDefinition def : flowSpec.getFlowlets().values()) { def.generateSchema(new ReflectionSchemaGenerator()); } return getFlowDef4Flow(id, flowSpec); } private void fillConnectionsAndStreams(final ProgramId id, final FlowSpecification spec, final FlowDefinitionImpl def) { List<ConnectionDefinitionImpl> connections = new ArrayList<ConnectionDefinitionImpl>(); // we gather streams across all connections, hence we need to eliminate duplicate streams hence using map Map<String, FlowStreamDefinitionImpl> flowStreams = new HashMap<String, FlowStreamDefinitionImpl>(); QueueSpecificationGenerator generator = new SimpleQueueSpecificationGenerator(new Id.Account(id.getAccountId())); Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queues = generator.create(spec); for (Table.Cell<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> conSet : queues.cellSet()) { for (QueueSpecification queueSpec : conSet.getValue()) { String srcName = conSet.getRowKey().getName(); String destName = conSet.getColumnKey(); FlowletStreamDefinitionImpl from; if (!spec.getFlowlets().containsKey(srcName)) { from = new FlowletStreamDefinitionImpl(srcName); flowStreams.put(srcName, new FlowStreamDefinitionImpl(srcName, null)); } else { from = new FlowletStreamDefinitionImpl(srcName, queueSpec.getQueueName().getSimpleName()); } FlowletStreamDefinitionImpl to = new FlowletStreamDefinitionImpl(destName, queueSpec.getQueueName().getSimpleName()); connections.add(new ConnectionDefinitionImpl(from, to)); } } def.setConnections(connections); def.setFlowStreams(new ArrayList<FlowStreamDefinitionImpl>(flowStreams.values())); new StreamNamerImpl().name(id.getAccountId(), def); } private void fillFlowletsAndDataSets(final FlowSpecification flowSpec, final FlowDefinitionImpl flowDef) { Set<String> datasets = new HashSet<String>(); List<FlowletDefinitionImpl> flowlets = new ArrayList<FlowletDefinitionImpl>(); for (FlowletDefinition flowletSpec : flowSpec.getFlowlets().values()) { datasets.addAll(flowletSpec.getDatasets()); FlowletDefinitionImpl flowletDef = new FlowletDefinitionImpl(); flowletDef.setClassName(flowletSpec.getFlowletSpec().getClassName()); if (flowletSpec.getInputs().isEmpty()) { flowletDef.setFlowletType(FlowletType.SOURCE); } else if (flowletSpec.getOutputs().isEmpty()) { flowletDef.setFlowletType(FlowletType.SINK); } else { flowletDef.setFlowletType(FlowletType.COMPUTE); } flowletDef.setInstances(flowletSpec.getInstances()); flowletDef.setName(flowletSpec.getFlowletSpec().getName()); flowlets.add(flowletDef); } flowDef.setFlowlets(flowlets); flowDef.setDatasets(datasets); } /** * Returns run information for a given Runnable id. * * @param id of the program. */ @Override public List<ProgramRunRecord> getHistory(ProgramId id) throws AppFabricServiceException, TException { List<RunRecord> log; try { Id.Program programId = Id.Program.from(id.getAccountId(), id.getApplicationId(), id.getFlowId()); try { log = store.getRunHistory(programId); } catch (OperationException e) { throw new AppFabricServiceException(String.format(UserMessages.getMessage(UserErrors.PROGRAM_NOT_FOUND), id.toString(), e.getMessage())); } List<ProgramRunRecord> history = new ArrayList<ProgramRunRecord>(); for (RunRecord runRecord : log) { history.add(new ProgramRunRecord(runRecord.getPid(), runRecord.getStartTs(), runRecord.getStopTs(), runRecord.getEndStatus()) ); } return history; } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Returns run information for a given flow id. * * @param id */ @Override public void stopAll(String id) throws AppFabricServiceException, TException { // Note: Is id application id? try { List<ListenableFuture<?>> futures = Lists.newLinkedList(); for (Type type : Type.values()) { for (Map.Entry<RunId, ProgramRuntimeService.RuntimeInfo> entry : runtimeService.list(type).entrySet()) { ProgramRuntimeService.RuntimeInfo runtimeInfo = entry.getValue(); if (runtimeInfo.getProgramId().getApplicationId().equals(id)) { futures.add(runtimeInfo.getController().stop()); } } } if (!futures.isEmpty()) { try { Futures.successfulAsList(futures).get(); } catch (Exception e) { LOG.warn(e.getMessage(), e); throw new AppFabricServiceException(e.getMessage()); } } } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Initializes deployment of resources from the client. * <p> * Upon receiving a request to initialize an upload with auth-token and resource information, * we create a unique identifier for the upload and also create directories needed for storing * the uploading archive. At this point the upload has not yet begun. The bytes of the archive * are still on the client machine. An session id is returned back to client - which will use * the session id provided to upload the chunks. * </p> * <p> * <i>Note:</i> As the state of upload are transient they are not being persisted on the server. * </p> * * @param info ArchiveInfo * @return ArchiveId instance containing the resource id and * resource version. */ @Override public ArchiveId init(AuthToken token, ArchiveInfo info) throws AppFabricServiceException { LOG.debug("Init deploying application " + info.toString()); ArchiveId identifier = new ArchiveId(info.getAccountId(), "appId", "resourceId"); try { if (sessions.containsKey(info.getAccountId())) { throw new AppFabricServiceException("An upload is already in progress for this account."); } Location uploadDir = locationFactory.create(archiveDir + "/" + info.getAccountId()); if (!uploadDir.exists() && !uploadDir.mkdirs()) { LOG.warn("Unable to create directory '{}'", uploadDir.getName()); } Location archive = uploadDir.append(info.getFilename()); SessionInfo sessionInfo = new SessionInfo(identifier, info, archive, DeployStatus.REGISTERED); sessions.put(info.getAccountId(), sessionInfo); return identifier; } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Writes chunk of data transmitted from the client. Along with data, there is the session id also * being returned. * * @param resource identifier. * @param chunk binary data of the resource transmitted from the client. * @throws AppFabricServiceException */ @Override public void chunk(AuthToken token, ArchiveId resource, ByteBuffer chunk) throws AppFabricServiceException { if (!sessions.containsKey(resource.getAccountId())) { throw new AppFabricServiceException("A session id has not been created for upload. Please call #init"); } SessionInfo info = sessions.get(resource.getAccountId()).setStatus(DeployStatus.UPLOADING); try { OutputStream stream = info.getOutputStream(); // Read the chunk from ByteBuffer and write it to file if (chunk != null) { byte[] buffer = new byte[chunk.remaining()]; chunk.get(buffer); stream.write(buffer); } else { sessions.remove(resource.getAccountId()); throw new AppFabricServiceException("Invalid chunk received."); } } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); sessions.remove(resource.getAccountId()); throw new AppFabricServiceException("Failed to write archive chunk."); } } /** * Finalizes the deployment of a archive. Once upload is completed, it will * start the pipeline responsible for verification and registration of archive resources. * * @param resource identifier to be finalized. */ @Override public void deploy(AuthToken token, final ArchiveId resource) throws AppFabricServiceException { LOG.debug("Finishing deploy of application " + resource.toString()); if (!sessions.containsKey(resource.getAccountId())) { throw new AppFabricServiceException("No information about archive being uploaded is available."); } final SessionInfo sessionInfo = sessions.get(resource.getAccountId()); DeployStatus status = sessionInfo.getStatus(); try { Id.Account id = Id.Account.from(resource.getAccountId()); Location archiveLocation = sessionInfo.getArchiveLocation(); sessionInfo.getOutputStream().close(); sessionInfo.setStatus(DeployStatus.VERIFYING); Manager<Location, ApplicationWithPrograms> manager = managerFactory.create(); ApplicationWithPrograms applicationWithPrograms = manager.deploy(id, archiveLocation).get(); ApplicationSpecification specification = applicationWithPrograms.getAppSpecLoc().getSpecification(); setupSchedules(resource.getAccountId(), specification); status = DeployStatus.DEPLOYED; } catch (Throwable e) { LOG.warn(e.getMessage(), e); status = DeployStatus.FAILED; if (e instanceof ExecutionException) { Throwable cause = e.getCause(); if (cause instanceof ClassNotFoundException) { status.setMessage(String.format(UserMessages.getMessage(UserErrors.CLASS_NOT_FOUND), cause.getMessage())); } else if (cause instanceof IllegalArgumentException) { status.setMessage(String.format(UserMessages.getMessage(UserErrors.SPECIFICATION_ERROR), cause.getMessage())); } else { status.setMessage(cause.getMessage()); } } status.setMessage(e.getMessage()); throw new AppFabricServiceException(e.getMessage()); } finally { save(sessionInfo.setStatus(status)); sessions.remove(resource.getAccountId()); } } /** * Returns status of deployment of archive. * * @param resource identifier * @return status of resource processing. * @throws AppFabricServiceException */ @Override public DeploymentStatus dstatus(AuthToken token, ArchiveId resource) throws AppFabricServiceException { try { if (!sessions.containsKey(resource.getAccountId())) { SessionInfo info = retrieve(resource.getAccountId()); DeploymentStatus status = new DeploymentStatus(info.getStatus().getCode(), info.getStatus().getMessage()); return status; } else { SessionInfo info = sessions.get(resource.getAccountId()); DeploymentStatus status = new DeploymentStatus(info.getStatus().getCode(), info.getStatus().getMessage()); return status; } } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getMessage()); } } /** * Promotes a FAR from single node to cloud. * * @param id of the flow. * @return true if successful; false otherwise. * @throws AppFabricServiceException */ @Override public boolean promote(AuthToken authToken, ArchiveId id, String hostname) throws AppFabricServiceException { try { Preconditions.checkArgument(!hostname.isEmpty(), "Empty hostname passed."); final Location appArchive = store.getApplicationArchiveLocation(Id.Application.from(id.getAccountId(), id.getApplicationId())); if (appArchive == null || !appArchive.exists()) { throw new AppFabricServiceException("Unable to locate the application."); } String schema = "https"; if ("localhost".equals(hostname)) { schema = "http"; } int port = configuration.getInt(Constants.AppFabric.REST_PORT, 10007); String url = String.format("%s://%s:%d/app", schema, hostname, port); SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder() .setUrl(url) .setRequestTimeoutInMs((int) UPLOAD_TIMEOUT) .setHeader("X-Archive-Name", appArchive.getName()) .setHeader("X-Continuuity-ApiKey", authToken.getToken()) .build(); try { Future<Response> future = client.put(new LocationBodyGenerator(appArchive)); Response response = future.get(UPLOAD_TIMEOUT, TimeUnit.MILLISECONDS); if (response.getStatusCode() != 200) { throw new RuntimeException(response.getResponseBody()); } return true; } finally { client.close(); } } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(throwable.getLocalizedMessage()); } } private static final class LocationBodyGenerator implements BodyGenerator { private final Location location; private LocationBodyGenerator(Location location) { this.location = location; } @Override public Body createBody() throws IOException { final InputStream input = location.getInputStream(); return new Body() { @Override public long getContentLength() { try { return location.length(); } catch (IOException e) { throw Throwables.propagate(e); } } @Override public long read(ByteBuffer buffer) throws IOException { // Fast path if (buffer.hasArray()) { int len = input.read(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); if (len > 0) { buffer.position(buffer.position() + len); } return len; } byte[] bytes = new byte[buffer.remaining()]; int len = input.read(bytes); if (len < 0) { return len; } buffer.put(bytes, 0, len); return len; } @Override public void close() throws IOException { input.close(); } }; } } /** * Deletes a program specified by {@code ProgramId}. * * @param identifier of a flow. * @throws AppFabricServiceException when there is an issue deactivating the flow. */ @Override public void remove(AuthToken token, ProgramId identifier) throws AppFabricServiceException { try { Preconditions.checkNotNull(identifier, "No application id provided."); Id.Program programId = Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()); // Make sure it is not running checkAnyRunning(new Predicate<Id.Program>() { @Override public boolean apply(Id.Program programId) { return programId.equals(programId); } }, Type.values()); Type programType = entityTypeToType(identifier); for (Map.Entry<RunId, ProgramRuntimeService.RuntimeInfo> entry : runtimeService.list(programType).entrySet()) { Preconditions.checkState(!programId.equals(entry.getValue().getProgramId()), "Program still running: application=%s, type=%s, program=%s", programId.getApplication(), programType, programId.getId()); } // Delete the program from store. store.remove(programId); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException("Fail to delete program " + throwable.getMessage()); } } @Override public void removeApplication(AuthToken token, ProgramId identifier) throws AppFabricServiceException { try { Preconditions.checkNotNull(identifier, "No application id provided."); Id.Account accountId = Id.Account.from(identifier.getAccountId()); final Id.Application appId = Id.Application.from(accountId, identifier.getApplicationId()); // Check if all are stopped. checkAnyRunning(new Predicate<Id.Program>() { @Override public boolean apply(Id.Program programId) { return programId.getApplication().equals(appId); } }, Type.values()); deleteProgramLocations(appId); Location appArchive = store.getApplicationArchiveLocation(appId); Preconditions.checkNotNull(appArchive, "Could not find the location of application", appId.getId()); appArchive.delete(); deleteMetrics(identifier.getAccountId(), identifier.getApplicationId()); store.removeApplication(appId); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException("Fail to delete program " + throwable.getMessage()); } } private void checkAnyRunning(Predicate<Id.Program> predicate, Type... types) { for (Type type : types) { for (Map.Entry<RunId, ProgramRuntimeService.RuntimeInfo> entry : runtimeService.list(type).entrySet()) { Id.Program programId = entry.getValue().getProgramId(); if (predicate.apply(programId)) { throw new IllegalStateException(String.format("Program still running: %s %s %s %s", programId.getApplicationId(), type, programId.getId(), entry.getValue().getController().getRunId())); } } } } /** * Delete the jar location of the program. * * @param appId applicationId. * @throws IOException if there are errors with location IO */ private void deleteProgramLocations(Id.Application appId) throws IOException, OperationException { ApplicationSpecification specification = store.getApplication(appId); Iterable<ProgramSpecification> programSpecs = Iterables.concat(specification.getFlows().values(), specification.getMapReduces().values(), specification.getProcedures().values(), specification.getWorkflows().values()); for (ProgramSpecification spec : programSpecs){ Type type = Type.typeOfSpecification(spec); Id.Program programId = Id.Program.from(appId, spec.getName()); Location location = Programs.programLocation(locationFactory, appFabricDir, programId, type); location.delete(); } } @Override public void removeAll(AuthToken token, String account) throws AppFabricServiceException { Preconditions.checkNotNull(account); // TODO: Is it the same as reset?? } @Override public void reset(AuthToken token, String account) throws AppFabricServiceException { final Id.Account accountId; try { Preconditions.checkNotNull(account); accountId = Id.Account.from(account); // Check if any program is still running checkAnyRunning(new Predicate<Id.Program>() { @Override public boolean apply(Id.Program programId) { return programId.getAccountId().equals(accountId.getId()); } }, Type.values()); deleteMetrics(account); // delete all meta data store.removeAll(accountId); // delete queues data queueAdmin.dropAll(); LOG.info("Deleting all data for account '" + account + "'."); dataSetAccessor.dropAll(DataSetAccessor.Namespace.USER); // NOTE: there could be services running at the moment that rely on the system datasets to be available dataSetAccessor.truncateAll(DataSetAccessor.Namespace.SYSTEM); LOG.info("All data for account '" + account + "' deleted."); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); throw new AppFabricServiceException(String.format(UserMessages.getMessage(UserErrors.RESET_FAIL), throwable.getMessage())); } } @Override public void resumeSchedule(AuthToken token, ScheduleId identifier) throws AppFabricServiceException, TException { Preconditions.checkNotNull(identifier, "No program id provided."); scheduler.resumeSchedule(identifier.getId()); } @Override public void suspendSchedule(AuthToken token, ScheduleId identifier) throws AppFabricServiceException, TException { Preconditions.checkNotNull(identifier, "No program id provided."); scheduler.suspendSchedule(identifier.getId()); } @Override public List<ScheduleId> getSchedules(AuthToken token, ProgramId identifier) throws AppFabricServiceException, TException { Preconditions.checkNotNull(identifier, "No program id provided."); Id.Program programId = Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()); Type programType = entityTypeToType(identifier); List<ScheduleId> scheduleIds = Lists.newArrayList(); for (String id : scheduler.getScheduleIds(programId, programType)) { scheduleIds.add(new ScheduleId(id)); } return scheduleIds; } @Override public List<ScheduleRunTime> getNextScheduledRunTime(AuthToken token, ProgramId identifier) throws TException { Preconditions.checkNotNull(identifier, "No program id provided."); Id.Program programId = Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()); Type programType = entityTypeToType(identifier); List<ScheduledRuntime> runtimes = scheduler.nextScheduledRuntime(programId, programType); List<ScheduleRunTime> r = Lists.newArrayList(); for (ScheduledRuntime runtime : runtimes) { r.add(new ScheduleRunTime(new ScheduleId(runtime.getScheduleId()), runtime.getTime())); } return r; } @Override public void storeRuntimeArguments(AuthToken token, ProgramId identifier, Map<String, String> arguments) throws AppFabricServiceException, TException { Preconditions.checkNotNull(identifier, "No program id provided."); Id.Program programId = Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()); try { store.storeRunArguments(programId, arguments); } catch (OperationException e) { LOG.warn("Error storing runtime args {}", e.getMessage(), e); throw new AppFabricServiceException(e.getMessage()); } } @Override public Map<String, String> getRuntimeArguments(AuthToken token, ProgramId identifier) throws AppFabricServiceException, TException { Preconditions.checkNotNull(identifier, "No program id provided."); Id.Program programId = Id.Program.from(identifier.getAccountId(), identifier.getApplicationId(), identifier.getFlowId()); try { return store.getRunArguments(programId); } catch (OperationException e) { LOG.warn("Error getting runtime args {}", e.getMessage(), e); throw new AppFabricServiceException(e.getMessage()); } } /** * Deletes metrics for a given account. * * @param accountId for which the metrics need to be reset. * @throws IOException throw due to issue in reseting metrics for * @throws TException on thrift errors while talking to thrift service * @throws MetadataServiceException on errors from metadata service */ private void deleteMetrics(String accountId) throws IOException, TException, MetadataServiceException { List<Application> applications = this.mds.getApplications(accountId); Iterable<Discoverable> discoverables = this.discoveryServiceClient.discover(Constants.Service.METRICS); Discoverable discoverable = new TimeLimitEndpointStrategy(new RandomEndpointStrategy(discoverables), DISCOVERY_TIMEOUT_SECONDS, TimeUnit.SECONDS).pick(); if (discoverable == null) { LOG.error("Fail to get any metrics endpoint for deleting metrics."); return; } for (Application application : applications){ String url = String.format("http://%s:%d/metrics/app/%s", discoverable.getSocketAddress().getHostName(), discoverable.getSocketAddress().getPort(), application.getId()); SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder() .setUrl(url) .setRequestTimeoutInMs((int) METRICS_SERVER_RESPONSE_TIMEOUT) .build(); client.delete(); } String url = String.format("http://%s:%d/metrics", discoverable.getSocketAddress().getHostName(), discoverable.getSocketAddress().getPort()); SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder() .setUrl(url) .setRequestTimeoutInMs((int) METRICS_SERVER_RESPONSE_TIMEOUT) .build(); client.delete(); } private void deleteMetrics(String account, String application) throws IOException { Iterable<Discoverable> discoverables = this.discoveryServiceClient.discover(Constants.Service.METRICS); Discoverable discoverable = new TimeLimitEndpointStrategy(new RandomEndpointStrategy(discoverables), DISCOVERY_TIMEOUT_SECONDS, TimeUnit.SECONDS).pick(); if (discoverable == null) { LOG.error("Fail to get any metrics endpoint for deleting metrics."); return; } String url = String.format("http://%s:%d/metrics/app/%s", discoverable.getSocketAddress().getHostName(), discoverable.getSocketAddress().getPort(), application); LOG.debug("Deleting metrics for application {}", application); SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder() .setUrl(url) .setRequestTimeoutInMs((int) METRICS_SERVER_RESPONSE_TIMEOUT) .build(); client.delete(); } /** * Saves the {@link SessionInfo} to the filesystem. * * @param info to be saved. * @return true if and only if successful; false otherwise. */ private boolean save(SessionInfo info) { try { Gson gson = new GsonBuilder().registerTypeAdapter(Location.class, new LocationCodec(locationFactory)).create(); String accountId = info.getArchiveId().getAccountId(); Location outputDir = locationFactory.create(archiveDir + "/" + accountId); if (!outputDir.exists()) { return false; } final Location sessionInfoFile = outputDir.append("session.json"); OutputSupplier<Writer> writer = new OutputSupplier<Writer>() { @Override public Writer getOutput() throws IOException { return new OutputStreamWriter(sessionInfoFile.getOutputStream(), "UTF-8"); } }; Writer w = writer.getOutput(); try { gson.toJson(info, w); } finally { Closeables.closeQuietly(w); } } catch (IOException e) { LOG.warn(e.getMessage(), e); return false; } return true; } /** * Retrieves a {@link SessionInfo} from the file system. * * @param accountId to which the * @return */ @Nullable private SessionInfo retrieve(String accountId) { try { final Location outputDir = locationFactory.create(archiveDir + "/" + accountId); if (!outputDir.exists()) { return null; } final Location sessionInfoFile = outputDir.append("session.json"); InputSupplier<Reader> reader = new InputSupplier<Reader>() { @Override public Reader getInput() throws IOException { return new InputStreamReader(sessionInfoFile.getInputStream(), "UTF-8"); } }; Gson gson = new GsonBuilder().registerTypeAdapter(Location.class, new LocationCodec(locationFactory)).create(); Reader r = reader.getInput(); try { SessionInfo info = gson.fromJson(r, SessionInfo.class); return info; } finally { Closeables.closeQuietly(r); } } catch (IOException e) { LOG.warn("Failed to retrieve session info for account."); } return null; } private void setupSchedules(String accountId, ApplicationSpecification specification) throws IOException { for (Map.Entry<String, WorkflowSpecification> entry : specification.getWorkflows().entrySet()){ Id.Program programId = Id.Program.from(accountId, specification.getName(), entry.getKey()); scheduler.schedule(programId, Type.WORKFLOW, entry.getValue().getSchedules()); } } }
package edu.uoregon.casls.aris_android.object_controllers; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import edu.uoregon.casls.aris_android.ARISWebView; import edu.uoregon.casls.aris_android.GamePlayActivity; import edu.uoregon.casls.aris_android.R; import edu.uoregon.casls.aris_android.Utilities.AppConfig; import edu.uoregon.casls.aris_android.data_objects.Instance; import edu.uoregon.casls.aris_android.data_objects.Media; import edu.uoregon.casls.aris_android.data_objects.Plaque; import edu.uoregon.casls.aris_android.data_objects.Tab; import edu.uoregon.casls.aris_android.media.ARISMediaViewFragment; import edu.uoregon.casls.aris_android.models.InstancesModel; public class PlaqueViewFragment extends Fragment { public Plaque mPlaque; public Instance mInstance; public InstancesModel instancesModel; public Tab tab; public ARISMediaViewFragment mediaViewFrag; public static View mPlaqueView; public ARISWebView webView; public GamePlayActivity mGamePlayActivity; private OnFragmentInteractionListener mListener; public PlaqueViewFragment() { } public void initContext(GamePlayActivity gamePlayAct) { mGamePlayActivity = gamePlayAct; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGamePlayActivity = (GamePlayActivity) getActivity(); if (getArguments() != null) { // mParam1 = getArguments().getString(ARG_PARAM1); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mPlaqueView = inflater.inflate(R.layout.fragment_plaque_view, container, false); // FragmentTransaction ft = mGamePlayActivity.getSupportFragmentManager().beginTransaction(); // Init fragment mediaViewFrag = new ARISMediaViewFragment(); mediaViewFrag.initContext(mGamePlayActivity); // add a frag inside another (this) frag. getChildFragmentManager().beginTransaction().add(R.id.fl_plaque_media_view_container, mediaViewFrag).commit(); getChildFragmentManager().executePendingTransactions(); return mPlaqueView; } @Override public void onResume() { super.onResume(); // presumably the media fragment has now loaded and passed initial lifecycle calls so we can // tell it to load stuff. Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment.onResume; "); this.loadView(); } public void initWithInstance(Instance i) { // delegate = d; // Android app eschews the delegates (for now, anyway) Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment.initWithInstance called; "); mInstance = i; mPlaque = mGamePlayActivity.mGame.plaquesModel.plaqueForId(mInstance.object_id); if (mPlaque.event_package_id > 0) mGamePlayActivity.mGame.eventsModel.runEventPackageId(mPlaque.event_package_id); // this.title = this.tabTitle; // iOS IU stuff. } public void initWithTab(Tab t) { // delegate = d; tab = t; mInstance = mGamePlayActivity.mGame.instancesModel.instanceForId(0); //get null inst mInstance.object_type = tab.type; mInstance.object_id = tab.content_id; mPlaque = mGamePlayActivity.mGame.plaquesModel.plaqueForId(mInstance.object_id); // self.title = plaque.name; // iOS } // todo: call from onCreateView? public void loadView() { // mediaView = [[ARISMediaView alloc] initWithDelegate:self]; // [mediaView setDisplayMode:ARISMediaDisplayModeTopAlignAspectFitWidthAutoResizeHeight]; // FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); // transaction.add(R.id.ll_plaque_media_view_container, mediaViewFrag).commit(); // add a frag inside another (this) frag. // getChildFragmentManager().beginTransaction().add(R.id.fl_plaque_media_view_container, mediaViewFrag).commit(); // getChildFragmentManager().executePendingTransactions(); // Show Continue text and forward button if continue_function != NONE // In Android: Hide these features if continue_function == NONE Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment.loadView; looking at continue_function: " + mPlaque.continue_function); if (mPlaque.continue_function.contentEquals("NONE")) { //fixme: NPE here: Attempt to read from field 'java.lang.String edu.uoregon.casls.aris_android.data_objects.Plaque.continue_function' on a null object reference RelativeLayout continueFooter = (RelativeLayout) mPlaqueView.findViewById(R.id.rl_plaque_footer); continueFooter.setVisibility(View.INVISIBLE); } else { ImageView ivContinueArrow = (ImageView) mPlaqueView.findViewById(R.id.iv_plaque_footer_right_arrow); ivContinueArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { continueButtonTouched(v); } }); ivContinueArrow.bringToFront(); ivContinueArrow.setClickable(true); } this.loadPlaque(); } public void loadPlaque() { Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment.loadPlaque; "); if (!mPlaque.name.isEmpty()) { // set plaqueue title TextView tvPlaqueueTitle = (TextView) mPlaqueView.findViewById(R.id.tv_plaque_title); tvPlaqueueTitle.setText(mPlaque.name); } if (!mPlaque.description.contentEquals("")) { // load the description webview Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment.loadPlaque with description webview; "); webView = (ARISWebView) mPlaqueView.findViewById(R.id.wv_plaque_desc); webView.initContextAndInjectJavaScript(mGamePlayActivity); webView.loadHTMLString(mPlaque.description); } // load associated media into media fragment todo: may just want to put fragment into includable view with ordinary class? Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment. looking for Plaque media; "); Media media = mGamePlayActivity.mMediaModel.mediaForId(mPlaque.media_id); if (media != null) { Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, "PlaqueViewFragment. setting webview with Plaque media; "); mediaViewFrag.setMedia(media); // [mediaView setMedia:media]; } } public void continueButtonTouched(View v) { Log.d(AppConfig.LOGTAG + AppConfig.LOGTAG_D1, getClass().getSimpleName() + " continueButtonTouched. mPlaque.continue_function = " + mPlaque.continue_function); if (mPlaque.continue_function.contentEquals("JAVASCRIPT")) { webView.hookWithParams(""); } else if (mPlaque.continue_function.contentEquals("EXIT")) { this.dismissSelf(); } } private void dismissSelf() { if (tab != null) this.showNav(); if (mListener != null) { mListener.fragmentPlaqueDismiss(); } // the following iOS logic wil happen in GamePlayActivity.fragmentPlaqueExit(); } private void showNav() { mListener.gamePlayTabBarViewControllerRequestsNav(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDestroyView() { super.onDestroyView(); mGamePlayActivity.viewingInstantiableObject = false; } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void fragmentPlaqueDismiss(); void onFragmentInteraction(Uri uri); void gamePlayTabBarViewControllerRequestsNav(); } }
package org.noorganization.instalist.controller.database_seed; import android.util.Log; import com.orm.query.Condition; import com.orm.query.Select; import org.noorganization.instalist.controller.ListModificationListener; import org.noorganization.instalist.controller.implementation.ListController; import org.noorganization.instalist.model.ListEntry; import org.noorganization.instalist.model.Product; import org.noorganization.instalist.model.ShoppingList; import org.noorganization.instalist.model.Unit; import java.util.ArrayList; import java.util.List; import java.util.Random; public class DatabaseSeeder { private final static String LOG_TAG = DatabaseSeeder.class.getName(); private static DatabaseSeeder mInstance; private final String SAMPLE_TAG = "SAMPLE"; private final int PRODUCT_TEST_DATA_SIZE = 10; private final long PRODUCT_LIST_SEED = 324982340237840L; private ListModificationListener mListController; public static DatabaseSeeder getInstance(){ if(mInstance == null) mInstance = new DatabaseSeeder(); return mInstance; } // PRIVATE AREA private DatabaseSeeder(){ mListController = ListController.getInstance(); } /** * Fill the database with some sample data. */ public void startUp(){ List<ShoppingList> shoppingList = ShoppingList.listAll(ShoppingList.class); for(ShoppingList list : shoppingList) { List<ListEntry> listEntries = Select.from(ListEntry.class).where( Condition.prop("m_list").eq(list.getId())).list(); for(ListEntry listEntry : listEntries) { if(mListController.removeItem(listEntry)){ Log.d(LOG_TAG, "Deleted item."); }else{ Log.d(LOG_TAG, "Deletion of item failed."); } } if(mListController.removeList(list)){ Log.d(LOG_TAG, "Delete list successful."); } else{ Log.d(LOG_TAG, "Delete list failed."); } } Random rand = new Random(PRODUCT_LIST_SEED); String[] listNames = new String[]{SAMPLE_TAG.concat("_Home"), SAMPLE_TAG.concat("_Work")}; String[] listProductNames = new String[]{"Sugar", "Beer", "Cheese", "Ham", "Nails", "Grenade Apple Juice"}; String[] listUnitNames = new String[]{"g", "kg", "ml", "l", "hl", "pfund"}; List<Product> productList = new ArrayList<>(); List<ShoppingList> shoppingLists = new ArrayList<>(); // add new lists for(String listName : listNames) { shoppingLists.add(mListController.addList(listName)); Log.d(LOG_TAG, "List name: " + listName); //shoppingLists[counter].save(); } for(int Index = 0; Index < PRODUCT_TEST_DATA_SIZE; ++ Index){ String productName; Product singleProduct; Unit singleUnit; productName = listProductNames[rand.nextInt(listProductNames.length)].concat("_" + String.valueOf(Index)); // singleUnit = new Unit(listUnitNames[rand.nextInt(listUnitNames.length)]); // singleUnit.save(); singleProduct = new Product(productName, null, 1.0f, 1.0f); singleProduct.save(); productList.add(singleProduct); } for(Product product : productList){ Log.d(LOG_TAG, "Add Product: " + product.mName); //mListController.addOrChangeItem(shoppingLists[rand.nextInt(shoppingLists.length)], product, rand.nextFloat()); ShoppingList list = shoppingLists.get(rand.nextInt(shoppingLists.size())); Log.d(LOG_TAG, "List name: " + list.mName); ListEntry listEntry = new ListEntry(list, product, rand.nextFloat() * 100.0f); listEntry.save(); } } /** * Delete all sample data from database. */ public void tearDown(){ List<ShoppingList> shoppingLists = ShoppingList.listAll(ShoppingList.class); List<ListEntry> listEntries = ListEntry.listAll(ListEntry.class); for(ListEntry listEntry : listEntries) mListController.removeItem(listEntry); for( ShoppingList shoppingList : shoppingLists) mListController.removeList(shoppingList); } }
package org.noorganization.instalist.view.fragment; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import org.noorganization.instalist.R; import org.noorganization.instalist.controller.IListController; import org.noorganization.instalist.controller.implementation.ControllerFactory; import org.noorganization.instalist.model.Ingredient; import org.noorganization.instalist.model.ListEntry; import org.noorganization.instalist.model.Product; import org.noorganization.instalist.model.Recipe; import org.noorganization.instalist.model.ShoppingList; import org.noorganization.instalist.model.view.BaseItemListEntry; import org.noorganization.instalist.model.view.ProductListEntry; import org.noorganization.instalist.model.view.RecipeListEntry; import org.noorganization.instalist.model.view.SelectableBaseItemListEntry; import org.noorganization.instalist.view.MainShoppingListView; import org.noorganization.instalist.view.datahandler.SelectableBaseItemListEntryDataHolder; import org.noorganization.instalist.view.interfaces.IBaseActivity; import org.noorganization.instalist.view.listadapter.SelectableItemListAdapter; import org.noorganization.instalist.view.utils.ViewUtils; import java.util.ArrayList; import java.util.List; public class ProductListDialogFragment extends Fragment{ public static final String FILTER_BY_PRODUCT = "0"; public static final String FILTER_BY_RECIPE = "1"; public static final String FILTER_SHOW_ALL = "2"; private ShoppingList mCurrentShoppingList; private Button mAddNewProductButton; private Button mCancelButton; private Button mAddProductsButton; private Button mTempAddRecipeButton; // create the abstract selectable list entries to show mixed entries private List<SelectableBaseItemListEntry> mSelectableBaseItemListEntries = new ArrayList<>(); private SelectableItemListAdapter mListAdapter; private IBaseActivity mBaseActivityInterface; private Context mContext; /** * Creates an instance of an ProductListDialogFragment. * @param _ListName the name of the list where the products should be added. * @return the new instance of this fragment. */ public static ProductListDialogFragment newInstance(String _ListName){ ProductListDialogFragment fragment = new ProductListDialogFragment(); Bundle args = new Bundle(); args.putString(MainShoppingListView.KEY_LISTNAME, _ListName); fragment.setArguments(args); return fragment; } @Override public void onAttach(Activity _Activity) { super.onAttach(_Activity); mContext = _Activity; try { mBaseActivityInterface = (IBaseActivity) _Activity; } catch (ClassCastException e) { throw new ClassCastException(_Activity.toString() + " has no IBaseActivity interface attached."); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get bundle args to get the listname that should be shown Bundle bundle = this.getArguments(); if (bundle == null) { return; } setHasOptionsMenu(true); String currentListName = bundle.getString(MainShoppingListView.KEY_LISTNAME); mCurrentShoppingList = ShoppingList.findByName(currentListName); if(mCurrentShoppingList == null){ throw new IllegalStateException(ProductListDialogFragment.class.toString() + ": Cannot find corresponding ShoppingList with name: " + currentListName); } List<Product> productList = Product.listAll(Product.class); List<Recipe> recipeList = Recipe.listAll(Recipe.class); List<ListEntry> listEntries = mCurrentShoppingList.getEntries(); // remove all inserted list entries for(ListEntry listEntry : listEntries){ productList.remove(listEntry.mProduct); } for(Product product: productList){ mSelectableBaseItemListEntries.add(new SelectableBaseItemListEntry(new ProductListEntry(product))); } for(Recipe recipe: recipeList){ mSelectableBaseItemListEntries.add(new SelectableBaseItemListEntry(new RecipeListEntry(recipe))); } mAddProductsListener = new OnAddProductsListener(); mCancelListener = new OnCancelListener(); mCreateProductListener = new OnCreateProductListener(); } @Override public void onActivityCreated(Bundle _SavedIndstance) { super.onActivityCreated(_SavedIndstance); mBaseActivityInterface.setToolbarTitle(mContext.getResources().getString(R.string.product_list_dialog_title)); mBaseActivityInterface.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mBaseActivityInterface.setNavigationIcon(R.mipmap.ic_arrow_back_white_36dp); mBaseActivityInterface.setNavigationClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBaseActivityInterface.onBackPressed(); } }); } @Override public View onCreateView(LayoutInflater _Inflater, ViewGroup _Container, Bundle _SavedInstanceState) { super.onCreateView(_Inflater, _Container, _SavedInstanceState); View view = _Inflater.inflate(R.layout.fragment_product_list_dialog, _Container, false); mListAdapter = new SelectableItemListAdapter(getActivity(), mSelectableBaseItemListEntries, mCurrentShoppingList); mAddNewProductButton = (Button) view.findViewById(R.id.fragment_product_list_dialog_add_new_product); mCancelButton = (Button) view.findViewById(R.id.fragment_product_list_dialog_cancel); mAddProductsButton = (Button) view.findViewById(R.id.fragment_product_list_dialog_add_products_to_list); mTempAddRecipeButton = (Button) view.findViewById(R.id.testRecipeButton); ListView listView = (ListView) view.findViewById(R.id.fragment_product_list_dialog_product_list_view); listView.setAdapter(mListAdapter); mBaseActivityInterface.setToolbarTitle(mContext.getResources().getString(R.string.product_list_dialog_title) + " " + mCurrentShoppingList.mName); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_product_list_dialog, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.menu_product_list_dialog_filter_by_product: mListAdapter.getFilter().filter(FILTER_BY_PRODUCT); break; case R.id.menu_product_list_dialog_filter_by_recipe: mListAdapter.getFilter().filter(FILTER_BY_RECIPE); break; case R.id.menu_product_list_dialog_filter_by_all: mListAdapter.getFilter().filter(FILTER_SHOW_ALL); break; case R.id.menu_product_list_dialog_sort_by_name: break; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); mAddNewProductButton.setOnClickListener(mCreateProductListener); mCancelButton.setOnClickListener(mCancelListener); mAddProductsButton.setOnClickListener(mAddProductsListener); mTempAddRecipeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ViewUtils.addFragment(getActivity(), RecipeCreationFragment.newInstance(mCurrentShoppingList.mName)); ViewUtils.removeFragment(getActivity(), ProductListDialogFragment.this); } }); } @Override public void onPause() { super.onPause(); mAddNewProductButton.setOnClickListener(null); mCancelButton.setOnClickListener(null); mAddProductsButton.setOnClickListener(null); } /** * Assign to add all selected list items to the current list. */ private View.OnClickListener mAddProductsListener; /** * Assign to go back to the last fragment. */ private View.OnClickListener mCancelListener; /** * Assign to call add new product overview. */ private View.OnClickListener mCreateProductListener; private class OnAddProductsListener implements View.OnClickListener { @Override public void onClick(View v) { List<SelectableBaseItemListEntry> listEntries = SelectableBaseItemListEntryDataHolder.getInstance().getListEntries(); IListController mListController = ControllerFactory.getListController(); for(SelectableBaseItemListEntry listEntry : listEntries){ // 2 possible solutions for adding to current shoppinglist // first would be like add all single items with the controller // second would be add all to added products to a list and persist it then to the database --> less db writes when recipes hold same items. if(listEntry.isChecked()){ BaseItemListEntry baseItemListEntry = listEntry.getItemListEntry(); switch (baseItemListEntry.getType()){ case PRODUCT_LIST_ENTRY: Product product = (Product)(baseItemListEntry.getEntry().getObject()); ListEntry listEntryIntern = mListController.addOrChangeItem(mCurrentShoppingList, product, 1.0f); if(listEntryIntern == null){ Log.e(ProductListDialogFragment.class.getName(), "Insertion failed."); } break; case RECIPE_LIST_ENTRY: Recipe recipe = (Recipe) (baseItemListEntry.getEntry().getObject()); if(recipe == null){ Log.e(ProductListDialogFragment.class.getName(), "recipe is null."); throw new NullPointerException(ProductListDialogFragment.class.getName() + ": Recipe cannot be found."); } List<Ingredient> ingredients = recipe.getIngredients(); for(Ingredient ingredient : ingredients){ product = ingredient.mProduct; mListController.addOrChangeItem(mCurrentShoppingList, product, ingredient.mAmount, true); } break; default: throw new IllegalStateException(ProductListDialogFragment.class.toString() + ". There is a item type that is not handled."); } } } SelectableBaseItemListEntryDataHolder.getInstance().clear(); // go back to old fragment ViewUtils.removeFragment(getActivity(), ProductListDialogFragment.this); } } private class OnCancelListener implements View.OnClickListener { @Override public void onClick(View v) { ViewUtils.removeFragment(getActivity(), ProductListDialogFragment.this); } } private class OnCreateProductListener implements View.OnClickListener { @Override public void onClick(View v) { ProductChangeFragment creationFragment = ProductChangeFragment.newInstance(mCurrentShoppingList.mName); ViewUtils.addFragment(getActivity(), creationFragment); ViewUtils.removeFragment(getActivity(), ProductListDialogFragment.this); } } }
package com.faveset.khttp; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; // TODO: // add file sending and chunked transfers. class ResponseWriter implements HttpResponseWriter { public interface OnSendCallback { void onSend(); } // 1.1 is the default version. private static final int sHttpMinorVersionDefault = 1; private static final Map<Integer, String> sReasonMap; // This is the default reason that will be reported if one is not found // in sReasonMap. private static final String sUnknownReason = "Unknown"; // Most web servers set the max total header length to 4-8KB, so // we'll just choose a standard page size. The pool will grow as // needed; though, this size should handle most cases without additional // allocations. private static final int sBufferSize = 4096; private HeadersBuilder mHeadersBuilder; private ByteBufferPool mBufPool; private OnSendCallback mSendCallback; private NonBlockingConnection.OnSendCallback mNbcSendCallback; // Tracks whether writeHeader() has been called explicitly. private boolean mWroteHeaders; private int mHttpMinorVersion; // HTTP status code for the response. private int mStatus; // Tracks the number of bytes sent for the result. private long mSentCount; public ResponseWriter() { mHeadersBuilder = new HeadersBuilder(); // Use direct allocations. mBufPool = new ByteBufferPool(sBufferSize, true); mNbcSendCallback = new NonBlockingConnection.OnSendCallback() { public void onSend(NonBlockingConnection conn) { mSendCallback.onSend(); } }; mHttpMinorVersion = sHttpMinorVersionDefault; mStatus = HttpStatus.OK; } /** * Resets the ResponseWriter state so that it can be reused. */ public void clear() { mHeadersBuilder.clear(); mBufPool.clear(); mWroteHeaders = false; mHttpMinorVersion = sHttpMinorVersionDefault; mStatus = HttpStatus.OK; mSentCount = 0; } public HeadersBuilder getHeadersBuilder() { return mHeadersBuilder; } /** * @return the number of bytes sent for the response. */ public long getSentCount() { return mSentCount; } /** * @return the HTTP status code for the response. */ public int getStatus() { return mStatus; } /** * Finalizes the response and sends it over the connection. This manages * NonBlockingConnection callbacks until completion and then calls * callback when sending is done. * * The callback should clear the ResponseWriter's state before reusing * the ResponseWriter. */ public void send(NonBlockingConnection conn, OnSendCallback callback) { mSendCallback = callback; long remCount = mBufPool.remaining(); mSentCount = remCount; ByteBuffer[] bufs = mBufPool.build(); conn.send(mNbcSendCallback, bufs, remCount); } /** * Configures the ResponseWriter to use an HTTP minor version of * minorVersion. Major version will always be 1. * * @return this for chaining. */ public ResponseWriter setHttpMinorVersion(int minorVersion) { mHttpMinorVersion = minorVersion; return this; } /** * Uses buf as the data for the HTTP reply. * * This will implicitly call writeHeader with status OK if not already * performed by the caller. */ public void write(ByteBuffer buf) { writeHeader(HttpStatus.OK); mBufPool.writeBuffer(buf); } public void write(String s) { writeHeader(HttpStatus.OK); mBufPool.writeString(s); } /** * Prepares and writes an HTTP response header with given status code. * If not called, the other write methods will call this implicitly with * status OK. */ public void writeHeader(int statusCode) throws BufferOverflowException { if (mWroteHeaders) { return; } mStatus = statusCode; String reason = sReasonMap.get(statusCode); if (reason == null) { reason = sUnknownReason; } String statusLine = String.format("HTTP/1.%d %d, %s\r\n", mHttpMinorVersion, statusCode, reason); mBufPool.writeString(statusLine); mHeadersBuilder.write(mBufPool); // Terminal CRLF. mBufPool.writeString(Strings.CRLF); // We're now ready for the message-body. mWroteHeaders = true; } static { // These are taken from RFC2616 recommendations. sReasonMap = new HashMap<Integer, String>(); sReasonMap.put(100, "Continue"); sReasonMap.put(101, "Switching Protocols"); sReasonMap.put(200, "OK"); sReasonMap.put(201, "Created"); sReasonMap.put(202, "Accepted"); sReasonMap.put(203, "Non-Authoritative Information"); sReasonMap.put(204, "No Content"); sReasonMap.put(205, "Reset Content"); sReasonMap.put(206, "Partial Content"); sReasonMap.put(300, "Multiple Choices"); sReasonMap.put(301, "Moved Permanently"); sReasonMap.put(302, "Found"); sReasonMap.put(303, "See Other"); sReasonMap.put(304, "Not Modified"); sReasonMap.put(305, "Use Proxy"); sReasonMap.put(307, "Temporary Redirect"); sReasonMap.put(400, "Bad Request"); sReasonMap.put(401, "Unauthorized"); sReasonMap.put(402, "Payment Required "); sReasonMap.put(403, "Forbidden"); sReasonMap.put(404, "Not Found"); sReasonMap.put(405, "Method Not Allowed"); sReasonMap.put(406, "Not Acceptable"); sReasonMap.put(407, "Proxy Authentication Required"); sReasonMap.put(408, "Request Time-out"); sReasonMap.put(409, "Conflict"); sReasonMap.put(410, "Gone"); sReasonMap.put(411, "Length Required"); sReasonMap.put(412, "Precondition Failed"); sReasonMap.put(413, "Request Entity Too Large"); sReasonMap.put(414, "Request-URI Too Large"); sReasonMap.put(415, "Unsupported Media Type"); sReasonMap.put(416, "Requested range not satisfiable"); sReasonMap.put(417, "Expectation Failed"); sReasonMap.put(500, "Internal Server Error"); sReasonMap.put(501, "Not Implemented"); sReasonMap.put(502, "Bad Gateway"); sReasonMap.put(503, "Service Unavailable"); sReasonMap.put(504, "Gateway Time-out"); sReasonMap.put(505, "HTTP Version not supported"); } }
package Services.Books; import Services.Books.BooksarrayJSON.Books; import com.google.gson.Gson; import com.google.gson.*; import com.google.common.collect.Lists; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.reflect.Type; import java.util.Map.Entry; public class BooksService { private static HashMap<String, String> book ; private static List<HashMap<String,String>> arrayList ; private static ArrayList<Books> BooksList ; private LinkedList<Integer> BooksIDs = new LinkedList<>();// {"00001", "00002"}; // private String[] BooksNames = {"Engineering Psychology and Human Performance", "Some Book"}; private LinkedList<String> BooksNames = new LinkedList<>(); //private String[] BooksAuthors = {"Christopher D. Wickens , Justin G. Hollands, Simon Banbury, Raja Parasuraman", "Many Authors"}; private LinkedList<String> BooksAuthors = new LinkedList<>(); // private String[] BooksCondition = {"New", "Used - Very Good"}; private LinkedList<String> BooksCondition = new LinkedList<>(); // private String[] BooksUniversity = {"University of Pittsburgh", "CMU"}; private LinkedList<String> BooksUniversity = new LinkedList<>(); // private String[] BooksSchool = {"School of Information Science", "CS"}; private LinkedList<String> BooksSchool = new LinkedList<>(); // private String[] BooksDescription = {"Forming connections between human performance and design Engineering Psychology and Human" // + " Performance, 4e examines human-machine interaction. The book is organized directly from the psychological " // + "perspective of human information processing. The chapters generally correspond to the flow of information as it is " // + "processed by a human being--from the senses, through the brain, to action--rather than from the perspective of " // + "system components or engineering design concepts. This book is ideal for a psychology student, engineering student, " // + "or actual practitioner in engineering psychology, human performance, and human factors Learning Goals Upon " // + "completing this book, readers should be able to: * Identify how human ability contributes to the design of " // + "technology. * Understand the connections within human information processing and human performance. * Challenge the" // + " way they think about technology's influence on human performance. * show how theoretical advances have been, or " // + "might be, applied to improving human-machine interaction", "Test Description"}; private LinkedList<String> BooksDescription = new LinkedList<>(); //private String[] BooksISBN13 = {"978-0205021987", "111-2233445566"}; private LinkedList<String> BooksISBN13 = new LinkedList<>(); //private String[] BooksISBN10 = {"0205021980", "1122334455"}; private LinkedList<String> BooksISBN10 = new LinkedList<>(); //private String[] BooksImages = {"book1.jpg", "Book.JPG"}; private LinkedList<String> BooksImages = new LinkedList<>(); //private String[] BooksCourse = {"Human Factors in System Design", "Course Name"}; private LinkedList<String> BooksCourse = new LinkedList<>(); public BooksService(){ // saveListToFile(); } public String getAllBooks(){ return readCurrentList(); } /* public List<HashMap<String,String>> getOneBook(Integer id){ List<HashMap<String,String>> Books = readCurrentList(); Integer size = Books.size(); arrayList = new ArrayList<HashMap<String, String>>(); for (int i = 0; i<size; i++){ if(Books.get(i).get("BookID").equals(id.toString())){ book = new HashMap<String, String>(); book.put("BookID",Books.get(i).get("BookID")); book.put("BookName",Books.get(i).get("BookName")); book.put("BookAuthors",Books.get(i).get("BookAuthors")); book.put("BookCondition",Books.get(i).get("BookCondition")); book.put("BookUniversity",Books.get(i).get("BookUniversity")); book.put("BookSchool",Books.get(i).get("BookSchool")); book.put("BookDescription",Books.get(i).get("BookDescription")); book.put("BookISBN13",Books.get(i).get("BookISBN13")); book.put("BookISBN10",Books.get(i).get("BookISBN10")); book.put("BookImages",Books.get(i).get("BookImages")); book.put("BookCourse",Books.get(i).get("BookCourse")); arrayList.add(book); } } return arrayList; } public void createBook( String bookname, String bookauthors, String bookcondition, String bookuniversity, String bookschool, String bookcourse, String bookISBN13, String bookISBN10, String bookimg, String bookdescription){ try { List<HashMap<String,String>> Books = readCurrentList(); book = new HashMap<String, String>(); Integer size=Books.size(); size = size+1; book.put("BookID", size.toString()); book.put("BookName", bookname); book.put("BookAuthors", bookauthors); book.put("BookCondition", bookcondition); book.put("BookUniversity", bookuniversity); book.put("BookSchool", bookschool); book.put("BookDescription",bookdescription); book.put("BookISBN13", bookISBN13); book.put("BookISBN10",bookISBN10); book.put("BookImages",bookimg); book.put("BookCourse", bookcourse); Books.add(book); Gson gson = new GsonBuilder().create(); String arrayListToJson = gson.toJson(Books); String filename = "Book_entries.json"; File file = new File("src\\main\\resources\\public", filename); file.delete(); BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true)); buffWriter.append(arrayListToJson); buffWriter.newLine(); buffWriter.close(); } catch (IOException e) { } } */ public Integer getNumberOfBooks(){ int size = BooksIDs.size(); return size; } public String getbooksname(){ return BooksNames.get(0); } public int saveListToFile() { Books book1 = new Books(); book1.setBookID(1); book1.setBookName("Engineering Psychology and Human Performance"); book1.setBookAuthor("Christopher D. Wickens , Justin G. Hollands, Simon Banbury, Raja Parasuraman"); book1.setBookCondition("New"); book1.setBookUniversity("University of Pittsburgh"); book1.setBookSchool("School of Information Science"); book1.setBookDescription("Forming connections between human performance and design Engineering Psychology and Human" + " Performance, 4e examines human-machine interaction. The book is organized directly from the psychological " + "perspective of human information processing. The chapters generally correspond to the flow of information as it is " + "processed by a human being--from the senses, through the brain, to action--rather than from the perspective of " + "system components or engineering design concepts. This book is ideal for a psychology student, engineering student, " + "or actual practitioner in engineering psychology, human performance, and human factors Learning Goals Upon " + "completing this book, readers should be able to: * Identify how human ability contributes to the design of " + "technology. * Understand the connections within human information processing and human performance. * Challenge the" + " way they think about technology's influence on human performance. * show how theoretical advances have been, or " + "might be, applied to improving human-machine interaction"); book1.setBookISBN13("978-0205021987"); book1.setBookISBN10("0205021980"); book1.setBookImages("book1.jpg"); book1.setBookCourse("Human Factors in System Design"); Books book2 = new Books(); book2.setBookID(2); book2.setBookName("Some Book"); book2.setBookAuthor("Many Authors"); book2.setBookCondition("Used - Very Good"); book2.setBookUniversity("CMU"); book2.setBookSchool("CS"); book2.setBookDescription("Test Description"); book2.setBookISBN13("111-2233445566"); book2.setBookISBN10("1122334455"); book2.setBookImages("Book.JPG"); book2.setBookCourse("Course Name"); List<Books> Books = Lists.newArrayList(book1, book2); Gson gson = new GsonBuilder().create(); String arrayListToJson = gson.toJson(Books); String filename = "Book_entries.json"; File file = new File("https://nameless-mountain-5787.herokuapp.com/Book_entries.json"); file.delete(); try { BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true)); buffWriter.append(arrayListToJson); buffWriter.newLine(); buffWriter.close(); } catch (IOException e) { return -1; } return 0; } public String readCurrentList() { String filename = "Book_entries.json"; File file = new File("src\\main\\resources\\public",filename); List<HashMap<String,String>> Book = null; Gson gson = new Gson(); try { BufferedReader buffReader = new BufferedReader(new FileReader(file)); String line; String jsonString= ""; while ((line = buffReader.readLine()) != null) { jsonString= jsonString+line; } buffReader.close(); //@SuppressWarnings("serial") //Type collectionType = new TypeToken<List<HashMap<String,String>>>() { //}.getType(); //Book = gson.fromJson(jsonString, collectionType); return jsonString; } catch (IOException e) { return e.toString(); } } }
package app.update; import app.util.*; import spark.*; import spark.template.freemarker.FreeMarkerEngine; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import com.heroku.sdk.jdbc.DatabaseUrl; public class UpdateController { private static final String LAS_VERSION_URL_VALUE ="https: private static final String LAST_VERSION_NUMBER_VALUE = "0.2.26"; private static final String USER_PARAM = "USER"; private static final String VERSION_PARAM = "VERSION"; private static final String MSG_PARAM = "mensaje"; private static final String LAS_VERSION_URL_PARAM = "lasVersionURL"; private static final String LAS_VERSION_NUMBER_PARAM = "lasVersionNumber"; private static final String header = "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n" + "<script>\n" + " (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n" + " (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n" + " m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n" + " })(window,document,'script','https: "\n" + " ga('create', 'UA-96140168-1', 'auto');\n" + " ga('send', 'pageview');\n" + "\n" + "</script>\n" + "<!--cript type='text/javascript'>\n" + "window.__lo_site_id = 82140;\n" + "\n" + " (function() {\n" + " var wa = document.createElement('script'); wa.type = 'text/javascript'; wa.async = true;\n" + " wa.src = 'https://d10lpsik1i8c69.cloudfront.net/w.js';\n" + " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wa, s);\n" + " })();\n" + " </script>\n" + "<script type=\"text/javascript\" src=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\">\n" + "</script public static Route handleUpdateGet = (Request request, Response response) -> { insertTick(request); //System.out.println("imprimiendo update.ftl"); response.type("application/json"); Map<String, Object> model = new HashMap<>(); model.put(LAS_VERSION_NUMBER_PARAM,LAST_VERSION_NUMBER_VALUE); model.put(LAS_VERSION_URL_PARAM, LAS_VERSION_URL_VALUE);//fuente amazon model.put(MSG_PARAM, "Ud ya tiene la ultima versi&oacute;n instalada disponible"); // return ViewUtil.render(request, model, Path.Template.UPDATE);//SEVERE: ResourceManager : unable to find resource 'update.ftl' in any resource loader. String userVersion = request.queryParams(VERSION_PARAM); if(userVersion!=null) { Double ver=versionToDouble(userVersion); //TODO controlar si la version del usuario es de 32 o 64bites if(versionToDouble(LAST_VERSION_NUMBER_VALUE).equals(ver)) { model.put(MSG_PARAM, //"<HTML>Ud esta ejecutando la ultima version disponible de UrsulaGIS"); "<HTML>" //+ "<b>Aviso:<\\/b>" + "<br>" + "<ul>" + "<li>Ud esta ejecutando la ultima version disponible de UrsulaGIS<\\/li>" + "<li>Si necesita ayuda para empezar visite <a href=\\\"www.ursulagis.com\\\"> www.ursulagis.com <\\/a> <\\/li>" + "<li>Tambien recomendamos este tutorial <a href=\\\"https://youtu.be/E76YyxKDCaQ\\\"> UrsulaGIS 0.2.27: Cmo crear un polgono <\\/a> <\\/li>" + "<\\/ul>" + "<\\/HTML>");//XXX va a webView.getEngine().loadContent(message); //Ud esta ejecutando la ultima version disponible de UrsulaGIS }else if(ver>= 0.223) { model.put(MSG_PARAM, "<HTML>" + "<b>Aviso:<\\/b>" + "<br>Ya esta disponible para descargar laversion 0.2.26 de UrsulaGIS" + " que permite abrir las imagenes ndvi en el nuevo formato<\\/b>\\t<br>visite" + " <a href=\\\"www.ursulagis.com\\\"> www.ursulagis.com <\\/a>\\tpara mas informaci&oacute;n <\\/HTML>"); // "<HTML>" // + "<b>Aviso:</b>" // + "<br>Ya esta disponible para descargar la version 0.2.26 de UrsulaGIS que permite abrir las imagenes ndvi en el nuevo formato</b>" // + " </HTML>");//XXX va a webView.getEngine().loadContent(message); } else {//antes de la 0.223 no traia el parametro de la version model.put(MSG_PARAM, "Hay una nueva versi&oacute;n disponible para actualizar "+LAST_VERSION_NUMBER_VALUE); } } FreeMarkerEngine fm= new FreeMarkerEngine(); return fm.render(new ModelAndView(model, Path.Template.UPDATE)); }; public static Double versionToDouble(String ver){ ver= ver.replace(" dev", ""); String[] v =ver.split("\\."); String ret = v[0]+"."; for(int i=1;i<v.length;i++){ ret=ret.concat(v[i]); } try{ return Double.parseDouble(ret); }catch(Exception e){ e.printStackTrace(); return -1.0; } } private static void insertTick(Request request) { Connection connection = null; try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS sessiones (tick timestamp, version varchar(255))"); String version = "unknown"; String user = "unknown"; String ip = "unknown"; try{ version = request.queryParams(VERSION_PARAM); if(version==null)version = "0.2.19?"; user = request.queryParams(USER_PARAM); if(user==null)user = "unknown"; ip = request.headers("X-FORWARDED-FOR"); if(ip==null){ // ip = request.queryParams("fwd"); //if(ip==null) ip = "unknown"; } } catch(Exception e){ System.out.println("ip unknown"); } stmt.executeUpdate("INSERT INTO sessiones VALUES (now(),'"+version+" / "+user+" @ "+ip+"')"); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } } }
package com.areen.jlib.gui; import java.awt.Component; import java.net.URL; import javax.swing.JOptionPane; /** * * @author Dejan */ public class GuiTools { private static Component parentFrame = null; /** * Use this method if you want your application to stop whenever a resource is missing. * * Example: * URL url = GuiTools.getResource(myJFrame, "/icons/help.png"); * If /icons/help.png file is missing, a dialog will appear with the alert, and application will exit. * * @param argClass * @param argResource * @return */ public static URL getResource(Class<?> argClass, String argResource) { URL url = argClass.getResource(argResource); if (url == null) { if (parentFrame != null) { parentFrame.setVisible(false); } JOptionPane.showMessageDialog(GuiTools.parentFrame, "Resource '" + argResource + "' is missing.\n" + "Application will now exit. Please contact developers and report this problem." , "Resource missing!", JOptionPane.ERROR_MESSAGE); System.exit(111); // We will exit with code 111 to notify (possibly) some other apps about // the error. } return url; } // getResource() method public static void setParentComponent(Component argComponent) { GuiTools.parentFrame = argComponent; } } // GuiTools
package com.bitso; import java.math.BigDecimal; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import com.bitso.BitsoTransactions.Transaction.SIDE; import com.bitso.helpers.Helpers; public class BitsoTransactions { public ArrayList<Transaction> list; public BitsoTransactions(JSONArray a) { list = new ArrayList<Transaction>(a.length()); for (int i = 0; i < a.length(); i++) { JSONObject o = a.getJSONObject(i); Transaction t = new Transaction(); t.date = Long.parseLong(o.getString("date")); t.tid = o.getLong("tid"); t.price = new BigDecimal(o.getString("price")); t.amount = new BigDecimal(o.getString("amount")); t.side = SIDE.valueOf(o.getString("side").toUpperCase()); list.add(t); } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Bitso Recent Transactions\n"); for (Transaction t : list) { sb.append(t); } return sb.toString(); } public static class Transaction { public enum SIDE { SELL, BUY }; long date; long tid; BigDecimal price; BigDecimal amount; SIDE side; public String toString() { return Helpers.fieldPrinter(this); } } }
package com.chipchap.model; import com.google.gson.JsonElement; /** * * the interface for exporting to JsonElement * * @author Chi Thien Phan * @version 1.0 * @since 08.03.2017 * */ public interface Exporter { /** * export to jsonelement for exporting process * * @param newKey * @return */ public JsonElement export(String newKey); }
package com.jakewharton.trakt; import com.jakewharton.trakt.services.AccountService; import com.jakewharton.trakt.services.ActivityService; import com.jakewharton.trakt.services.CalendarService; import com.jakewharton.trakt.services.CommentService; import com.jakewharton.trakt.services.GenreService; import com.jakewharton.trakt.services.ListService; import com.jakewharton.trakt.services.MovieService; import com.jakewharton.trakt.services.NetworkService; import com.jakewharton.trakt.services.RateService; import com.jakewharton.trakt.services.RecommendationsService; import com.jakewharton.trakt.services.SearchService; import com.jakewharton.trakt.services.ShowService; import com.jakewharton.trakt.services.UserService; import com.jakewharton.trakt.util.Base64; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; public class Trakt { /** * trakt API URL. */ public static final String API_URL = "https://api.trakt.tv"; /** * API key path parameter name. */ public static final String PARAM_API_KEY = "apikey"; /** * API key. */ private String mApiKey; /** * Whether to return more detailed log output. */ private boolean mIsDebug; /** * User password. */ private String mPasswordSha1; /** * User email. */ private String mUsername; /** * Currently valid instance of RestAdapter. */ private RestAdapter mRestAdapter; /** * Create a new manager instance. */ public Trakt() { } /** * POST API methods on trakt require basic setAuthentication. You must set your trakt username * and sha1 of the password. They will be sent in the HTTP header. * * @param username Username. * @param passwordSha1 SHA1 of user password. */ public Trakt setAuthentication(String username, String passwordSha1) { mUsername = username; mPasswordSha1 = passwordSha1; mRestAdapter = null; return this; } /** * Set your trakt API key. All API methods require a valid API key. * * @param key trakt API key value. */ public Trakt setApiKey(String key) { mApiKey = key; mRestAdapter = null; return this; } public Trakt setIsDebug(boolean isDebug) { mIsDebug = isDebug; mRestAdapter = null; return this; } /** * If no instance exists yet, builds a new {@link RestAdapter} using the currently set * authentication information, API key and debug flag. */ protected RestAdapter buildRestAdapter() { if (mRestAdapter == null) { RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(API_URL) .setConverter(new GsonConverter(TraktHelper.getGsonBuilder().create())); // if available, send mUsername and password in header builder.setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { requestFacade.addPathParam(PARAM_API_KEY, mApiKey); if ((mUsername != null) && (mPasswordSha1 != null)) { String source = mUsername + ":" + mPasswordSha1; String authorization = "Basic " + Base64.encodeBytes(source.getBytes()); requestFacade.addHeader("Authorization", authorization); } } }); if (mIsDebug) { builder.setLogLevel(RestAdapter.LogLevel.FULL); } mRestAdapter = builder.build(); } return mRestAdapter; } public AccountService accountService() { return buildRestAdapter().create(AccountService.class); } public ActivityService activityService() { return buildRestAdapter().create(ActivityService.class); } public CalendarService calendarService() { return buildRestAdapter().create(CalendarService.class); } public CommentService commentService() { return buildRestAdapter().create(CommentService.class); } public GenreService genreService() { return buildRestAdapter().create(GenreService.class); } public ListService listService() { return buildRestAdapter().create(ListService.class); } public MovieService movieService() { return buildRestAdapter().create(MovieService.class); } public NetworkService networkService() { return buildRestAdapter().create(NetworkService.class); } public RateService rateService() { return buildRestAdapter().create(RateService.class); } public RecommendationsService recommendationsService() { return buildRestAdapter().create(RecommendationsService.class); } public SearchService searchService() { return buildRestAdapter().create(SearchService.class); } public ShowService showService() { return buildRestAdapter().create(ShowService.class); } public UserService userService() { return buildRestAdapter().create(UserService.class); } }
package com.jcabi.github; import com.jcabi.http.Request; import com.jcabi.http.response.JsonResponse; import com.jcabi.http.response.RestResponse; import java.io.IOException; import java.net.HttpURLConnection; import javax.json.JsonObject; import javax.validation.constraints.NotNull; /** * Github statuses for a given commit. * @author Marcin Cylke (maracin.cylke+github@gmail.com) * @version $Id$ * @since 0.23 * @checkstyle MultipleStringLiteralsCheck (500 lines) */ public class RtStatuses implements Statuses { /** * RESTful request. */ private final transient Request request; /** * Commit cmmt. */ private final transient Commit cmmt; /** * Create a new status-aware object based on given commit. * @param req Http request * @param commit Specific commit */ RtStatuses(final Request req, final Commit commit) { final Coordinates coords = commit.repo().coordinates(); this.request = req.uri() .path("/repos") .path(coords.user()) .path(coords.repo()) .path("/statuses") .path(commit.sha()) .back(); this.cmmt = commit; } /** * Generate string representation. * @return String representation */ @Override @NotNull(message = "toString is never NULL") public final String toString() { return this.request.uri().get().toString(); } /** * Get commit object. * @return Commit object */ @Override @NotNull(message = "Commit can't be NULL") public final Commit commit() { return this.cmmt; } /** * Create new status for a commit. * @param status Add this status * @return Returned status * @throws IOException In case of any I/O problems */ @Override public final Status create( @NotNull(message = "status can't be NULL") final StatusCreate status ) throws IOException { final JsonObject response = this.request.method(Request.POST) .body().set(status.json()).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject(); return new RtStatus(this.cmmt, response); } /** * Get all status messages for a given commit. * @param ref It can be a SHA, a branch name, or a tag name. * @return Full list of statuses for this commit. * @todo #1126:30min Implement this method which gets all status messages for a given commit. */ @Override @NotNull(message = "iterable of statuses can't be NULL") public final Iterable<Status> list( @NotNull(message = "ref can't be NULL") final String ref ) { throw new UnsupportedOperationException("Not implemented"); } /** * JSON object for this request. * @return Json object * @throws IOException In case of I/O problems */ @Override @NotNull(message = "JSON can't be NULL") public final JsonObject json() throws IOException { return new RtJson(this.request).fetch(); } }
package com.qiniu.qbox.up; import java.io.IOException; import java.io.RandomAccessFile; import java.util.zip.CRC32; import org.apache.commons.codec.binary.Base64; import com.qiniu.qbox.Config; import com.qiniu.qbox.auth.CallRet; import com.qiniu.qbox.auth.Client; public class UpService { private Client conn; public UpService(Client conn) { this.conn = conn; } /** * @param blockSize * @param body In fact, the content of the body is the first chunk * @param bodyLength depends on the file size, if the file size >= chunk size(typically 256k) * bodyLength equals to chunk size, otherwise equals to file size . * @return */ public ResumablePutRet makeBlock(long blockSize, byte[] body, long bodyLength) { CallRet ret = this.conn.callWithBinary(Config.getUpHost() + "/mkblk/" + String.valueOf(blockSize), "application/octet-stream", body, bodyLength); return new ResumablePutRet(ret); } /** * put the chunk data into the * @param blockSize * @param ctx * @param offset * @param body * @param bodyLength * @return */ public ResumablePutRet putBlock(long blockSize, String ctx, long offset, byte[] body, long bodyLength) { CallRet ret = this.conn.callWithBinary(Config.getUpHost() + "/bput/" + ctx + "/" + String.valueOf(offset), "application/octet-stream", body, bodyLength); return new ResumablePutRet(ret); } public CallRet makeFile(String cmd, String entry, long fsize, String params, String callbackParams, String[] checksums) { if (callbackParams != null && !callbackParams.isEmpty()) { params += "/params/" + new String(Base64.encodeBase64(callbackParams.getBytes(), false, false)); } String url = Config.getUpHost() + cmd + Client.urlsafeEncodeString(entry.getBytes()) + "/fsize/" + String.valueOf(fsize) + params; byte[] body = new byte[20 * checksums.length]; for (int i = 0; i < checksums.length; i++) { byte[] buf = Base64.decodeBase64(checksums[i]); System.arraycopy(buf, 0, body, i * 20, buf.length); } CallRet ret = this.conn.callWithBinary(url, null, body, body.length); return ret; } public static int blockCount(long fsize) { return (int)((fsize + Config.getBlockSize() - 1) / Config.getBlockSize()); } /** * Put a single block. * * @param in * @param blockIndex * @param blockSize * @param chunkSize * @param retries If fails, how many times should it retry to upload? * @param progress * @param notifier */ public ResumablePutRet resumablePutBlock(RandomAccessFile file, int blockIndex, long blockSize, long chunkSize, int retryTimes, BlockProgress progress, BlockProgressNotifier notifier) { ResumablePutRet ret = null; if (progress.context == null || progress.context.isEmpty()) { // This block has never been uploaded. int bodyLength = (int)((blockSize > chunkSize) ? chunkSize : blockSize); // Smaller one. byte[] body = new byte[bodyLength]; try { file.seek(Config.getBlockSize() * blockIndex); int readBytes = file.read(body, 0, bodyLength); if (readBytes != bodyLength) { // Didn't get expected content. return new ResumablePutRet(new CallRet(400, "Read nothing")); } // make a new block and put the first chunk data ret = makeBlock((int)blockSize, body, bodyLength); if (!ret.ok()) { // statusCode == 200 return ret; // Error handling } CRC32 crc32 = new CRC32(); crc32.update(body, 0, bodyLength); if (ret.getCrc32() != crc32.getValue()) { // Something wrong! ret.statusCode = 400; return ret; } progress.context = ret.getCtx(); progress.offset = bodyLength; progress.restSize = blockSize - bodyLength; notifier.notify(blockIndex, progress); } catch (IOException e) { e.printStackTrace(); } } else if (progress.offset + progress.restSize != blockSize) { // Invalid arg. return new ResumablePutRet(new CallRet(400, "Invalid arg. File length does not match")); } while (progress.restSize > 0) { int bodyLength = (int)((chunkSize < progress.restSize) ? chunkSize : progress.restSize); byte[] body = new byte[bodyLength]; for (int retries = retryTimes; retries > 0; --retries) { try { file.seek(blockIndex * Config.getBlockSize() + progress.offset); int readBytes = file.read(body, 0, bodyLength); if (readBytes != bodyLength) { // Didn't get anything return new ResumablePutRet(new CallRet(400, "Read nothing")); } ret = putBlock(blockSize, progress.context, progress.offset, body, bodyLength); if (ret.ok()) { CRC32 crc32 = new CRC32(); crc32.update(body, 0, bodyLength); if (ret.getCrc32() == crc32.getValue()) { progress.context = ret.getCtx(); progress.offset += bodyLength; progress.restSize -= bodyLength; notifier.notify(blockIndex, progress); break; // Break to while loop. } } else if (ret.getStatusCode() == 701) { // error occurs, We should roll back to the latest block that uploaded successfully, // and put the whole block that currently failed from the first chunk again. // For convenient, we just fabricate a progress with empty context. progress.context = "" ; notifier.notify(blockIndex, progress) ; return ret ; } } catch (IOException e) { e.printStackTrace(); return new ResumablePutRet(new CallRet(400, e)); } } // end of for } // end of while if (ret == null) { ret = new ResumablePutRet(new CallRet(400, (String)null)); } return ret; } /** * This function provides the service that allows users to upload a file in a resumable way. * They don't need to worry about the accidents such as PC'power off, network failure etc... * when uploading a file. * @param file * @param fsize * @param checksums * @param progresses * @param progressNotifier * @param blockProgressNotifier * @return */ public ResumablePutRet resumablePut(RandomAccessFile file, long fsize, String[] checksums, BlockProgress[] progresses, ProgressNotifier progressNotifier, BlockProgressNotifier blockProgressNotifier) { int blockCount = blockCount(fsize); if (checksums.length != blockCount || progresses.length != blockCount) { return new ResumablePutRet(new CallRet(400, "Invalid arg. Unexpected block count.")); } for (int i = 0; i < blockCount; i++) { if (checksums[i] == null || checksums[i].isEmpty()) { int blockIndex = i; long blockSize = Config.getBlockSize(); if (blockIndex == blockCount - 1) { blockSize = fsize - Config.getBlockSize() * blockIndex; } if (progresses[i] == null) { progresses[i] = new BlockProgress(); } ResumablePutRet ret = resumablePutBlock(file, blockIndex, blockSize, Config.getPutChuncksize(), Config.getPutRetryTimes(), progresses[i], blockProgressNotifier); if (!ret.ok()) { return ret; } checksums[i] = ret.getChecksum() ; //checksums[i] = ret.getCtx() ; // notify the completion of a block progressNotifier.notify(i, checksums[i]); } } return new ResumablePutRet(new CallRet(200, (String)null)); } }
package com.sample.framework; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.safari.SafariDriver; public final class Driver { private Driver() { } private static ConcurrentHashMap<String, WebDriver> driverThreadMap = new ConcurrentHashMap<String, WebDriver>(); private static final Map<String, Class<?>> driverMap = new HashMap<String, Class<?>>() { private static final long serialVersionUID = 1L; { put("chrome", ChromeDriver.class); put("firefox", FirefoxDriver.class); put("ie", InternetExplorerDriver.class); put("safari", SafariDriver.class); put("opera", OperaDriver.class); } }; private static String getThreadName() { return Thread.currentThread().getName() + "-" + Thread.currentThread().getId(); } public static void add(String browser, Capabilities capabilities) throws Exception { Class<?> driverClass = driverMap.get(browser); WebDriver driver = (WebDriver) driverClass.getConstructor(Capabilities.class).newInstance(capabilities); String threadName = getThreadName(); driverThreadMap.put(threadName, driver); } public static WebDriver current() { String threadName = getThreadName(); return driverThreadMap.get(threadName); } }
package com.sirtrack.construct; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.ListIterator; import com.sirtrack.construct.lib.*; import com.sirtrack.construct.lib.BitStream.BitStreamReader; import com.sirtrack.construct.lib.BitStream.BitStreamWriter; import com.sirtrack.construct.lib.Containers.Container; import static com.sirtrack.construct.Macros.Field; import static com.sirtrack.construct.lib.Binary.hexStringToByteArray; import static com.sirtrack.construct.lib.Containers.*; public class Core { public static class ConstructError extends RuntimeException { public ConstructError(String string) { super(string); } public ConstructError(String string, Exception e) { super(string, e); } } public static class FieldError extends ConstructError { public FieldError(String string) { super(string); } public FieldError(String string, Exception e) { super(string, e); } } public static class SizeofError extends ConstructError { public SizeofError(String string) { super(string); } } public static class ValueError extends ConstructError { public ValueError(String string) { super(string); } } public static class RangeError extends ConstructError { public RangeError(String string) { super(string); } } public static class TypeError extends ConstructError { public TypeError(String string) { super(string); } } public static class SwitchError extends ConstructError { public SwitchError(String string) { super(string); } } public static class ArrayError extends ConstructError { public ArrayError(String string, Exception e) { super(string, e); } } // Bits = BitField // Byte = UBInt8 // Bytes = Field // Const = ConstAdapter // Tunnel = TunnelAdapter // Embed = Embedded static public byte[] ByteArray(int... ints) { byte[] ba = new byte[ints.length]; int k = 0; for (int i : ints) { ba[k++] = (byte) i; } return ba; } static public byte[] ByteArray(byte[]... bas) { ByteArrayOutputStream out = new ByteArrayOutputStream(); for (byte[] ba : bas) { try { out.write(ba); } catch (IOException e) { throw new RuntimeException(e); } } return out.toByteArray(); } /** * A generic container of attributes. * * Containers are the common way to express parsed data. */ static public <T> Container Container(Object... pairs) { return new Container(pairs); } public static byte[] _read_stream(ByteBufferWrapper stream, int length) { if (length < 0) throw new FieldError("length must be >= 0 " + length); { int len = stream.remaining(); if (len < length) throw new FieldError("expected " + length + " found " + len); byte[] out = new byte[length]; stream.get(out, 0, length); return out; } } static public abstract class Construct implements Cloneable { public static final int FLAG_COPY_CONTEXT = 0x0001; public static final int FLAG_DYNAMIC = 0x0002; public static final int FLAG_EMBED = 0x0004; public static final int FLAG_NESTING = 0x0008; public int conflags; public String name; protected Object val; public Construct() { this(null, 0); // must set name later } public Construct(String name) { this(name, 0); } public Construct(String name, int flags) { setName(name); this.conflags = flags; } public void setName(String name){ if (name != null) { if (name.equals("_") || name.startsWith("<")) throw new ValueError("reserved name " + name); // raise } this.name = name; } public Construct clone() throws CloneNotSupportedException { return (Construct) super.clone(); } @Override public String toString() { if( get() != null) return get().toString(); else return getClass().getName() + "(" + name + ")"; } public Object get() { return val; } public void set(Object val) { this.val = val; } /** * Set the given flag or flags. * * @param flag * flag to set; may be OR'd combination of flags */ void _set_flag(int flag) { conflags |= flag; } /** * Clear the given flag or flags. * * @param flag * flag to clear; may be OR'd combination of flags */ public void _clear_flag(int flag) { conflags &= ~flag; } /** Pull flags from subconstructs. */ public void _inherit_flags(Construct... subcons) { for (Construct sc : subcons) { _set_flag(sc.conflags); } } /** * Check whether a given flag is set. * * @param flag * flag to check * @return */ boolean _is_flag(int flag) { return (conflags & flag) == flag; } static public int getDataLength(Object data) { if (data instanceof String) return ((String) data).length(); else if (data instanceof Byte || data instanceof Character) return 1; else if (data instanceof Integer) { int num = (Integer) data; if (num < 256) return 1; else if (num < 65536) return 2; else return 4; // return Integer.SIZE/8; } else if (data instanceof byte[]) return ((byte[]) data).length; else if (data instanceof List) return ((List) data).size(); else throw new RuntimeException("Data length unknown for " + data); } static public void appendDataStream(ByteArrayOutputStream stream, Object data) { if (data instanceof String) try { stream.write(((String) data).getBytes()); } catch (IOException e) { throw new ValueError("Can't append data " + data + " " + e.getMessage()); } else if (data instanceof Byte) stream.write((Byte) data); else if (data instanceof Integer) stream.write((Integer) data); else if (data instanceof byte[]) try { stream.write((byte[]) data); } catch (IOException e) { throw new ValueError("Can't append data " + data + " " + e.getMessage()); } else throw new ValueError("Can't append data " + data); } public void _write_stream(ByteArrayOutputStream stream, int length, Object data) { if (length < 0) throw new FieldError("length must be >= 0 " + length); int datalength = getDataLength(data); if (length != datalength) throw new FieldError("expected " + length + " found " + datalength); appendDataStream(stream, data); }; /** * Parse an in-memory buffer. * * Strings, buffers, memoryviews, and other complete buffers can be parsed * with this method. * * @param data */ public <T> T parse(byte[] data) { return (T) parse_stream(new ByteBufferWrapper().wrap(data)); } /** * @param hex * a string representation of hex bytes: 65535 = "FFFF" * @return */ public <T> T parse(String hex) { byte[] data = hexStringToByteArray(hex); return (T) parse(data); } /** * Parse an in-memory buffer. Also accepts a context, useful for passing * initial values * * @param data * @param context * @return */ public <T> T parse(byte[] data, Container context) { return (T) _parse(new ByteBufferWrapper().wrap(data), context); } public <T> T parse(String hex, Container context) { byte[] data = hexStringToByteArray(hex); return (T) _parse(new ByteBufferWrapper().wrap(data), context); } /** * Parse a stream. * * Files, pipes, sockets, and other streaming sources of data are handled by * this method. */ public Object parse_stream(ByteBufferWrapper stream) { return _parse(stream, new Container()); } abstract public Object _parse(ByteBufferWrapper stream, Container context); /** * Build an object in memory. * * @param obj * @return */ public byte[] build(Object obj) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); build_stream(obj, stream); return stream.toByteArray(); } /** * Build an object directly into a stream. * * @param obj * @param stream */ public void build_stream(Object obj, ByteArrayOutputStream stream) { _build(obj, stream, new Container()); } // abstract public void _build( String obj, OutputStream stream, Container // context); public abstract void _build(Object obj, ByteArrayOutputStream stream, Container context); /** * Calculate the size of this object, optionally using a context. Some * constructs have no fixed size and can only know their size for a given * hunk of data; these constructs will raise an error if they are not passed * a context. * * @param context * contextual data * @return the length of this construct */ public int sizeof(Container context) { if (context == null) { context = new Container(); } try { return _sizeof(context); } catch (Exception e) { throw new SizeofError(e.getMessage()); } } public int sizeof() { return sizeof(null); } public abstract int _sizeof(Container context); } /** * Abstract subconstruct (wraps an inner construct, inheriting its name and * flags). */ public static abstract class Subconstruct<T extends Construct> extends Construct { protected T subcon; /** * @param subcon * the construct to wrap */ public Subconstruct(T subcon) { super(subcon.name, subcon.conflags); this.subcon = subcon; } Subconstruct(String name, T subcon) { super(name, subcon.conflags); this.subcon = subcon; } public Subconstruct<T> clone() throws CloneNotSupportedException { Subconstruct<T> s = (Subconstruct<T>) super.clone(); s.subcon = (T)subcon.clone(); return s; } // @Override // public T get(){ // return subcon; @Override public Object _parse(ByteBufferWrapper stream, Container context) { return subcon._parse(stream, context); } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { subcon._build(obj, stream, context); } @Override public int _sizeof(Container context) { return subcon._sizeof(context); } } /** * A fixed-size byte field. */ public static class StaticField extends Construct { int length; /** * @param name * field name * @param length * number of bytes in the field */ public StaticField(String name, int length) { super(name); this.length = length; } @Override public Object _parse(ByteBufferWrapper stream, Container context) { return _read_stream(stream, length); } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { _write_stream(stream, length, obj); } @Override public int _sizeof(Container context) { return length; } /* * public int _sizeof( Container context ){ @Override public Construct clone() { // TODO Auto-generated method stub return null; } return length; } */ } /** * A field that uses ``struct`` to pack and unpack data. * * See ``struct`` documentation for instructions on crafting format strings. */ public static class FormatField<T extends Number> extends StaticField { int length; Packer<T> packer; /** * @param name * name of the field * @param endianness * : format endianness string; one of "<", ">", or "=" * @param format * : a single format character */ public FormatField(String name, char endianity, char format) { super(name, 0); if (endianity != '>' && endianity != '<' && endianity != '=') throw new ValueError("endianity must be be '=', '<', or '>' " + endianity); packer = new Packer<T>(endianity, format); super.length = packer.length(); } @Override public T _parse(ByteBufferWrapper stream, Container context) { try { return packer.unpack(stream.bb); } catch (Exception e) { throw new FieldError(e.getMessage(), e); } } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { _write_stream(stream, super.length, packer.pack(obj)); } @Override public T get() { return (T)val; } } /** * callable that takes a context and returns length as an int */ static public interface LengthFunc { abstract int length(Container context); } /** * @param name * context field name * @return get length from context field */ static public LengthFunc LengthField(final String name) { return new LengthFunc() { public int length(Container ctx) { return (Integer) ctx.get(name); } }; } /** * A variable-length field. The length is obtained at runtime from a function. * >>> foo = Struct("foo", ... Byte("length"), ... MetaField("data", lambda * ctx: ctx["length"]) ... ) >>> foo.parse("\\x03ABC") Container(data = 'ABC', * length = 3) >>> foo.parse("\\x04ABCD") Container(data = 'ABCD', length = 4) * * @param name * name of the field * @param lengthfunc * callable that takes a context and returns length as an int */ public static MetaField MetaField(String name, LengthFunc lengthfunc) { return new MetaField(name, lengthfunc); } public static class MetaField extends Construct { LengthFunc lengthfunc; /** * @param name * name of the field * @param lengthfunc * callable that takes a context and returns length as an int */ public MetaField(String name, LengthFunc lengthfunc) { super(name); this.lengthfunc = lengthfunc; this._set_flag(FLAG_DYNAMIC); } @Override public Object _parse(ByteBufferWrapper stream, Container context) { return _read_stream(stream, lengthfunc.length(context)); } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { _write_stream(stream, lengthfunc.length(context), obj); } @Override public int _sizeof(Container context) { return lengthfunc.length(context); } } /** * callable that takes a context and returns length as an int */ static public interface CountFunc { abstract int count(Container context); } /** * Example: MetaArray(lambda ctx: 5, UBInt8("foo")) See also Array, Range and * RepeatUntil. * * @param countfunc * a function that takes the context as a parameter and returns the * number of elements of the array (count) * @param subcon * the subcon to repeat `countfunc()` times * @return An array (repeater) of a meta-count. The array will iterate exactly * `countfunc()` times. Will raise ArrayError if less elements are * found. */ public static MetaArray MetaArray(CountFunc countfunc, Construct subcon) { return new MetaArray(countfunc, subcon); } /** * An array (repeater) of a meta-count. The array will iterate exactly * `countfunc()` times. Will raise ArrayError if less elements are found. See * also Array, Range and RepeatUntil. * * Example: MetaArray(lambda ctx: 5, UBInt8("foo")) */ public static class MetaArray extends Subconstruct { CountFunc countfunc; /** * Parameters: countfunc - a function that takes the context as a parameter * and returns the number of elements of the array (count) subcon - the * subcon to repeat `countfunc()` times * * @param length * @param name * @param subcon */ MetaArray(CountFunc countfunc, Construct subcon) { super(subcon); this.countfunc = countfunc; _clear_flag(FLAG_COPY_CONTEXT); _set_flag(FLAG_DYNAMIC); } @Override public Object _parse(ByteBufferWrapper stream, Container context) { List obj = ListContainer(); int c = 0; int count = countfunc.count(context); try { if ((subcon.conflags & FLAG_COPY_CONTEXT) != 0) { while (c < count) { obj.add(subcon._parse(stream, context.clone())); c += 1; } } else { while (c < count) { obj.add(subcon._parse(stream, context)); c += 1; } } } catch (Exception e) { throw new ArrayError("expected " + count + ", found " + c, e); } return obj; } @Override public void _build(Object object, ByteArrayOutputStream stream, Container context) { List<Object> obj = (List<Object>) object; int count = countfunc.count(context); if (obj.size() != count) { throw new ArrayError("expected " + count + ", found " + obj.size(), null); } if ((subcon.conflags & FLAG_COPY_CONTEXT) != 0) { for (Object subobj : obj) { subcon._build(subobj, stream, context.clone()); } } else { for (Object subobj : obj) { subcon._build(subobj, stream, context); } } } @Override public int _sizeof(Container context) { return subcon._sizeof(context) * countfunc.count(context); } } public static <T extends Construct>Range Range(int mincount, int maxcount, T subcon) { return new Range<T>(mincount, maxcount, subcon); } /** * A range-array. The subcon will iterate between `mincount` to `maxcount` * times. If less than `mincount` elements are found, raises RangeError. See * also GreedyRange and OptionalGreedyRange. * * The general-case repeater. Repeats the given unit for at least mincount * times, and up to maxcount times. If an exception occurs (EOF, validation * error), the repeater exits. If less than mincount units have been * successfully parsed, a RangeError is raised. * * .. note:: This object requires a seekable stream for parsing. */ public static class Range<T extends Construct> extends Subconstruct<T> { /** * @param mincount * the minimal count * @param maxcount * the maximal count * @param subcon * the subcon to repeat >>> c = Range(3, 7, UBInt8("foo")) >>> * c.parse("\\x01\\x02") Traceback (most recent call last): ... * construct.core.RangeError: expected 3..7, found 2 >>> * c.parse("\\x01\\x02\\x03") [1, 2, 3] >>> * c.parse("\\x01\\x02\\x03\\x04\\x05\\x06") [1, 2, 3, 4, 5, 6] >>> * c.parse("\\x01\\x02\\x03\\x04\\x05\\x06\\x07") [1, 2, 3, 4, 5, * 6, 7] >>> * c.parse("\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09") [1, 2, * 3, 4, 5, 6, 7] >>> c.build([1,2]) Traceback (most recent call * last): ... construct.core.RangeError: expected 3..7, found 2 >>> * c.build([1,2,3,4]) '\\x01\\x02\\x03\\x04' >>> * c.build([1,2,3,4,5,6,7,8]) Traceback (most recent call last): * ... construct.core.RangeError: expected 3..7, found 8 */ int mincount; int maxcout; public Range(int mincount, int maxcount, T subcon) { super(subcon); this.mincount = mincount; this.maxcout = maxcount; _clear_flag(FLAG_COPY_CONTEXT); _set_flag(FLAG_DYNAMIC); } @Override public List<T> get(){ return (List<T>)val; } @Override public void set( Object val ){ } @Override public Object _parse(ByteBufferWrapper stream, Container context) { // obj = ListContainer() List<Object> obj = ListContainer(); val = ListContainer(); int c = 0; int pos = stream.position(); try { if ((subcon.conflags & FLAG_COPY_CONTEXT) != 0) { while (c < maxcout) { T clone = (T) subcon.clone(); pos = stream.position(); get().add( clone ); obj.add(clone._parse(stream, context.clone())); c += 1; } } else { while (c < maxcout) { T clone = (T) subcon.clone(); pos = stream.position(); get().add(clone); obj.add(clone._parse(stream, context)); c += 1; } } } catch (Exception e) { if (c < mincount) { throw new RangeError("expected " + mincount + " to " + maxcout + " found " + c + " " + e.getMessage()); } stream.position(pos); } return obj; } @Override public void _build(Object object, ByteArrayOutputStream stream, Container context) { if (!(object instanceof List)) throw new TypeError("Expected object array"); List<Object> obj = (List<Object>) object; if (obj.size() < mincount || obj.size() > maxcout) { throw new RangeError("expected " + mincount + " to " + maxcout + " found " + obj.size()); } int cnt = 0; try { if ((subcon.conflags & FLAG_COPY_CONTEXT) != 0) { for (Object subobj : obj) { subcon._build(subobj, stream, context.clone()); cnt += 1; } } else { for (Object subobj : obj) { subcon._build(subobj, stream, context); cnt += 1; } } } catch (Exception e) { throw new RangeError(e.getMessage()); } } @Override public int _sizeof(Container context) { throw new SizeofError("can't calculate size"); } } /** * A sequence of named constructs, similar to structs in C. The elements are * parsed and built in the order they are defined. See also Embedded. Example: * Struct("foo", UBInt8("first_element"), UBInt16("second_element"), * Padding(2), UBInt8("third_element"), ) */ static public Struct Struct(String name, Construct... subcons) { return new Struct(name, subcons); } static public Struct Struct(Construct... subcons) { return new Struct(null, subcons); } static public class Struct extends Construct { public boolean nested = true; public Construct[] subcons; /** * @param name * the name of the structure * @param subcons * a sequence of subconstructs that make up this structure. */ public Struct(String name, Construct... subcons) { super(name); this.subcons = subcons; _inherit_flags(subcons); _clear_flag(FLAG_EMBED); } @Override public Struct clone() throws CloneNotSupportedException { Struct clone = (Struct) super.clone(); clone.subcons = new Construct[subcons.length]; Field[] fields = getClass().getDeclaredFields(); int i = 0; for( Field f : fields ){ if (Construct.class.isAssignableFrom(f.getType())) try{ f.setAccessible(true); // clone field Construct fclone = ((Construct)f.get(this)).clone(); // set the field clone into the Struct clone f.set(clone, fclone); // also add the field clone to the subcons array clone.subcons[i++] = fclone; } catch( Exception e ){ throw new RuntimeException(e); } // Clone elements in the subcons array // Because we cater for both static and runtime Struct definitions, // we need to make sure subcons don't end up twice in the subcons array // This case has to handle only the runtime (old) definition // So if we already have stuff in the subcons array, carry on else if ( /*f.getType() == Construct[].class &&*/ f.getName().equals("subcons") && clone.subcons[0] == null ) try{ i = 0; for( Construct c : subcons ){ clone.subcons[i++] = c.clone(); } } catch( Exception e ){ throw new RuntimeException(e); } else continue; } return clone; } /** * This is a special constructor for typesafe Structs. * Instead of passing an array of Subcons at runtime, * this constructor inspects the public fields of type Construct for this Struct * and invokes each field's constructor by passing the field name. * It's assumed that all declared fields have a public constructor: Construct( String name ) * @param name */ public Struct(String name) { super(name); Constructor fctor; Field field = null; String fname; try { Field[] fields = getClass().getFields(); List<Construct> subconf = new ArrayList<Construct>(); for( int i = 0; i < fields.length; i++ ) { field = fields[i]; field.setAccessible(true); Class clazz = field.getType(); if (!Construct.class.isAssignableFrom(clazz)) continue; fname = field.getName(); fctor = clazz.getConstructors()[0]; fctor.setAccessible(true); Construct inst; Object enclosingInst; switch (fctor.getParameterTypes().length) { // TODO should check that the first instance is of the right type: enclosing type or String case 2: // inner classes try{ // static class case enclosingInst = getClass().getDeclaredField("this$0").get(this); } catch( NoSuchFieldException nsfe ){ // private nested class case enclosingInst = this; } inst = (Construct) fctor.newInstance(enclosingInst, fname); break; case 1: if( String.class.isAssignableFrom( fctor.getParameterTypes()[0] )){ inst = (Construct) fctor.newInstance(fname); } else { // no arguments constructor try{ // static class case enclosingInst = getClass().getDeclaredField("this$0").get(this); } catch( NoSuchFieldException nsfe ){ // private nested class case enclosingInst = this; } inst = (Construct) fctor.newInstance(enclosingInst); // now call name setter with fname inst.setName(fname); } break; case 0: inst = (Construct) fctor.newInstance(); break; default: throw new Exception("No default case: " + fctor); } field.set(this, inst); subconf.add(inst); } subcons = new Construct[subconf.size()]; subcons = subconf.toArray(subcons); _inherit_flags(subcons); _clear_flag(FLAG_EMBED); } catch (Exception e) { throw new RuntimeException("Error constructing field " + field + "\r\n" + e.toString(), e); } } public Struct() { this((String) null); } @Override public Object _parse(ByteBufferWrapper stream, Container context) { Container obj; if (context.contains("<obj>")) { obj = context.get("<obj>"); context.del("<obj>"); } else { obj = new Container(); if (nested) { context = Container("_", context); } } for (Construct sc : subcons) { if ((sc.conflags & FLAG_EMBED) != 0) { context.set("<obj>", obj); Object val = sc._parse(stream, context); sc.set( val ); } else { Object val = sc._parse(stream, context); sc.set( val ); if (sc.name != null) { obj.set(sc.name, val); context.set(sc.name, val); } } } return obj; } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { if (context.contains("<unnested>")) { context.del("<unnested>"); } else if (nested) { context = Container("_", context); } for (Construct sc : subcons) { Object subobj; if ((sc.conflags & FLAG_EMBED) != 0) { context.set("<unnested>", true); subobj = obj; } else if (sc.name == null) { subobj = null; } else if (obj instanceof Container) { Container container = (Container) obj; subobj = container.get(sc.name); if (subobj == null) throw new FieldError("No field found: " + sc.name + " in " + subobj); context.set(sc.name, subobj); } else continue; sc._build(subobj, stream, context); } } @Override public int _sizeof(Container context) { int sum = 0; // if( nested ) // context = Container( "_", context ); for (Construct sc : subcons) { sum += sc._sizeof(context); } return sum; } } /** * @param name * the name of the structure * @param subcons * a sequence of subconstructs that make up this structure. * @param nested * : a keyword-only argument that indicates whether this struct * creates a nested context. The default is True. This parameter is * considered "advanced usage", and may be removed in the future. * @return A sequence of unnamed constructs. The elements are parsed and built * in the order they are defined. See also Embedded. Example: * Sequence("foo", UBInt8("first_element"), UBInt16("second_element"), * Padding(2), UBInt8("third_element"), ) */ public static Sequence Sequence(String name, Construct... subcons) { return new Sequence(name, subcons); } public static class Sequence extends Struct { public Sequence(String name, Construct... subcons) { super(name, subcons); } @Override public Object _parse(ByteBufferWrapper stream, Container context) { List obj; if (context.contains("<obj>")) { obj = context.get("<obj>"); context.del("<obj>"); } else { obj = ListContainer(); if (nested) { context = Container("_", context); } } for (Construct sc : subcons) { if ((sc.conflags & FLAG_EMBED) != 0) { context.set("<obj>", obj); sc._parse(stream, context); } else { Object subobj = sc._parse(stream, context); if (sc.name != null) { obj.add(subobj); context.set(sc.name, subobj); } } } return obj; } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { if (context.contains("<unnested>")) { context.del("<unnested>"); } else if (nested) { context = Container("_", context); } Object subobj; ListIterator objiter; if (obj instanceof List) objiter = ((List) obj).listIterator(); else objiter = (ListIterator) obj; for (Construct sc : subcons) { if ((sc.conflags & FLAG_EMBED) != 0) { context.set("<unnested>", true); subobj = objiter; } else if (sc.name == null) { subobj = null; } else { subobj = objiter.next(); context.set(sc.name, subobj); } sc._build(subobj, stream, context); } } } public static Construct NoDefault = new Construct(null) { @Override public Object _parse(ByteBufferWrapper stream, Container context) { throw new SwitchError("no default case defined"); } @Override public void _build(Object obj, ByteArrayOutputStream stream, com.sirtrack.construct.lib.Containers.Container context) { throw new SwitchError("no default case defined"); } @Override public int _sizeof(com.sirtrack.construct.lib.Containers.Container context) { throw new SwitchError("no default case defined"); } }; /** * a function that takes the context and returns a key */ public abstract static class KeyFunc { public final String key; public KeyFunc(String key) { this.key = key; } public KeyFunc() { this.key = null; } public String key() { return key; } public abstract Object get(Container context); } /** * @param key * a context key * @param val * a value * @return A KeyFunc that evaluates ctx.get(key).equals(val) */ public static KeyFunc Equals(final String key, final Object val) { return new KeyFunc(key) { public Object get(Container ctx) { return ctx.get(key).equals(val); }; }; } /** * @param key * a context key * @return ctx.get(key) */ public static KeyFunc KeyVal(final String key) { return new KeyFunc(key) { public Object get(Container ctx) { return ctx.get(key); }; }; } /** * A conditional branch. Switch will choose the case to follow based on the * return value of keyfunc. If no case is matched, and no default value is * given, SwitchError will be raised. See also Pass. Example: Struct("foo", * UBInt8("type"), Switch("value", lambda ctx: ctx.type, { 1 : UBInt8("spam"), * 2 : UBInt16("spam"), 3 : UBInt32("spam"), 4 : UBInt64("spam"), } ), ) * * @param name * the name of the construct * @param keyfunc * a function that takes the context and returns a key, which will ne * used to choose the relevant case. * @param cases * a dictionary mapping keys to constructs. the keys can be any * values that may be returned by keyfunc. */ public static Switch Switch(String name, KeyFunc keyfunc, Object... cases) { return new Switch(name, keyfunc, Container(cases)); } /** * A conditional branch. Switch will choose the case to follow based on the * return value of keyfunc. If no case is matched, and no default value is * given, SwitchError will be raised. See also Pass. Example: Struct("foo", * UBInt8("type"), Switch("value", lambda ctx: ctx.type, { 1 : UBInt8("spam"), * 2 : UBInt16("spam"), 3 : UBInt32("spam"), 4 : UBInt64("spam"), } ), ) * * @param name * the name of the construct * @param keyfunc * a function that takes the context and returns a key, which will ne * used to choose the relevant case. * @param cases * a dictionary mapping keys to constructs. the keys can be any * values that may be returned by keyfunc. * @param defaultval * a default value to use when the key is not found in the cases. if * not supplied, an exception will be raised when the key is not * found. You can use the builtin construct Pass for 'do-nothing'. * @param include_key * whether or not to include the key in the return value of parsing. * defualt is False. */ public static Switch Switch(String name, KeyFunc keyfunc, Container cases, Construct defaultval, boolean include_key) { return new Switch(name, keyfunc, cases, defaultval, include_key); } /** * A conditional branch. Switch will choose the case to follow based on the * return value of keyfunc. If no case is matched, and no default value is * given, SwitchError will be raised. See also Pass. Example: Struct("foo", * UBInt8("type"), Switch("value", lambda ctx: ctx.type, { 1 : UBInt8("spam"), * 2 : UBInt16("spam"), 3 : UBInt32("spam"), 4 : UBInt64("spam"), } ), ) */ public static class Switch extends Construct { /** * a function that takes the context and returns a key, which will ne used * to choose the relevant case. */ public KeyFunc keyfunc; public Container cases; public Construct defaultval; public boolean include_key; /** * @param name * the name of the construct * @param keyfunc * a function that takes the context and returns a key, which will * ne used to choose the relevant case. * @param cases * a dictionary mapping keys to constructs. the keys can be any * values that may be returned by keyfunc. * @param defaultval * a default value to use when the key is not found in the cases. * if not supplied, an exception will be raised when the key is not * found. You can use the builtin construct Pass for 'do-nothing'. * @param include_key * whether or not to include the key in the return value of * parsing. defualt is False. */ public Switch(String name, KeyFunc keyfunc, Container cases, Construct defaultval, boolean include_key) { super(name); this.keyfunc = keyfunc; this.cases = cases; this.defaultval = defaultval; this.include_key = include_key; Construct[] ca = cases.values(Construct.class); this._inherit_flags(ca); this._set_flag(FLAG_DYNAMIC); } public Switch(String name, KeyFunc keyfunc, Container cases) { this(name, keyfunc, cases, NoDefault, false); } @Override public Object get() { return val; } @Override public void set(Object val) { // do nothing: prevent Structs from setting val to the parsed value // keep the Switch case construct as a value //this.val = val; } @Override public Switch clone() throws CloneNotSupportedException { Switch c = (Switch) super.clone(); c.cases = cases.clone(); // TODO check deep copy c.defaultval = defaultval.clone(); return c; } @Override public Object _parse(ByteBufferWrapper stream, Container context) { Object key = keyfunc.get(context); /* assign the case Construct as a value for Switch * users can then retrieve the case Construct with get()*/ val = cases.get(key, defaultval); Object res = ((Construct)val)._parse(stream, context); if (include_key) res = Container(key, res); return res; } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { Object key; if (include_key) { List list = (List) obj; key = list.get(0); obj = list.get(1); } else { key = keyfunc.get(context); } Construct casestruct = cases.get(key, defaultval); casestruct._build(obj, stream, context); /* * if self.include_key: key, obj = obj else: key = self.keyfunc(context) * case = self.cases.get(key, self.default) case._build(obj, stream, * context) */ } @Override public int _sizeof(Container context) { Construct casestruct = cases.get(keyfunc.get(context), defaultval); return casestruct._sizeof(context); } } /** * Creates an in-memory buffered stream, which can undergo encoding and * decoding prior to being passed on to the subconstruct. See also Bitwise. * * Note: Do not use pointers inside Buffered * * Example: Buffered(BitField("foo", 16), encoder = decode_bin, decoder = * encode_bin, resizer = lambda size: size / 8, ) */ static public class Buffered<T extends Construct> extends Subconstruct<T> { public Encoder encoder; public Decoder decoder; public Resizer resizer; /** * Creates an in-memory buffered stream, which can undergo encoding and * decoding prior to being passed on to the subconstruct. See also Bitwise.<br/> * <br/> * Note: Do not use pointers inside Buffered * * @param subcon * the subcon which will operate on the buffer * @param encoder * a function that takes a string and returns an encoded string * (used after building) * @param decoder * a function that takes a string and returns a decoded string * (used before parsing) * @param resizer * a function that takes the size of the subcon and "adjusts" or * "resizes" it according to the encoding/decoding process. */ public Buffered(T subcon, Encoder encoder, Decoder decoder, Resizer resizer) { super(subcon); this.encoder = encoder; this.decoder = decoder; this.resizer = resizer; } // @Override // public T get(){ // return subcon; // @Override // public void set( Object val ){ // subcon.set(val); @Override public Object _parse(ByteBufferWrapper stream, Container context) { byte[] data = _read_stream(stream, _sizeof(context)); byte[] stream2 = decoder.decode(data); return subcon._parse(new ByteBufferWrapper().wrap(stream2), context); } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { int size = _sizeof(context); ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); subcon._build(obj, stream2, context); byte[] data = encoder.encode(stream2.toString()); if (data.length != size) throw new RuntimeException("Wrong data length: " + data.length); _write_stream(stream, size, data); } @Override public int _sizeof(Container context) { return resizer.resize( subcon._sizeof(context)); } } /** * Wraps the stream with a read-wrapper (for parsing) or a write-wrapper (for * building). The stream wrapper can buffer the data internally, reading it * from- or writing it to the underlying stream as needed. For example, * BitByteBufferWrapper reads whole bytes from the underlying stream, but * returns them as individual bits. See also Bitwise. * * When the parsing or building is done, the stream's close method will be * invoked. It can perform any finalization needed for the stream wrapper, but * it must not close the underlying stream. * * Note: Do not use pointers inside Restream * * Example: Restream(BitField("foo", 16), stream_reader = * BitByteBufferWrapper, stream_writer = BitStreamWriter, resizer = lambda * size: size / 8, ) */ public static class Restream extends Subconstruct { BitStreamReader stream_reader; BitStreamWriter stream_writer; Resizer resizer; /** * Wraps the stream with a read-wrapper (for parsing) or a write-wrapper * (for building). The stream wrapper can buffer the data internally, * reading it from- or writing it to the underlying stream as needed. For * example, BitByteBufferWrapper reads whole bytes from the underlying * stream, but returns them as individual bits. See also Bitwise.<br/> * <br/> * When the parsing or building is done, the stream's close method will be * invoked. It can perform any finalization needed for the stream wrapper, * but it must not close the underlying stream.<br/> * <br/> * Note: Do not use pointers inside Restream * * @param subcon * the subcon * @param stream_reader * the read-wrapper * @param stream_writer * the write wrapper * @param resizer * a function that takes the size of the subcon and "adjusts" or * "resizes" it according to the encoding/decoding process. */ public Restream(Construct subcon, BitStreamReader stream_reader, BitStreamWriter stream_writer, Resizer resizer) { super(subcon); this.stream_reader = stream_reader; this.stream_writer = stream_writer; this.resizer = resizer; } @Override public Object _parse(ByteBufferWrapper stream, Container context) { stream_reader.init(stream); Object obj = subcon._parse(stream_reader, context); stream_reader.close(); return obj; } @Override public void _build(Object obj, ByteArrayOutputStream stream, Container context) { ByteArrayOutputStream stream2 = stream_writer.init(stream); subcon._build(obj, stream2, context); stream_writer.close(); } @Override public int _sizeof(Container context) { return resizer.resize(subcon._sizeof(context)); } } * class Pointer(Subconstruct): """ Changes the stream position to a given * offset, where the construction should take place, and restores the stream * position when finished. See also Anchor, OnDemand and OnDemandPointer. * * Notes: requires a seekable stream. * * Parameters: offsetfunc: a function that takes the context and returns an * absolute stream position, where the construction would take place subcon - * the subcon to use at `offsetfunc()` * * Example: Struct("foo", UBInt32("spam_pointer"), Pointer(lambda ctx: * ctx.spam_pointer, Array(5, UBInt8("spam")) ) ) """ __slots__ = * class Peek(Subconstruct): """ Peeks at the stream: parses without changing * the stream position. See also Union. If the end of the stream is reached * when peeking, returns None. * * Notes: requires a seekable stream. * * Parameters: subcon - the subcon to peek at perform_build - whether or not * to perform building. by default this parameter is set to False, meaning * building is a no-op. * * Example: Peek(UBInt8("foo")) """ __slots__ = ["perform_build"] def * class OnDemand(Subconstruct): """ Allows for on-demand (lazy) parsing. When * parsing, it will return a LazyContainer that represents a pointer to the * data, but does not actually parses it from stream until it's "demanded". By * accessing the 'value' property of LazyContainers, you will demand the data * from the stream. The data will be parsed and cached for later use. You can * use the 'has_value' property to know whether the data has already been * demanded. See also OnDemandPointer. * * Notes: requires a seekable stream. * * Parameters: subcon - advance_stream - whether or not to advance the stream * position. by default this is True, but if subcon is a pointer, this should * be False. force_build - whether or not to force build. If set to False, and * the LazyContainer has not been demaned, building is a no-op. * * Example: OnDemand(Array(10000, UBInt8("foo")) """ __slots__ = /* * ["offsetfunc"] def __init__(self, offsetfunc, subcon): * Subconstruct.__init__(self, subcon) self.offsetfunc = offsetfunc def * _parse(self, stream, context): newpos = self.offsetfunc(context) origpos = * stream.tell() stream.seek(newpos) obj = self.subcon._parse(stream, context) * stream.seek(origpos) return obj def _build(self, obj, stream, context): * newpos = self.offsetfunc(context) origpos = stream.tell() * stream.seek(newpos) self.subcon._build(obj, stream, context) * stream.seek(origpos) def _sizeof(self, context): return 0 * * __init__(self, subcon, perform_build = False): Subconstruct.__init__(self, * subcon) self.perform_build = perform_build def _parse(self, stream, * context): pos = stream.tell() try: return self.subcon._parse(stream, * context) except FieldError: pass finally: stream.seek(pos) def _build(self, * obj, stream, context): if self.perform_build: self.subcon._build(obj, * stream, context) def _sizeof(self, context): return 0 * * ["advance_stream", "force_build"] def __init__(self, subcon, advance_stream * = True, force_build = True): Subconstruct.__init__(self, subcon) * self.advance_stream = advance_stream self.force_build = force_build def * _parse(self, stream, context): obj = LazyContainer(self.subcon, stream, * stream.tell(), context) if self.advance_stream: * stream.seek(self.subcon._sizeof(context), 1) return obj def _build(self, * obj, stream, context): if not isinstance(obj, LazyContainer): * self.subcon._build(obj, stream, context) elif self.force_build or * obj.has_value: self.subcon._build(obj.value, stream, context) elif * self.advance_stream: stream.seek(self.subcon._sizeof(context), 1) */ /** * @param name * the new name * @param subcon * the subcon to reconfigure * @param setflags * the flags to set (default is 0) * @param clearflags * the flags to clear (default is 0) */ static public Reconfig Reconfig(String name, Construct subcon) { return new Reconfig(name, subcon); } /** * @param name * the new name * @param subcon * the subcon to reconfigure * @param setflags * the flags to set (default is 0) * @param clearflags * the flags to clear (default is 0) */ static public Reconfig Reconfig(String name, Construct subcon, int setflags, int clearflags) { return new Reconfig(name, subcon, setflags, clearflags); } /** * Reconfigures a subconstruct. Reconfig can be used to change the name and * set and clear flags of the inner subcon. Example: Reconfig("foo", * UBInt8("bar")) */ static public class Reconfig<T extends Construct> extends Subconstruct<T> { /** * @param name * the new name * @param subcon * the subcon to reconfigure * @param setflags * the flags to set (default is 0) * @param clearflags * the flags to clear (default is 0) */ public Reconfig(String name, T subcon, int setflags, int clearflags) { super(name, subcon); _set_flag(setflags); _clear_flag(clearflags); } public Reconfig(String name, T subcon) { this(name, subcon, 0, 0); } @Override public T get(){ return subcon; } // @Override // public void set( Object val ){ // subcon.set(val); } /** * a function that takes the context and return the computed value */ public static interface ValueFunc<T> { T get(Container ctx); } /** * A computed value. Example: Struct("foo", UBInt8("width"), UBInt8("height"), * Value("total_pixels", lambda ctx: ctx.width * ctx.height), ) * * @param name * the name of the value * @param func * a function that takes the context and return the computed value */ public static <T>Value Value(String name, ValueFunc<T> func) { return new Value<T>(name, func); }; public static class Value<T> extends Construct implements ValueFunc<T> { public ValueFunc<T> func; /** * Us this consstructor if a class extends Value and implements ValueFunc, * in its own constructor it needs to set super.func = this * * @param name */ public Value() { super(); this.func = this; _set_flag(FLAG_DYNAMIC); } /** * @param name * @param func overrides unimplemented ValueFunc<T> at runtime */ public Value(String name, ValueFunc<T> func) { super(name); this.func = func; _set_flag(FLAG_DYNAMIC); } public T get(Container ctx){ throw new RuntimeException("unimplemented"); } @Override public T get() { return (T)val; } @Override public Object _parse(ByteBufferWrapper stream, com.sirtrack.construct.lib.Containers.Container context) { return func.get(context); } @Override public void _build(Object obj, ByteArrayOutputStream stream, com.sirtrack.construct.lib.Containers.Container context) { context.set(name, func.get(context)); } @Override public int _sizeof(com.sirtrack.construct.lib.Containers.Container context) { return 0; } }
package com.ultimo; import io.undertow.server.HttpServerExchange; import io.undertow.util.Headers; import io.undertow.util.HttpString; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.restheart.db.MongoDBClientSingleton; import org.restheart.hal.Representation; import org.restheart.handlers.PipedHttpHandler; import org.restheart.handlers.RequestContext; import org.restheart.handlers.RequestContext.METHOD; import org.restheart.handlers.applicationlogic.ApplicationLogicHandler; import org.restheart.handlers.collection.CollectionRepresentationFactory; import org.restheart.security.handlers.IAuthToken; import org.restheart.utils.HttpStatus; import org.restheart.utils.ResponseHelper; import com.mongodb.AggregationOutput; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientException; import com.mongodb.MongoCommandException; import com.mongodb.MongoException; import com.mongodb.MongoTimeoutException; import com.mongodb.util.JSON; import org.slf4j.LoggerFactory; import org.slf4j.Logger; /* * Watch out for the $match and the other important changes that could happen with the new version of MongoDB when it is released. */ public class AggregateService extends ApplicationLogicHandler implements IAuthToken { MongoClient db; private static final Logger LOGGER = LoggerFactory.getLogger("com.ultimo"); public AggregateService(PipedHttpHandler next, Map<String, Object> args) { super(next, args); } @Override public void handleRequest(HttpServerExchange exchange,RequestContext context) throws Exception { if (context.getMethod() == METHOD.OPTIONS) { exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET"); exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge, " + AUTH_TOKEN_HEADER + ", " + AUTH_TOKEN_VALID_HEADER + ", " + AUTH_TOKEN_LOCATION_HEADER); exchange.setResponseCode(HttpStatus.SC_OK); exchange.endExchange(); } else if (context.getMethod() == METHOD.POST) { String dbname = context.getDBName(); String collectionName = context.getCollectionName(); db = MongoDBClientSingleton.getInstance().getClient(); DB database = db.getDB(dbname); DBCollection collection = database.getCollection(collectionName); // Get Payload try{ InputStream input = exchange.getInputStream(); BufferedReader inputReader = new BufferedReader(new InputStreamReader(input)); String payload = ""; readLoop : while(true) { String inputTemp = inputReader.readLine(); if (inputTemp != null) { payload = payload + inputTemp; } else { break readLoop; } } LOGGER.debug("Payload Recieved"); LOGGER.trace(payload); // // Begin Formatting Query Pipeline // DBObject dbInputObject = null; // List<DBObject> query = new ArrayList<DBObject>(); // JSONArray inputArray = new JSONArray(payload); // for (int a = 0; a < inputArray.length(); a++) // JSONObject inputObject = (JSONObject) inputArray.get(a); // if (inputObject.has("$project")) // dbInputObject = new BasicDBObject("$project",JSON.parse(inputObject.get("$project").toString())); // query.add(dbInputObject); // if (inputObject.has("$match")) // dbInputObject = new BasicDBObject("$match",JSON.parse(inputObject.get("$match").toString())); // System.out.println("Match" + dbInputObject.get("$match").toString()); // query.add(dbInputObject); // if (inputObject.has("$group")) // dbInputObject = new BasicDBObject("$group",JSON.parse(inputObject.get("$group").toString())); // query.add(dbInputObject); // if (inputObject.has("$sort")) // dbInputObject = new BasicDBObject("$sort",JSON.parse(inputObject.get("$sort").toString())); // query.add(dbInputObject); // LOGGER.trace(query.toString()); // LOGGER.debug("Query List Made"); // // Send Query to DB // AggregationOutput output = collection.aggregate( query ); // LOGGER.debug("Query Executed"); // /// System.out.println(output.) // // Process Results // JSONArray resultsArray = new JSONArray(output.results().toString()); // List<DBObject> outputList = new ArrayList<DBObject>(); // int i = 0; // while(i < resultsArray.length()) // DBObject outputObject = (DBObject) JSON.parse(resultsArray.get(i).toString()); // outputList.add(outputObject); // if (resultsArray.length() == 0) // LOGGER.debug("No Results Were Found."); // for(DBObject b : outputList) // //System.out.println(b); // LOGGER.trace(b.toString()); //call method for aggregate List<DBObject> outputList = executeMongoAggregate(payload, collection); CollectionRepresentationFactory data = new CollectionRepresentationFactory(); Representation response = data.getRepresentation(exchange, context, outputList, outputList.size()); LOGGER.trace("Results Transformed into RestHeart Represenation"); int code = HttpStatus.SC_ACCEPTED; // Send Response Back exchange.setResponseCode(code); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, Representation.HAL_JSON_MEDIA_TYPE); exchange.getResponseSender().send(response.toString()); exchange.endExchange(); LOGGER.debug("Response has been Sent and Exchange has been Closed"); } catch(JSONException e) { LOGGER.error("Incorrectly Formated JSON Array. Please check JSON Array Format"); ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE, "Incorrectly Formatted JSON Array. Please check JSON Array Format"); e.printStackTrace(); } catch(MongoCommandException e) { LOGGER.error("Bad MongoDB Request. Request Errored Out"); LOGGER.error(e.getMessage()); ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_BAD_REQUEST, "Bad MongoDB Request. Please rephrase your command."); e.printStackTrace(); } catch(MongoTimeoutException e) { LOGGER.error("MongoDB Connection Timed Out. Please check MongoDB Status and try again "); LOGGER.error(e.getMessage()); ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_INTERNAL_SERVER_ERROR, "MongoDB Connection TimedOut"); e.printStackTrace(); } catch(MongoClientException e) { LOGGER.error("MongoDB Client Error. Ensure that DB and Collection exist"); LOGGER.error(e.getMessage()); ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_INTERNAL_SERVER_ERROR, "MongoDB Client Exception. Please check MongoDB Status"); e.printStackTrace(); } catch(MongoException e) { LOGGER.error("General MongoDB Exception"); LOGGER.error(e.getMessage()); ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_INTERNAL_SERVER_ERROR, "General MongoDB Error"); e.printStackTrace(); } catch(Exception e) { LOGGER.error("Unspecified Application Error" ); e.printStackTrace(); ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Unspecified Application Error"); } } else { ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_METHOD_NOT_ALLOWED, "Method Not Allowed. Post Only "); } } //cal mongo aggregate public static List<DBObject> executeMongoAggregate(String payload, DBCollection collection ){ // Begin Formatting Query Pipeline DBObject dbInputObject = null; List<DBObject> query = new ArrayList<DBObject>(); JSONArray inputArray = new JSONArray(payload); for (int a = 0; a < inputArray.length(); a++) { JSONObject inputObject = (JSONObject) inputArray.get(a); if (inputObject.has("$project")) { dbInputObject = new BasicDBObject("$project",JSON.parse(inputObject.get("$project").toString())); query.add(dbInputObject); } if (inputObject.has("$match")) { dbInputObject = new BasicDBObject("$match",JSON.parse(inputObject.get("$match").toString())); System.out.println("Match" + dbInputObject.get("$match").toString()); query.add(dbInputObject); } if (inputObject.has("$group")) { dbInputObject = new BasicDBObject("$group",JSON.parse(inputObject.get("$group").toString())); query.add(dbInputObject); } if (inputObject.has("$sort")) { dbInputObject = new BasicDBObject("$sort",JSON.parse(inputObject.get("$sort").toString())); query.add(dbInputObject); } } LOGGER.trace(query.toString()); LOGGER.debug("Query List Made"); // Send Query to DB AggregationOutput output = collection.aggregate( query ); LOGGER.debug("Query Executed"); /// System.out.println(output.) // Process Results JSONArray resultsArray = new JSONArray(output.results().toString()); List<DBObject> outputList = new ArrayList<DBObject>(); int i = 0; while(i < resultsArray.length()) { DBObject outputObject = (DBObject) JSON.parse(resultsArray.get(i).toString()); outputList.add(outputObject); i++; } if (resultsArray.length() == 0) { LOGGER.debug("No Results Were Found."); } for(DBObject b : outputList) { //System.out.println(b); LOGGER.trace(b.toString()); } return outputList; } }
package cronapi.database; import java.util.*; import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.PageRequest; import cronapi.CronapiMetaData; import cronapi.CronapiMetaData.CategoryType; import cronapi.CronapiMetaData.ObjectType; import cronapi.ParamMetaData; import cronapi.RestClient; import cronapi.Var; import javax.persistence.EntityManager; @CronapiMetaData(category = CategoryType.DATABASE, categoryTags = { "Database", "Banco", "Dados", "Storage" }) public class Operations { @CronapiMetaData(type = "function", name = "{{datasourceQuery}}", nameTags = { "datasourceQuery", "openConnection", "abrirConsulta" }, description = "{{functionToQueryInDatasource}}", params = { "{{entity}}", "{{query}}", "{{paramsQueryTuples}}" }, paramsType = { ObjectType.STRING, ObjectType.STRING, ObjectType.LIST }, returnType = ObjectType.DATASET, arbitraryParams = true, wizard = "procedures_sql_callreturn") public static Var query(Var entity, Var query, Var ... params) { DataSource ds = new DataSource(entity.getObjectAsString()); if(query == Var.VAR_NULL) ds.fetch(); else { ds.filter(query.getObjectAsString(), params); } Var varDs = new Var(ds); return varDs; } public static Var queryPaged(Var entity, Var query, Var useRestPagination, Var ... params) { DataSource ds = new DataSource(entity.getObjectAsString()); String limit = null; String offset = null; boolean limitChosen = false; boolean offsetChosen = false; List<Var> finalParams = new LinkedList<>(); for (Var p : params){ switch (p.getId()) { case "limit": limit = p.getObjectAsString(); limitChosen = true; break; case "offset": offset = p.getObjectAsString(); offsetChosen = true; break; default: finalParams.add(p); break; } } PageRequest page; int pageNumber = 0; int pageSize = 100; if(offset != null){ pageNumber = Integer.parseInt(offset); } if(limit != null){ pageSize = Integer.parseInt(limit); } page = new PageRequest(pageNumber, pageSize); if (useRestPagination.getObjectAsBoolean()) { if(query != Var.VAR_NULL) { String queryString = RestClient.getRestClient().getRequest().getServletPath(); if (queryString.contains("/api/cronapi/query/")) { queryString = queryString.replace("/api/cronapi/query/", ""); String[] splitedQueryString = queryString.split("/"); if (splitedQueryString.length > 1) { for (int ix = 1; ix < splitedQueryString.length; ix++) { Var param = Var.valueOf("id"+(ix-1), splitedQueryString[ix]); finalParams.add(param); } } } } String pageFromRequest = RestClient.getRestClient().getRequest().getParameter("page"); Boolean isODataParam = StringUtils.isNotEmpty(RestClient.getRestClient().getRequest().getParameter("$skip")); if (StringUtils.isEmpty(pageFromRequest)) { pageFromRequest = RestClient.getRestClient().getRequest().getParameter("$skip"); if (StringUtils.isEmpty(pageFromRequest)) pageFromRequest = "0"; } String pageSizeFromRequest = RestClient.getRestClient().getRequest().getParameter("size"); if (StringUtils.isEmpty(pageSizeFromRequest)) { pageSizeFromRequest = RestClient.getRestClient().getRequest().getParameter("$top"); if (StringUtils.isEmpty(pageSizeFromRequest)) pageSizeFromRequest = "100"; } if (isODataParam) { pageFromRequest = pageFromRequest.equals("0") ? "0" : String.valueOf((Integer.parseInt(pageSizeFromRequest) / Integer.parseInt(pageFromRequest)) ); } if(!offsetChosen){ pageNumber = Integer.parseInt(pageFromRequest); } if(!limitChosen){ pageSize = Integer.parseInt(pageSizeFromRequest); } page = new PageRequest(pageNumber, pageSize); } if(query == Var.VAR_NULL){ ds.fetch(); } else { ds.filter(query.getObjectAsString(), page, finalParams.toArray(new Var[0])); } return new Var(ds); } @CronapiMetaData(type = "function", name = "{{datasourceNext}}", nameTags = { "next", "avançar", "proximo" }, description = "{{functionToMoveCursorToNextPosition}}", params = { "{{datasource}}" }, paramsType = { ObjectType.DATASET }, returnType = ObjectType.VOID, displayInline = true) public static void next(Var ds) { ((DataSource)ds.getObject()).next(); } @CronapiMetaData(type = "function", name = "{{datasourceHasData}}", nameTags = { "hasElement", "existeRegistro", "temRegistro" }, description = "{{functionToVerifyDataInCurrentPosition}}", params = { "{{datasource}}" }, paramsType = { ObjectType.DATASET }, returnType = ObjectType.BOOLEAN, displayInline = true) public static Var hasElement(Var ds) { if (ds.getObject() != null) { return Var.valueOf(((DataSource) ds.getObject()).getObject() != null); } return Var.VAR_FALSE; } @CronapiMetaData(type = "function", name = "{{datasourceClose}}", nameTags = { "close", "fechar", "limpar", "clear" }, description = "{{functionToCloseAndCleanDatasource}}", params = { "{{datasource}}" }, paramsType = { ObjectType.DATASET }, returnType = ObjectType.VOID, displayInline = true) public static void close(Var ds) { ((DataSource)ds.getObject()).clear(); } @CronapiMetaData(type = "function", name = "{{datasourceUpdateField}}", nameTags = { "updateField", "atualizarCampo", "setField", "modificarCampo" }, description = "{{functionToUpdateFieldInDatasource}}", params = { "{{datasource}}", "{{fieldName}}", "{{fieldValue}}" }, paramsType = { ObjectType.DATASET, ObjectType.STRING, ObjectType.STRING }, returnType = ObjectType.VOID) public static void updateField(Var ds, Var fieldName, Var fieldValue) { ds.setField(fieldName.getObjectAsString(), fieldValue.getObjectAsString()); } @CronapiMetaData(type = "function", name = "{{datasourceGetActiveData}}", nameTags = { "getElement", "obterElemento" }, description = "{{functionToDatasourceGetActiveData}}", params = { "{{datasource}}" }, paramsType = { ObjectType.DATASET }, returnType = ObjectType.OBJECT) public static Var getActiveData(Var ds) { return new Var(((DataSource)ds.getObject()).getObject()); } @CronapiMetaData(type = "function", name = "{{datasourceInsert}}", nameTags = { "insert", "create", "novo", "inserir", "criar" }, description = "{{functionToInsertObjectInDatasource}}", params = { "{{datasource}}", "{{params}}" }, paramsType = { ObjectType.DATASET, ObjectType.LIST }, returnType = ObjectType.VOID, arbitraryParams = true, wizard = "procedures_sql_insert_callnoreturn") public static void insert(Var entity, Var ... params) { DataSource ds = new DataSource(entity.getObjectAsString()); ds.insert(); ds.updateFields(params); ds.save(); } public static void insert(Var entity, Var object) { if(!object.equals(Var.VAR_NULL)) { DataSource ds = new DataSource(entity.getObjectAsString()); ds.insert(object.getObjectAsMap()); Object saved = ds.save(); ds.flush(); object.updateWith(saved); } } @CronapiMetaData(type = "function", name = "{{update}}", nameTags = { "update", "edit", "editar", "alterar" }, description = "{{functionToUpdateObjectInDatasource}}", params = { "{{datasource}}", "{{entity}}" }, paramsType = { ObjectType.DATASET, ObjectType.OBJECT }, returnType = ObjectType.VOID, arbitraryParams = true, wizard = "procedures_sql_update_callnoreturn") public static void update(Var entity, Var object) { if(!object.equals(Var.VAR_NULL)) { DataSource ds = new DataSource(entity.getObjectAsString()); ds.filter(object, null); ds.update(new Var(object.getObjectAsMap())); Object saved = ds.save(); object.updateWith(saved); } } @CronapiMetaData(type = "function", name = "{{datasourceRemove}}", nameTags = { "remove", "delete", "remover", "deletar", "excluir" }, description = "{{functionToRemoveObject}}", params = { "{{datasource}}", "{{entity}}" }, paramsType = { ObjectType.DATASET, ObjectType.OBJECT }, returnType = ObjectType.VOID, arbitraryParams = true, wizard = "procedures_sql_delete_callnoreturn") public static void remove(Var entity, Var object) { if(!object.equals(Var.VAR_NULL)) { DataSource ds = new DataSource(entity.getObjectAsString()); ds.filter(object, null); ds.delete(); } } @CronapiMetaData(type = "function", name = "{{datasourceGetField}}", nameTags = { "getField", "obterCampo" }, description = "{{functionToGetFieldOfCurrentCursorInDatasource}}", params = { "{{datasource}}", "{{fieldName}}" }, paramsType = { ObjectType.DATASET, ObjectType.STRING }, returnType = ObjectType.OBJECT, wizard = "procedures_get_field") public static Var getField(@ParamMetaData(blockType = "variables_get", type = ObjectType.OBJECT, description = "{{datasource}}") Var ds, @ParamMetaData(blockType = "procedures_get_field_datasource", type = ObjectType.STRING, description = "{{fieldName}}") Var fieldName) { return ds.getField(fieldName.getObjectAsString()); } @CronapiMetaData(type = "function", name = "{{datasourceGetField}}", nameTags = { "getField", "obterCampo" }, description = "{{functionToGetFieldOfCurrentCursorInDatasource}}", returnType = ObjectType.STRING, wizard = "procedures_get_field_datasource") public static Var getFieldFromDatasource() { return Var.VAR_NULL; } @CronapiMetaData(type = "function", name = "{{datasourceRemove}}", nameTags = { "remove", "delete", "apagar", "remover" }, description = "{{functionToRemoveObjectInDatasource}}", params = { "{{datasource}}" }, paramsType = { ObjectType.DATASET }, returnType = ObjectType.VOID, displayInline = true) public static void remove(Var ds) { ((DataSource)ds.getObject()).delete(); } @CronapiMetaData(type = "function", name = "{{datasourceExecuteQuery}}", nameTags = { "datasourceExecuteQuery", "executeCommand", "executarComando" }, description = "{{functionToExecuteQuery}}", params = { "{{entity}}", "{{query}}", "{{paramsQueryTuples}}" }, paramsType = { ObjectType.STRING, ObjectType.STRING, ObjectType.LIST }, returnType = ObjectType.DATASET, arbitraryParams = true, wizard = "procedures_sql_command_callnoreturn") public static void execute(Var entity, Var query, Var ... params) { DataSource ds = new DataSource(entity.getObjectAsString()); ds.execute(query.getObjectAsString(), params); } @CronapiMetaData(type = "function", name = "{{newEntity}}", nameTags = { "newEntity", "NovaEntidade" }, description = "{{newEntityDescription}}", params = { "{{entity}}", "{{params}}" }, paramsType = { ObjectType.STRING, ObjectType.MAP }, returnType = ObjectType.OBJECT, arbitraryParams = true, wizard = "procedures_createnewobject_callreturn") public static final Var newEntity(Var object, Var ... params) throws Exception { return cronapi.object.Operations.newObject(object, params); } @CronapiMetaData(type = "function", name = "{{datasourceExecuteJQPLQuery}}", nameTags = { "datasourceQuery", "openConnection", "abrirConsulta" }, description = "{{functionToQueryInDatasource}}", params = { "{{entity}}", "{{query}}", "{{paramsQueryTuples}}" }, paramsType = { ObjectType.STRING, ObjectType.STRING, ObjectType.MAP }, returnType = ObjectType.DATASET) public static Var executeQuery(Var entity, Var query, Var params) { Map<String, Var> map = params.getObjectAsMap(); Var[] vars = new Var[map.size()]; int i = 0; for (Map.Entry<String, Var> entry : map.entrySet()) { vars[i] = new Var(entry.getKey(), entry.getValue()); i++; } return query(entity, query, vars); } @CronapiMetaData(type = "function", name = "{{datasourceGetColumnName}}", nameTags = { "GetColumn", "obterColuna","datasource","dados" }, description = "{{datasourceGetColumnDescription}}", params = { "{{datasource}}", "{{fieldName}}" }, paramsType = { ObjectType.DATASET, ObjectType.STRING }, returnType = ObjectType.OBJECT, wizard = "procedures_get_field") public static Var getColumn( @ParamMetaData(blockType = "variables_get", type = ObjectType.OBJECT, description = "{{datasource}}") Var ds, @ParamMetaData(blockType = "procedures_get_field_datasource", type = ObjectType.STRING, description = "{{fieldName}}") Var fieldName) { Object obj = ds.getObject(); List<Object> dst = new LinkedList<Object>(); if (obj instanceof DataSource) { DataSource datasource = (DataSource) obj; while (datasource.hasNext()) { dst.add(ds.getField(fieldName.getObjectAsString())); datasource.next(); } dst.add(ds.getField(fieldName.getObjectAsString())); datasource.setCurrent(0); return Var.valueOf(dst); } return Var.valueOf(dst); } @CronapiMetaData(type = "function", name = "{{commitTransaction}}", nameTags = {"commitTransaction", "commitTransação"}, description = "{{commitTransactionDescription}}", params = {"{{entity}}"}, paramsType = { ObjectType.STRING}, returnType = ObjectType.VOID, wizard = "procedures_setentity_callnoreturn") public static final void commitTransaction(Var object) throws Exception { if (!object.equals(Var.VAR_NULL)) { String className = object.getObjectAsString(); Class<?> c = Class.forName(className); TransactionManager.commit(c); } } @CronapiMetaData(type = "function", name = "{{rollbackTransaction}}", nameTags = {"rollbackTransaction", "rollbackTransação"}, description = "{{rollbackTransactionDescription}}", params = {"{{entity}}"}, paramsType = { ObjectType.STRING }, returnType = ObjectType.VOID, wizard = "procedures_setentity_callnoreturn") public static final void rollbackTransaction(Var object) throws Exception { if (!object.equals(Var.VAR_NULL)) { String className = object.getObjectAsString(); Class<?> c = Class.forName(className); TransactionManager.rollback(c); } } @CronapiMetaData(type = "function", name = "{{flushTransaction}}", nameTags = {"flushTransaction", "flushTransação"}, description = "{{flushTransactionDescription}}", params = {"{{entity}}"}, paramsType = { ObjectType.STRING}, returnType = ObjectType.VOID, wizard = "procedures_setentity_callnoreturn") public static final void flushTransaction(Var object) throws Exception { if (!object.equals(Var.VAR_NULL)) { String className = object.getObjectAsString(); Class<?> c = Class.forName(className); TransactionManager.flush(c); } } @CronapiMetaData(type = "function", name = "{{beginTransaction}}", nameTags = {"beginTransaction", "iniciarTransação"}, description = "{{beginTransaction}}", params = {"{{entity}}"}, paramsType = { ObjectType.STRING}, returnType = ObjectType.VOID, wizard = "procedures_setentity_callnoreturn") public static final void beginTransaction(Var object) throws Exception { if (!object.equals(Var.VAR_NULL)) { String className = object.getObjectAsString(); Class<?> c = Class.forName(className); TransactionManager.begin(c); } } }
package de.idrinth.ssl; public class TrustManager implements org.apache.http.ssl.TrustStrategy { private java.security.KeyStore keyStore; private javax.net.ssl.X509TrustManager manager; /** * * @throws java.lang.Exception */ public TrustManager() throws java.lang.Exception { getStore(); addCertToStore("StartComCertificationAuthority"); addCertToStore("StartComClass2IVServerCA"); addCertToStore("IdrinthDe"); javax.net.ssl.TrustManagerFactory factory = javax.net.ssl.TrustManagerFactory.getInstance("PKIX"); factory.init(keyStore); for (javax.net.ssl.TrustManager trustManager : factory.getTrustManagers()) { if (trustManager instanceof javax.net.ssl.X509TrustManager) { manager = (javax.net.ssl.X509TrustManager) trustManager; return; } } throw new java.lang.RuntimeException("Couldn't initialize Trustmanager due to lack of X509TrustManager"); } /** * * @return java.security.KeyStore */ public final java.security.KeyStore getKeyStore() { return keyStore; } /** * * @throws java.lang.Exception */ private final void getStore() throws java.lang.Exception { String password = "changeit"; keyStore = new KeystoreFinder().getKeystore(password); javax.net.ssl.TrustManagerFactory trustManagerFactory = javax.net.ssl.TrustManagerFactory.getInstance(javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); javax.net.ssl.TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); javax.net.ssl.SSLContext.setDefault(sslContext); System.setProperty("javax.net.ssl.trustStorePassword", password); } /** * * @param name * @throws java.lang.Exception */ private final void addCertToStore(String name) throws java.lang.Exception { java.net.URL resource = getClass().getResource("/certificates/" + name + ".cer"); try (java.io.BufferedInputStream bis = new java.io.BufferedInputStream(resource.openStream())) { java.security.cert.Certificate cert = java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(bis); keyStore.setCertificateEntry(name, cert); } } /** * * @param chain * @param authType * @return boolean */ @Override public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) { try { manager.checkServerTrusted(chain, authType); return true; } catch (java.security.cert.CertificateException e) { de.idrinth.factory.Logger.build().log(e.getMessage(), de.idrinth.Logger.levelWarn); } return false; } class KeystoreFinder { /** * * @param password * @return java.security.KeyStore * @throws java.lang.Exception */ public java.security.KeyStore getKeystore(String password) throws java.lang.Exception { java.security.KeyStore keyStore = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType()); System.setProperty("javax.net.ssl.trustStore", java.security.KeyStore.getDefaultType()); System.setProperty("javax.net.ssl.keyStore", java.security.KeyStore.getDefaultType()); keyStore.load( new java.io.BufferedInputStream( new java.io.FileInputStream(fileForKeystore()) ), password.toCharArray() ); return keyStore; } /** * * @return String */ private String fileForKeystore() { String path = findStoreFolder().getAbsolutePath() + System.getProperty("file.separator"); String prefered = path + "jssecacerts"; String alternative = path + "cacerts"; return new java.io.File(prefered).exists() ? prefered : alternative; } /** * * @return java.io.File */ private java.io.File findStoreFolder() { String[] folders = "lib/security".split("/"); String fileSep = System.getProperty("file.separator"); java.io.File file = new java.io.File(System.getProperty("sun.boot.library.path")); while (!(new java.io.File(file.getAbsoluteFile() + fileSep + folders[0]).exists())) { file = file.getParentFile(); } return new java.io.File(file.getAbsolutePath() + fileSep + folders[0] + fileSep + folders[1]); } } }
package github; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.time.LocalDateTime; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.commons.lang3.tuple.ImmutablePair; import org.eclipse.egit.github.core.client.GitHubClient; import org.eclipse.egit.github.core.client.GitHubRequest; import org.eclipse.egit.github.core.client.GitHubResponse; import util.IOUtilities; import util.Utility; public class GitHubClientExtended extends GitHubClient { public static final int NO_UPDATE_RESPONSE_CODE = 304; protected static final int CONNECTION_TIMEOUT = 30000; public GitHubClientExtended() { } /** * Extends superclass method with connection timeout parameters. */ @Override protected HttpURLConnection createConnection(String uri) throws IOException { HttpURLConnection connection = super.createConnection(uri); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(CONNECTION_TIMEOUT); return connection; } /** * Utility method for creating a connection from a GitHubRequest. * * @param request * @return * @throws IOException */ public HttpURLConnection createConnection(GitHubRequest request) throws IOException { return createGet(request.generateUri()); } /** * Exposes the sendJson method (which is private in the superclass). * * @param <V> * @param request * @param params * @param type * @return * @throws IOException */ public <V> V sendJson(final HttpURLConnection request, final Object params, final Type type) throws IOException { sendParams(request, params); final int code = request.getResponseCode(); updateRateLimits(request); if (isOk(code)) if (type != null) return parseJson(getStream(request), type); else return null; if (isEmpty(code)) return null; throw createException(getStream(request), code, request.getResponseMessage()); } /** * Serves the same purpose as GitHubClient::get, with the added * functionality of returning a GitHubEventResponse (containing * event-specific information) instead of a GitHubResponse. * * @param request * @return response * @throws IOException */ public GitHubEventsResponse getEvent(GitHubRequest request) throws IOException { HttpURLConnection httpRequest = createGet(request.generateUri()); String accept = request.getResponseContentType(); if (accept != null) httpRequest.setRequestProperty(HEADER_ACCEPT, accept); final int code = httpRequest.getResponseCode(); updateRateLimits(httpRequest); if (isOk(code)) { // Copy the httpRequest input stream into a byte array InputStream reqIS = getStream(httpRequest); ByteArrayOutputStream buffer = IOUtilities.inputStreamToByteArrayOutputStream(reqIS); InputStream reqIS2 = new ByteArrayInputStream(buffer.toByteArray()); InputStream reqIS3 = new ByteArrayInputStream(buffer.toByteArray()); // The first copy is used to produce the GitHubResponse GitHubResponse ghResponse = new GitHubResponse(httpRequest, getBody(request, reqIS2)); // The second is parsed again for event-specific information return new GitHubEventsResponse(ghResponse, reqIS3); } else if (isEmpty(code)) { GitHubResponse ghResponse = new GitHubResponse(httpRequest, null); return new GitHubEventsResponse(ghResponse, null); } else { throw createException(getStream(httpRequest), code, httpRequest.getResponseMessage()); } } /** * Accesses the Rate Limit API endpoint to retrieve the number of remaining requests for the hour, * as well as the next reset time. Calling this function itself does not count towards the API limit. * * @return A pair consisting of the number of requests remaining for the hour and the next reset time. * @throws IOException */ @SuppressWarnings("unchecked") public ImmutablePair<Integer, LocalDateTime> getRateLimitResetTime() throws IOException { HttpURLConnection httpRequest = createGet("/rate_limit"); if (isOk(httpRequest.getResponseCode())) { // We extract from rate, which is similar to resources.core String json = String.valueOf( IOUtilities.inputStreamToByteArrayOutputStream(getStream(httpRequest))); Map<String, Object> map = new Gson().fromJson(json, new TypeToken<Map<String, Object>>() {}.getType()); Map<String, Double> mapRate = (Map<String, Double>) map.get("rate"); long reset = mapRate.get("reset").longValue(); int remaining = mapRate.get("remaining").intValue(); LocalDateTime nextReset = Utility.longToLocalDateTime(reset); return new ImmutablePair<>(remaining, nextReset); } else { throw new IOException(httpRequest.getResponseCode() + " " + httpRequest.getResponseMessage()); } } /** * Overridden to make public. */ @Override public IOException createException(InputStream response, int code, String status) { return super.createException(response, code, status); } /** * Overridden to make public. */ @Override public HttpURLConnection createPost(String uri) throws IOException { return super.createPost(uri); } /** * Overridden to make public. */ @Override public InputStream getStream(HttpURLConnection request) throws IOException { return super.getStream(request); } /** * Overridden to make public. */ @Override public Object getBody(GitHubRequest request, InputStream stream) throws IOException { return super.getBody(request, stream); } /** * Overridden to make public. */ @Override public boolean isError(final int code) { return super.isError(code); } /** * Overridden to make public. * * @param code * @return */ public boolean isOk(final int code) { return super.isOk(code); } /** * Overridden to make public. * * @param request * @param params * @throws IOException */ public void sendParams(HttpURLConnection request, Object params) throws IOException { super.sendParams(request, params); } }
package hu.bme.mit.spaceship; /** * A simple spaceship with two proton torpedos and four lasers */ public class GT4500 implements SpaceShip { private TorpedoStore primaryTorpedoStore; private TorpedoStore secondaryTorpedoStore; private boolean wasPrimaryFiredLast = false; public GT4500() { this.primaryTorpedoStore = new TorpedoStore(10); this.secondaryTorpedoStore = new TorpedoStore(10); } public boolean fireLasers(FiringMode firingMode) { // TODO not implemented yet return false; } /** * Tries to fire the torpedo stores of the ship. * * @param firingMode how many torpedo bays to fire * SINGLE: fires only one of the bays. * - For the first time the primary store is fired. * - To give some cooling time to the torpedo stores, torpedo stores are fired alternating. * - But if the store next in line is empty the ship tries to fire the other store. * - If the fired store reports a failure, the ship does not try to fire the other one. * ALL: tries to fire both of the torpedo stores. * * @return whether at least one torpedo was fired successfully */ @Override public boolean fireTorpedos(FiringMode firingMode) { boolean firingSuccess = false; switch (firingMode) { case SINGLE: if (wasPrimaryFiredLast) { // try to fire the secondary first if (! secondaryTorpedoStore.isEmpty()) { firingSuccess = secondaryTorpedoStore.fire(1); wasPrimaryFiredLast = false; } else { // although primary was fired last time, but the secondary is empty // thus try to fire primary again if (! primaryTorpedoStore.isEmpty()) { firingSuccess = primaryTorpedoStore.fire(1); wasPrimaryFiredLast = true; } // if both of the stores are empty, nothing can be done, return failure } } else { // try to fire the primary first if (! primaryTorpedoStore.isEmpty()) { firingSuccess = primaryTorpedoStore.fire(1); wasPrimaryFiredLast = true; } else { // although secondary was fired last time, but primary is empty // thus try to fire secondary again if (! secondaryTorpedoStore.isEmpty()) { firingSuccess = secondaryTorpedoStore.fire(1); wasPrimaryFiredLast = false; } // if both of the stores are empty, nothing can be done, return failure } } break; case ALL: // try to fire both of the torpedos firingSuccess = primaryTorpedoStore.fire(1) || secondaryTorpedoStore.fire(1); break; } return firingSuccess; } }
package hudson.remoting; import java.io.CharArrayWriter; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; /** * {@link Writer} that sends bits to an exported * {@link Writer} on a remote machine. */ final class ProxyWriter extends Writer { private Channel channel; private int oid; /** * If bytes are written to this stream before it's connected * to a remote object, bytes will be stored in this buffer. */ private CharArrayWriter tmp; /** * Set to true if the stream is closed. */ private boolean closed; /** * Creates unconnected {@link ProxyWriter}. * The returned stream accepts data right away, and * when it's {@link #connect(Channel,int) connected} later, * the data will be sent at once to the remote stream. */ public ProxyWriter() { } /** * Creates an already connected {@link ProxyWriter}. * * @param oid * The object id of the exported {@link OutputStream}. */ public ProxyWriter(Channel channel, int oid) throws IOException { connect(channel,oid); } /** * Connects this stream to the specified remote object. */ synchronized void connect(Channel channel, int oid) throws IOException { if(this.channel!=null) throw new IllegalStateException("Cannot connect twice"); this.channel = channel; this.oid = oid; // if we already have bytes to write, do so now. if(tmp!=null) { write(tmp.toCharArray()); tmp = null; } if(closed) // already marked closed? close(); } public void write(int c) throws IOException { write(new char[]{(char)c},0,1); } public void write(char[] cbuf, int off, int len) throws IOException { if(closed) throw new IOException("stream is already closed"); if(off==0 && len==cbuf.length) write(cbuf); else { char[] buf = new char[len]; System.arraycopy(cbuf,off,buf,0,len); write(buf); } } public synchronized void write(char[] cbuf) throws IOException { if(closed) throw new IOException("stream is already closed"); if(channel==null) { if(tmp==null) tmp = new CharArrayWriter(); tmp.write(cbuf); } else { channel.send(new Chunk(oid,cbuf)); } } public void flush() throws IOException { // noop } public synchronized void close() throws IOException { closed = true; if(channel!=null) { channel.send(new EOF(oid)); channel = null; oid = -1; } } protected void finalize() throws Throwable { super.finalize(); close(); } /** * {@link Command} for sending bytes. */ private static final class Chunk extends Command { private final int oid; private final char[] buf; public Chunk(int oid, char[] buf) { this.oid = oid; this.buf = buf; } protected void execute(Channel channel) { Writer os = (Writer) channel.getExportedObject(oid); try { os.write(buf); } catch (IOException e) { // ignore errors } } public String toString() { return "Pipe.Chunk("+oid+","+buf.length+")"; } private static final long serialVersionUID = 1L; } /** * {@link Command} for sending EOF. */ private static final class EOF extends Command { private final int oid; public EOF(int oid) { this.oid = oid; } protected void execute(Channel channel) { OutputStream os = (OutputStream) channel.getExportedObject(oid); channel.unexport(oid); if (os == null) { return; } try { os.close(); } catch (IOException e) { // ignore errors } } public String toString() { return "Pipe.EOF("+oid+")"; } private static final long serialVersionUID = 1L; } }
package it.polimi.main; import it.polimi.processing.collector.StartableCollector; import it.polimi.processing.enums.EventBuilderMode; import it.polimi.processing.enums.ExperimentType; import it.polimi.processing.enums.Reasoning; import it.polimi.processing.ets.collector.CollectorEventResult; import it.polimi.processing.ets.collector.CollectorExperimentResult; import it.polimi.processing.ets.core.RSPTestStand; import it.polimi.processing.ets.streamer.NTStreamer; import it.polimi.processing.ets.timecontrol.InternalTiming; import it.polimi.processing.ets.timecontrol.NaiveStrategy; import it.polimi.processing.ets.timecontrol.TimeStrategy; import it.polimi.processing.events.RSPTripleSet; import it.polimi.processing.events.factory.ConstantEventBuilder; import it.polimi.processing.events.factory.StepEventBuilder; import it.polimi.processing.events.factory.abstracts.EventBuilder; import it.polimi.processing.events.interfaces.EventResult; import it.polimi.processing.events.interfaces.ExperimentResult; import it.polimi.processing.rspengine.JeanRSPEngineFactory; import it.polimi.processing.rspengine.JenaReasoningListenerFactory; import it.polimi.processing.rspengine.abstracts.RSPEngine; import it.polimi.processing.rspengine.windowed.jena.enums.JenaEventType; import it.polimi.processing.rspengine.windowed.jena.enums.Reasoner; import it.polimi.processing.services.FileService; import it.polimi.processing.streamer.RSPTripleSetStreamer; import it.polimi.processing.system.ExecutionEnvirorment; import it.polimi.processing.system.GetPropertyValues; import it.polimi.utils.FileUtils; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.log4j.Log4j; import com.espertech.esper.client.UpdateListener; @Log4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class BaselineMain { // EVENT TYPES private static JenaEventType CEP_EVENT_TYPE; private static int EXPERIMENT_NUMBER; private static RSPEngine engine; private static Date EXPERIMENT_DATE; private static String file, COMMENT; private static RSPTestStand testStand; private static StartableCollector<EventResult> streamingEventResultCollector; private static StartableCollector<ExperimentResult> experimentResultCollector; private static UpdateListener listener; private static final DateFormat DT = new SimpleDateFormat("yyyy_MM_dd"); private static ExperimentType EXPERIMENT_TYPE; private static int EXECUTION_NUMBER; private static String whereOutput, whereWindow, outputFileName, windowFileName, experimentDescription; private static RSPTripleSetStreamer streamer; private static Reasoner CURRENT_REASONER; private static Reasoning REASONING; private static EventBuilderMode STREAMING_MODE; private static String engineName; private static String eventBuilderCodeName; private static int X; private static int Y; private static int INIT_SIZE; private static int EVENTS; private static String RSPENGINE; public static String INPUT_PROPERTIES; private static String wINDOWSIZE; public static void main(String[] args) throws ClassNotFoundException, SQLException, ParseException { if (args.length >= 1) { INPUT_PROPERTIES = args[0]; log.info(Arrays.deepToString(args)); } file = GetPropertyValues.getProperty(GetPropertyValues.DEFAULT_INPUT_FILE); EXPERIMENT_NUMBER = GetPropertyValues.getIntegerProperty("experiment_number"); EXPERIMENT_DATE = GetPropertyValues.getDateProperty("experiment_date"); EXECUTION_NUMBER = GetPropertyValues.getIntegerProperty("execution_number"); COMMENT = GetPropertyValues.contains("comment") ? GetPropertyValues.getProperty("comment") : ""; RSPENGINE = GetPropertyValues.getProperty("current_engine"); if (RSPENGINE.equals("JENA")) { CURRENT_REASONER = GetPropertyValues.getEnumProperty(Reasoner.class, "jena_current_reasoner"); engineName = CURRENT_REASONER.name().toLowerCase(); CEP_EVENT_TYPE = GetPropertyValues.getEnumProperty(JenaEventType.class, "cep_event_type"); REASONING = Reasoning.NAIVE; // GetPropertyValues.getEnumProperty(Reasoning.class, "reasoning_mode"); } EVENTS = GetPropertyValues.getIntegerProperty("max_event_stream"); STREAMING_MODE = GetPropertyValues.getEnumProperty(EventBuilderMode.class, "streaming_mode"); INIT_SIZE = GetPropertyValues.getIntegerProperty("init_size"); X = GetPropertyValues.getIntegerProperty("x_size"); Y = GetPropertyValues.getIntegerProperty("y_size"); log.info("Experiment [" + EXPERIMENT_NUMBER + "] on [" + file + "] of [" + EXPERIMENT_DATE + "] Number of Events [" + EVENTS + "]"); TimeStrategy strategy = (GetPropertyValues.getBooleanProperty("external_time_control_on")) ? timeStrategySelection() : new InternalTiming(); testStand = new RSPTestStand(strategy); eventBuilderCodeName = streamerSelection(); experimentDescription = "EXPERIMENT_ON_" + file + "_WITH_ENGINE_" + engineName + "EVENT_" + CEP_EVENT_TYPE; FileService.createOutputFolder(FileUtils.daypath + "/exp" + EXPERIMENT_NUMBER + "/" + engineName); wINDOWSIZE = GetPropertyValues.getProperty("rsp_events_in_window"); String generalName = "EN" + EXPERIMENT_NUMBER + "_" + "EXE" + EXECUTION_NUMBER + "_" + COMMENT + "_" + DT.format(EXPERIMENT_DATE) + "_" + file.split("\\.")[0] + "_" + CURRENT_REASONER + "_" + CEP_EVENT_TYPE + "_INIT" + INIT_SIZE + eventBuilderCodeName + "_EW_" + wINDOWSIZE; EXPERIMENT_TYPE = GetPropertyValues.getEnumProperty(ExperimentType.class, "experiment_type"); outputFileName = EXPERIMENT_TYPE.ordinal() + "Result_" + generalName; windowFileName = EXPERIMENT_TYPE.ordinal() + "Window_" + generalName; whereOutput = "exp" + EXPERIMENT_NUMBER + "/" + engineName + "/" + outputFileName; whereWindow = "exp" + EXPERIMENT_NUMBER + "/" + engineName + "/" + windowFileName; log.info("Output file name will be: [" + whereOutput + "]"); log.info("Window file name will be: [" + whereWindow + "]"); reasonerSelection(); collectorSelection(); jenaEngineSelection(); run(file, COMMENT, EXPERIMENT_NUMBER, EXPERIMENT_DATE, experimentDescription); } private static TimeStrategy timeStrategySelection() { return new NaiveStrategy(); } protected static String streamerSelection() { EventBuilder<RSPTripleSet> eb = null; String code = "_EB"; String message = "Event Builder Selection: [" + STREAMING_MODE + "] [" + INIT_SIZE + "] "; switch (STREAMING_MODE) { case CONSTANT: code += "K" + INIT_SIZE; eb = new ConstantEventBuilder(INIT_SIZE, EXPERIMENT_NUMBER); break; case STEP: message += " Heigh [" + X + "] Width [" + Y + "] "; eb = new StepEventBuilder(X, Y, INIT_SIZE, EXPERIMENT_NUMBER); code += "S" + INIT_SIZE + "H" + X + "W" + Y; break; default: message = "Not valid case [" + STREAMING_MODE + "]"; } log.info(message); if (eb != null) { streamer = new NTStreamer(testStand, eb, EVENTS); return code; } throw new IllegalArgumentException("Not valid case [" + STREAMING_MODE + "]"); } protected static void jenaEngineSelection() { String message = "Engine Selection: [" + CEP_EVENT_TYPE + "] [" + engineName.toUpperCase() + "] "; boolean incremental = Reasoning.INCREMENTAL.equals(REASONING); switch (CEP_EVENT_TYPE) { case TEVENT: engine = incremental ? JeanRSPEngineFactory.getIncrementalSerializedEngine(testStand, listener) : JeanRSPEngineFactory .getSerializedEngine(testStand, listener); return; case STMT: engine = incremental ? JeanRSPEngineFactory.getIncrementalStmtEngine(testStand, listener) : JeanRSPEngineFactory.getStmtEngine( testStand, listener); return; case GRAPH: engine = incremental ? JeanRSPEngineFactory.getJenaEngineGraph(testStand, listener) : JeanRSPEngineFactory.getJenaEngineGraph( testStand, listener); return; default: message = "Not valid case [" + CEP_EVENT_TYPE + "]"; } log.info(message); throw new IllegalArgumentException("Not valid case [" + CEP_EVENT_TYPE + "]"); } protected static void reasonerSelection() { log.info("Reasoner Selection: [" + CURRENT_REASONER + "]"); switch (CURRENT_REASONER) { case SMPL: listener = JenaReasoningListenerFactory.getSMPLListener(testStand); break; case RHODF: listener = JenaReasoningListenerFactory.getRhoDfListener(testStand); break; case FULL: listener = JenaReasoningListenerFactory.getFULLListener(testStand); break; case SMPL_INC: listener = JenaReasoningListenerFactory.getIncrementalSMPLListener(testStand); break; case RHODF_INC: listener = JenaReasoningListenerFactory.getIncrementalRhoDfListener(testStand); break; case FULL_INC: listener = JenaReasoningListenerFactory.getIncrementalFULLListener(testStand); break; default: log.error("Not valid case [" + CURRENT_REASONER + "]"); throw new IllegalArgumentException("Not valid case [" + CURRENT_REASONER + "]"); } } protected static void collectorSelection() { experimentResultCollector = new CollectorExperimentResult(); streamingEventResultCollector = new CollectorEventResult(engineName + "/"); String exp = ""; if (ExecutionEnvirorment.finalresultTrigLogEnabled) exp += "Result C&S "; if (ExecutionEnvirorment.memoryLogEnabled) exp += "Memory "; if (ExecutionEnvirorment.latencyLogEnabled) exp += "Latency "; log.info("Execution of " + exp + "Experiment"); } private static void run(String f, String comment, int experimentNumber, Date d, String experimentDescription) { testStand.build(streamingEventResultCollector, experimentResultCollector, engine, streamer); testStand.init(); try { experimentNumber += testStand.run(f, experimentNumber, comment, outputFileName, windowFileName, experimentDescription); } catch (Exception e) { log.error(e.getMessage()); testStand.stop(); } testStand.close(); } }
package javax.jmdns.impl; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jmdns.JmDNS; import javax.jmdns.JmmDNS; import javax.jmdns.NetworkTopologyDiscovery; import javax.jmdns.NetworkTopologyEvent; import javax.jmdns.NetworkTopologyListener; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import javax.jmdns.ServiceTypeListener; import javax.jmdns.impl.constants.DNSConstants; import javax.jmdns.impl.util.NamedThreadFactory; /** * This class enable multihoming mDNS. It will open a mDNS per IP address of the machine. * * @author C&eacute;drik Lime, Pierre Frisch */ public class JmmDNSImpl implements JmmDNS, NetworkTopologyListener, ServiceInfoImpl.Delegate { private static Logger logger = LoggerFactory.getLogger(JmmDNSImpl.class.getName()); private final Set<NetworkTopologyListener> _networkListeners; /** * Every JmDNS created. */ private final ConcurrentMap<InetAddress, JmDNS> _knownMDNS; /** * This enable the service info text update. */ private final ConcurrentMap<String, ServiceInfo> _services; /** * List of registered services */ private final Set<String> _serviceTypes; /** * Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's. */ private final ConcurrentMap<String, List<ServiceListener>> _serviceListeners; /** * Holds instances of ServiceTypeListener's. */ private final Set<ServiceTypeListener> _typeListeners; private final ExecutorService _listenerExecutor; private final ExecutorService _jmDNSExecutor; private final Timer _timer; private final AtomicBoolean _isClosing; private final AtomicBoolean _closed; public JmmDNSImpl() { super(); _networkListeners = Collections.synchronizedSet(new HashSet<NetworkTopologyListener>()); _knownMDNS = new ConcurrentHashMap<InetAddress, JmDNS>(); _services = new ConcurrentHashMap<String, ServiceInfo>(20); _listenerExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("JmmDNS Listeners")); _jmDNSExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS")); _timer = new Timer("Multihomed mDNS.Timer", true); _serviceListeners = new ConcurrentHashMap<String, List<ServiceListener>>(); _typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListener>()); _serviceTypes = Collections.synchronizedSet(new HashSet<String>()); (new NetworkChecker(this, NetworkTopologyDiscovery.Factory.getInstance())).start(_timer); _isClosing = new AtomicBoolean(false); _closed = new AtomicBoolean(false); } /* * (non-Javadoc) * @see java.io.Closeable#close() */ @Override public void close() throws IOException { if (_isClosing.compareAndSet(false, true)) { logger.debug("Cancelling JmmDNS: {}", this); _timer.cancel(); _listenerExecutor.shutdown(); _jmDNSExecutor.shutdown(); // We need to cancel all the DNS ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS.close")); try { for (final JmDNS mDNS : this.getDNS()) { executor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { try { mDNS.close(); } catch (IOException exception) { // JmDNS never throws this is only because of the closeable interface } } }); } } finally { executor.shutdown(); } try { executor.awaitTermination(DNSConstants.CLOSE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.warn("Exception ", exception); } _knownMDNS.clear(); _services.clear(); _serviceListeners.clear(); _typeListeners.clear(); _serviceTypes.clear(); _closed.set(true); JmmDNS.Factory.close(); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getNames() */ @Override public String[] getNames() { Set<String> result = new HashSet<String>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getName()); } return result.toArray(new String[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getHostNames() */ @Override public String[] getHostNames() { Set<String> result = new HashSet<String>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getHostName()); } return result.toArray(new String[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getInetAddresses() */ @Override public InetAddress[] getInetAddresses() throws IOException { Set<InetAddress> result = new HashSet<InetAddress>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getInetAddress()); } return result.toArray(new InetAddress[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getDNS() */ @Override public JmDNS[] getDNS() { synchronized (_knownMDNS) { return _knownMDNS.values().toArray(new JmDNS[_knownMDNS.size()]); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getInterfaces() */ @Override @Deprecated public InetAddress[] getInterfaces() throws IOException { Set<InetAddress> result = new HashSet<InetAddress>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getInterface()); } return result.toArray(new InetAddress[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String) */ @Override public ServiceInfo[] getServiceInfos(String type, String name) { return this.getServiceInfos(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, long) */ @Override public ServiceInfo[] getServiceInfos(String type, String name, long timeout) { return this.getServiceInfos(type, name, false, timeout); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean) */ @Override public ServiceInfo[] getServiceInfos(String type, String name, boolean persistent) { return this.getServiceInfos(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean, long) */ @Override public ServiceInfo[] getServiceInfos(final String type, final String name, final boolean persistent, final long timeout) { // We need to run this in parallel to respect the timeout. final JmDNS[] dnsArray = this.getDNS(); final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length); if (dnsArray.length > 0) { List<Callable<ServiceInfo>> tasks = new ArrayList<Callable<ServiceInfo>>(dnsArray.length); for (final JmDNS mDNS : dnsArray) { tasks.add(new Callable<ServiceInfo>() { @Override public ServiceInfo call() throws Exception { return mDNS.getServiceInfo(type, name, persistent, timeout); } }); } ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.getServiceInfos")); try { List<Future<ServiceInfo>> results = Collections.emptyList(); try { results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.debug("Interrupted ", exception); Thread.currentThread().interrupt(); // Will terminate next loop early. } for (Future<ServiceInfo> future : results) { if (future.isCancelled()) { continue; } try { ServiceInfo info = future.get(); if (info != null) { result.add(info); } } catch (InterruptedException exception) { logger.debug("Interrupted ", exception); Thread.currentThread().interrupt(); } catch (ExecutionException exception) { logger.warn("Exception ", exception); } } } finally { executor.shutdown(); } } return result.toArray(new ServiceInfo[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String) */ @Override public void requestServiceInfo(String type, String name) { this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean) */ @Override public void requestServiceInfo(String type, String name, boolean persistent) { this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, long) */ @Override public void requestServiceInfo(String type, String name, long timeout) { this.requestServiceInfo(type, name, false, timeout); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long) */ @Override public void requestServiceInfo(final String type, final String name, final boolean persistent, final long timeout) { // We need to run this in parallel to respect the timeout. for (final JmDNS mDNS : this.getDNS()) { _jmDNSExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { mDNS.requestServiceInfo(type, name, persistent, timeout); } }); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void addServiceTypeListener(ServiceTypeListener listener) throws IOException { _typeListeners.add(listener); for (JmDNS mDNS : this.getDNS()) { mDNS.addServiceTypeListener(listener); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void removeServiceTypeListener(ServiceTypeListener listener) { _typeListeners.remove(listener); for (JmDNS mDNS : this.getDNS()) { mDNS.removeServiceTypeListener(listener); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void addServiceListener(String type, ServiceListener listener) { final String loType = type.toLowerCase(); List<ServiceListener> list = _serviceListeners.get(loType); if (list == null) { _serviceListeners.putIfAbsent(loType, new LinkedList<ServiceListener>()); list = _serviceListeners.get(loType); } if (list != null) { synchronized (list) { if (!list.contains(listener)) { list.add(listener); } } } for (JmDNS mDNS : this.getDNS()) { mDNS.addServiceListener(type, listener); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void removeServiceListener(String type, ServiceListener listener) { String loType = type.toLowerCase(); List<ServiceListener> list = _serviceListeners.get(loType); if (list != null) { synchronized (list) { list.remove(listener); if (list.isEmpty()) { _serviceListeners.remove(loType, list); } } } for (JmDNS mDNS : this.getDNS()) { mDNS.removeServiceListener(type, listener); } } /* * (non-Javadoc) * @see javax.jmdns.impl.ServiceInfoImpl.Delegate#textValueUpdated(javax.jmdns.ServiceInfo, byte[]) */ @Override public void textValueUpdated(ServiceInfo target, byte[] value) { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); synchronized (_services) { for (JmDNS mDNS : dnsArray) { ServiceInfo info = ((JmDNSImpl) mDNS).getServices().get(target.getQualifiedName()); if (info != null) { info.setText(value); } else { logger.warn("We have a mDNS that does not know about the service info being updated."); } } } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#registerService(javax.jmdns.ServiceInfo) */ @Override public void registerService(ServiceInfo info) throws IOException { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); // This is really complex. We need to clone the service info for each DNS but then we loose the ability to update it. synchronized (_services) { for (JmDNS mDNS : dnsArray) { mDNS.registerService(info.clone()); } ((ServiceInfoImpl) info).setDelegate(this); _services.put(info.getQualifiedName(), info); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#unregisterService(javax.jmdns.ServiceInfo) */ @Override public void unregisterService(ServiceInfo info) { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); synchronized (_services) { _services.remove(info.getQualifiedName()); for (JmDNS mDNS : dnsArray) { mDNS.unregisterService(info); } ((ServiceInfoImpl) info).setDelegate(null); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#unregisterAllServices() */ @Override public void unregisterAllServices() { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); synchronized (_services) { _services.clear(); for (JmDNS mDNS : dnsArray) { mDNS.unregisterAllServices(); } } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#registerServiceType(java.lang.String) */ @Override public void registerServiceType(String type) { _serviceTypes.add(type); for (JmDNS mDNS : this.getDNS()) { mDNS.registerServiceType(type); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#list(java.lang.String) */ @Override public ServiceInfo[] list(String type) { return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#list(java.lang.String, long) */ @Override public ServiceInfo[] list(final String type, final long timeout) { final JmDNS[] dnsArray = this.getDNS(); // We need to run this in parallel to respect the timeout. final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length * 5); if (dnsArray.length > 0) { List<Callable<List<ServiceInfo>>> tasks = new ArrayList<Callable<List<ServiceInfo>>>(dnsArray.length); for (final JmDNS mDNS : dnsArray) { tasks.add(new Callable<List<ServiceInfo>>() { @Override public List<ServiceInfo> call() throws Exception { return Arrays.asList(mDNS.list(type, timeout)); } }); } ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.list")); try { List<Future<List<ServiceInfo>>> results = Collections.emptyList(); try { results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.debug("Interrupted ", exception); Thread.currentThread().interrupt(); // Will terminate next loop early. } for (Future<List<ServiceInfo>> future : results) { if (future.isCancelled()) { continue; } try { result.addAll(future.get()); } catch (InterruptedException exception) { logger.debug("Interrupted ", exception); Thread.currentThread().interrupt(); } catch (ExecutionException exception) { logger.warn("Exception ", exception); } } } finally { executor.shutdown(); } } return result.toArray(new ServiceInfo[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String) */ @Override public Map<String, ServiceInfo[]> listBySubtype(String type) { return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String, long) */ @Override public Map<String, ServiceInfo[]> listBySubtype(final String type, final long timeout) { Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5); for (ServiceInfo info : this.list(type, timeout)) { String subtype = info.getSubtype(); if (!map.containsKey(subtype)) { map.put(subtype, new ArrayList<ServiceInfo>(10)); } map.get(subtype).add(info); } Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size()); for (final Map.Entry<String, List<ServiceInfo>> entry : map.entrySet()) { final String subtype = entry.getKey(); final List<ServiceInfo> infoForSubType = entry.getValue(); result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()])); } return result; } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#addNetworkTopologyListener(javax.jmdns.NetworkTopologyListener) */ @Override public void addNetworkTopologyListener(NetworkTopologyListener listener) { _networkListeners.add(listener); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#removeNetworkTopologyListener(javax.jmdns.NetworkTopologyListener) */ @Override public void removeNetworkTopologyListener(NetworkTopologyListener listener) { _networkListeners.remove(listener); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#networkListeners() */ @Override public NetworkTopologyListener[] networkListeners() { return _networkListeners.toArray(new NetworkTopologyListener[_networkListeners.size()]); } /* * (non-Javadoc) * @see javax.jmdns.NetworkTopologyListener#inetAddressAdded(javax.jmdns.NetworkTopologyEvent) */ @Override public void inetAddressAdded(NetworkTopologyEvent event) { InetAddress address = event.getInetAddress(); try { if (!_knownMDNS.containsKey(address)) { synchronized (_knownMDNS) { if (!_knownMDNS.containsKey(address)) { final JmDNS dns = createJmDnsInstance(address); if (_knownMDNS.putIfAbsent(address, dns) == null) { // We need to register the services and listeners with the new JmDNS final Collection<String> types = _serviceTypes; final Collection<ServiceInfo> infos = _services.values(); final Collection<ServiceTypeListener> typeListeners = _typeListeners; final Map<String, List<ServiceListener>> serviceListeners = _serviceListeners; _jmDNSExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { // Register Types for (String type : types) { dns.registerServiceType(type); } // Register services for (ServiceInfo info : infos) { try { dns.registerService(info.clone()); } catch (IOException exception) { // logger.warn("Unexpected unhandled exception: " + exception); } } // Add ServiceType Listeners for (ServiceTypeListener listener : typeListeners) { try { dns.addServiceTypeListener(listener); } catch (IOException exception) { // logger.warn("Unexpected unhandled exception: " + exception); } } // Add Service Listeners for (final Map.Entry<String, List<ServiceListener>> entry : serviceListeners.entrySet()) { final String type = entry.getKey(); final List<ServiceListener> listeners = entry.getValue(); synchronized (listeners) { for (ServiceListener listener : listeners) { dns.addServiceListener(type, listener); } } } } }); final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(dns, address); for (final NetworkTopologyListener listener : this.networkListeners()) { _listenerExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { listener.inetAddressAdded(jmdnsEvent); } }); } } else { dns.close(); } } } } } catch (Exception e) { logger.warn("Unexpected unhandled exception: " + e); } } /* * (non-Javadoc) * @see javax.jmdns.NetworkTopologyListener#inetAddressRemoved(javax.jmdns.NetworkTopologyEvent) */ @Override public void inetAddressRemoved(NetworkTopologyEvent event) { InetAddress address = event.getInetAddress(); try { if (_knownMDNS.containsKey(address)) { synchronized (_knownMDNS) { if (_knownMDNS.containsKey(address)) { JmDNS mDNS = _knownMDNS.remove(address); mDNS.close(); final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(mDNS, address); for (final NetworkTopologyListener listener : this.networkListeners()) { _listenerExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { listener.inetAddressRemoved(jmdnsEvent); } }); } } } } } catch (Exception e) { logger.warn("Unexpected unhandled exception: " + e); } } /** * Checks the network state.<br/> * If the network change, this class will reconfigure the list of DNS do adapt to the new configuration. */ static class NetworkChecker extends TimerTask { private static Logger logger1 = LoggerFactory.getLogger(NetworkChecker.class.getName()); private final NetworkTopologyListener _mmDNS; private final NetworkTopologyDiscovery _topology; private Set<InetAddress> _knownAddresses; public NetworkChecker(NetworkTopologyListener mmDNS, NetworkTopologyDiscovery topology) { super(); this._mmDNS = mmDNS; this._topology = topology; _knownAddresses = Collections.synchronizedSet(new HashSet<InetAddress>()); } public void start(Timer timer) { // Run once up-front otherwise the list of servers will only appear after a delay. run(); timer.schedule(this, DNSConstants.NETWORK_CHECK_INTERVAL, DNSConstants.NETWORK_CHECK_INTERVAL); } /** * {@inheritDoc} */ @Override public void run() { try { InetAddress[] curentAddresses = _topology.getInetAddresses(); Set<InetAddress> current = new HashSet<InetAddress>(curentAddresses.length); for (InetAddress address : curentAddresses) { current.add(address); if (!_knownAddresses.contains(address)) { final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address); _mmDNS.inetAddressAdded(event); } } for (InetAddress address : _knownAddresses) { if (!current.contains(address)) { final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address); _mmDNS.inetAddressRemoved(event); } } _knownAddresses = current; } catch (Exception e) { logger1.warn("Unexpected unhandled exception: " + e); } } } protected JmDNS createJmDnsInstance(InetAddress address) throws IOException { return JmDNS.create(address); } }
package jcifs.smb; import java.io.IOException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.EnumSet; import java.util.Locale; import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jcifs.CIFSContext; import jcifs.CIFSException; import jcifs.Configuration; import jcifs.DfsReferralData; import jcifs.RuntimeCIFSException; import jcifs.SmbConstants; import jcifs.SmbResourceLocator; import jcifs.SmbTreeHandle; import jcifs.internal.CommonServerMessageBlockRequest; import jcifs.internal.CommonServerMessageBlockResponse; import jcifs.internal.RequestWithPath; import jcifs.internal.dfs.DfsReferralDataInternal; import jcifs.internal.smb1.com.SmbComClose; import jcifs.internal.smb1.com.SmbComFindClose2; import jcifs.internal.smb1.trans.nt.NtTransQuerySecurityDesc; import jcifs.util.transport.TransportException; /** * This class encapsulates the logic for switching tree connections * * Switching trees can occur either when the tree has been disconnected by failure or idle-timeout - as well as on * DFS referrals. * * @author mbechler * */ class SmbTreeConnection { private static final Logger log = LoggerFactory.getLogger(SmbTreeConnection.class); private final CIFSContext ctx; private final SmbTreeConnection delegate; private SmbTreeImpl tree; private volatile boolean treeAcquired; private volatile boolean delegateAcquired; private SmbTransportInternal exclusiveTransport; private boolean nonPooled; private final AtomicLong usageCount = new AtomicLong(); private static final Random RAND = new Random(); /** * @param ctx * */ public SmbTreeConnection ( CIFSContext ctx ) { this.ctx = ctx; this.delegate = null; } /** * @param treeConnection */ public SmbTreeConnection ( SmbTreeConnection treeConnection ) { this.ctx = treeConnection.ctx; this.delegate = treeConnection; } /** * @return the active configuration */ public Configuration getConfig () { return this.ctx.getConfig(); } private synchronized SmbTreeImpl getTree () { SmbTreeImpl t = this.tree; if ( t != null ) { return t.acquire(false); } else if ( this.delegate != null ) { this.tree = this.delegate.getTree(); return this.tree; } return t; } /** * @return */ private synchronized SmbTreeImpl getTreeInternal () { SmbTreeImpl t = this.tree; if ( t != null ) { return t; } if ( this.delegate != null ) { return this.delegate.getTreeInternal(); } return null; } /** * @param t */ private synchronized void switchTree ( SmbTreeImpl t ) { try ( SmbTreeImpl old = getTree() ) { if ( old == t ) { return; } boolean wasAcquired = this.treeAcquired; log.debug("Switching tree"); if ( t != null ) { log.debug("Acquired tree on switch " + t); t.acquire(); this.treeAcquired = true; } else { this.treeAcquired = false; } this.tree = t; if ( old != null ) { if ( wasAcquired ) { // release old.release(true); } } if ( this.delegate != null && this.delegateAcquired ) { log.debug("Releasing delegate"); this.delegateAcquired = false; this.delegate.release(); } } } /** * @return tree connection with increased usage count */ public SmbTreeConnection acquire () { long usage = this.usageCount.incrementAndGet(); if ( log.isTraceEnabled() ) { log.trace("Acquire tree connection " + usage + " " + this); } if ( usage == 1 ) { synchronized ( this ) { try ( SmbTreeImpl t = getTree() ) { if ( t != null ) { if ( !this.treeAcquired ) { if ( log.isDebugEnabled() ) { log.debug("Acquire tree on first usage " + t); } t.acquire(); this.treeAcquired = true; } } } if ( this.delegate != null && !this.delegateAcquired ) { log.debug("Acquire delegate on first usage"); this.delegate.acquire(); this.delegateAcquired = true; } } } return this; } public void release () { long usage = this.usageCount.decrementAndGet(); if ( log.isTraceEnabled() ) { log.trace("Release tree connection " + usage + " " + this); } if ( usage == 0 ) { synchronized ( this ) { try ( SmbTreeImpl t = getTree() ) { if ( this.treeAcquired && t != null ) { if ( log.isDebugEnabled() ) { log.debug("Tree connection no longer in use, release tree " + t); } this.treeAcquired = false; t.release(); } } if ( this.delegate != null && this.delegateAcquired ) { this.delegateAcquired = false; this.delegate.release(); } } SmbTransportInternal et = this.exclusiveTransport; if ( et != null ) { synchronized ( this ) { try { log.debug("Disconnecting exclusive transport"); this.exclusiveTransport = null; this.tree = null; this.treeAcquired = false; et.close(); et.disconnect(false, false); } catch ( Exception e ) { log.error("Failed to close exclusive transport", e); } } } } else if ( usage < 0 ) { log.error("Usage count dropped below zero " + this); throw new RuntimeCIFSException("Usage count dropped below zero"); } } /** * {@inheritDoc} * * @see java.lang.Object#finalize() */ @Override protected void finalize () throws Throwable { if ( isConnected() && this.usageCount.get() != 0 ) { log.warn("Tree connection was not properly released " + this); } } synchronized void disconnect ( boolean inError ) { try ( SmbSessionImpl session = getSession() ) { if ( session == null ) { return; } try ( SmbTransportImpl transport = session.getTransport() ) { synchronized ( transport ) { SmbTreeImpl t = getTreeInternal(); if ( t != null ) { try { t.treeDisconnect(inError, true); } finally { this.tree = null; this.treeAcquired = false; } } else { this.delegate.disconnect(inError); } } } } } <T extends CommonServerMessageBlockResponse> T send ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response, RequestParam... params ) throws CIFSException { return send(loc, request, response, params.length == 0 ? EnumSet.noneOf(RequestParam.class) : EnumSet.copyOf(Arrays.asList(params))); } <T extends CommonServerMessageBlockResponse> T send ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response, Set<RequestParam> params ) throws CIFSException { SmbException last = null; RequestWithPath rpath = ( request instanceof RequestWithPath ) ? (RequestWithPath) request : null; String savedPath = rpath != null ? rpath.getPath() : null; String savedFullPath = rpath != null ? rpath.getFullUNCPath() : null; if ( rpath != null ) { String fullPath = "\\" + loc.getServer() + "\\" + loc.getShare() + loc.getUNCPath(); rpath.setFullUNCPath(null, null, fullPath); } int maxRetries = this.ctx.getConfig().getMaxRequestRetries(); for ( int retries = 1; retries <= maxRetries; retries++ ) { try { return send0(loc, request, response, params); } catch ( SmbException smbe ) { // Retrying only makes sense if the invalid parameter is an tree id. If we have a stale file descriptor // retrying make no sense, as it will never become available again. if ( params.contains(RequestParam.NO_RETRY) || ( ! ( smbe.getCause() instanceof TransportException ) ) && smbe.getNtStatus() != NtStatus.NT_STATUS_INVALID_PARAMETER ) { log.debug("Not retrying", smbe); throw smbe; } log.debug("send", smbe); last = smbe; } catch ( IOException e ) { log.debug("send", e); } // If we get here, we got the 'The Parameter is incorrect' error or a transport exception // Disconnect and try again from scratch. if ( log.isDebugEnabled() ) { log.debug(String.format("Retrying (%d/%d) request %s", retries, maxRetries, request)); } // should we disconnect the transport here? otherwise we make an additional attempt to detect that if the // server closed the connection as a result log.debug("Disconnecting tree on send retry", last); disconnect(true); if ( retries >= maxRetries ) { break; } try { if ( retries != 1 ) { // backoff, but don't delay the first attempt as there are various reasons that can be fixed // immediately Thread.sleep(500 + RAND.nextInt(1000)); } } catch ( InterruptedException e ) { log.debug("interrupted sleep in send", e); } if ( request != null ) { request.reset(); } if ( rpath != null ) { // resolveDfs() and tree.send() modify the request packet. // I want to restore it before retrying. request.reset() // restores almost everything that was modified, except the path. rpath.setPath(savedPath); rpath.setFullUNCPath(rpath.getDomain(), rpath.getServer(), savedFullPath); } if ( response != null ) response.reset(); try ( SmbTreeHandle th = connectWrapException(loc) ) { log.debug("Have new tree connection for retry"); } catch ( SmbException e ) { log.debug("Failed to connect tree on retry", e); last = e; } } if ( last != null ) { log.debug("All attempts have failed, last exception", last); throw last; } throw new SmbException("All attempts failed, but no exception"); } private <T extends CommonServerMessageBlockResponse> T send0 ( SmbResourceLocatorImpl loc, CommonServerMessageBlockRequest request, T response, Set<RequestParam> params ) throws CIFSException, DfsReferral { for ( int limit = 10; limit > 0; limit if ( request instanceof RequestWithPath ) { ensureDFSResolved(loc, (RequestWithPath) request); } try ( SmbTreeImpl t = getTree() ) { if ( t == null ) { throw new CIFSException("Failed to get tree connection"); } ; return t.send(request, response, params); } catch ( DfsReferral dre ) { if ( dre.getData().unwrap(DfsReferralDataInternal.class).isResolveHashes() ) { throw dre; } request.reset(); log.trace("send0", dre); } } throw new CIFSException("Loop in DFS referrals"); } /** * @param loc * @return tree handle * @throws SmbException */ public SmbTreeHandleImpl connectWrapException ( SmbResourceLocatorImpl loc ) throws SmbException { try { return connect(loc); } catch ( UnknownHostException uhe ) { throw new SmbException("Failed to connect to server", uhe); } catch ( SmbException se ) { throw se; } catch ( IOException ioe ) { throw new SmbException("Failed to connect to server", ioe); } } /** * @param loc * @return tree handle * @throws IOException */ public synchronized SmbTreeHandleImpl connect ( SmbResourceLocatorImpl loc ) throws IOException { try ( SmbSessionImpl session = getSession() ) { if ( isConnected() ) { try ( SmbTransportImpl transport = session.getTransport() ) { if ( transport.isDisconnected() || transport.getRemoteHostName() == null ) { /* * Tree/session thinks it is connected but transport disconnected * under it, reset tree to reflect the truth. */ log.debug("Disconnecting failed tree and session"); disconnect(true); } } } if ( isConnected() ) { log.trace("Already connected"); return new SmbTreeHandleImpl(loc, this); } return connectHost(loc, loc.getServerWithDfs()); } } /** * @return whether we have a valid tree connection */ @SuppressWarnings ( "resource" ) public synchronized boolean isConnected () { SmbTreeImpl t = getTreeInternal(); return t != null && t.isConnected(); } /** * * @param loc * @param host * @return tree handle * @throws IOException */ public synchronized SmbTreeHandleImpl connectHost ( SmbResourceLocatorImpl loc, String host ) throws IOException { return connectHost(loc, host, null); } /** * * @param loc * @param host * @param referral * @return tree handle * @throws IOException */ public synchronized SmbTreeHandleImpl connectHost ( SmbResourceLocatorImpl loc, String host, DfsReferralData referral ) throws IOException { String targetDomain = null; try ( SmbTreeImpl t = getTree() ) { if ( t != null ) { if ( log.isDebugEnabled() ) { log.debug("Tree is " + t); } if ( loc.getShare().equals(t.getShare()) ) { try ( SmbSessionImpl session = t.getSession() ) { targetDomain = session.getTargetDomain(); if ( !session.isFailed() ) { try ( SmbTransportImpl trans = session.getTransport(); SmbTreeImpl ct = connectTree(loc, host, t.getShare(), trans, t, null) ) { switchTree(ct); return new SmbTreeHandleImpl(loc, this); } } log.debug("Session no longer valid"); } } } } String hostName = loc.getServerWithDfs(); String path = ( loc.getType() == SmbConstants.TYPE_SHARE || loc.getUNCPath() == null || "\\".equals(loc.getUNCPath()) ) ? null : loc.getUNCPath(); String share = loc.getShare(); DfsReferralData start = referral != null ? referral : this.ctx.getDfs().resolve(this.ctx, hostName, loc.getShare(), path); DfsReferralData dr = start; IOException last = null; do { if ( dr != null ) { targetDomain = dr.getDomain(); host = dr.getServer().toLowerCase(Locale.ROOT); share = dr.getShare(); } try { if ( this.nonPooled ) { if ( log.isDebugEnabled() ) { log.debug("Using exclusive transport for " + this); } this.exclusiveTransport = this.ctx.getTransportPool() .getSmbTransport(this.ctx, host, loc.getPort(), true, loc.shouldForceSigning()).unwrap(SmbTransportInternal.class); SmbTransportInternal trans = this.exclusiveTransport; try ( SmbSessionInternal smbSession = trans.getSmbSession(this.ctx, host, targetDomain).unwrap(SmbSessionInternal.class); SmbTreeImpl uct = smbSession.getSmbTree(share, null).unwrap(SmbTreeImpl.class); SmbTreeImpl ct = connectTree(loc, host, share, trans, uct, dr) ) { if ( dr != null ) { ct.setTreeReferral(dr); if ( dr != start ) { dr.unwrap(DfsReferralDataInternal.class).replaceCache(); } } switchTree(ct); return new SmbTreeHandleImpl(loc, this); } } try ( SmbTransportInternal trans = this.ctx.getTransportPool() .getSmbTransport(this.ctx, host, loc.getPort(), false, loc.shouldForceSigning()).unwrap(SmbTransportInternal.class); SmbSessionInternal smbSession = trans.getSmbSession(this.ctx, host, targetDomain).unwrap(SmbSessionInternal.class); SmbTreeImpl uct = smbSession.getSmbTree(share, null).unwrap(SmbTreeImpl.class); SmbTreeImpl ct = connectTree(loc, host, share, trans, uct, dr) ) { if ( dr != null ) { ct.setTreeReferral(dr); if ( dr != start ) { dr.unwrap(DfsReferralDataInternal.class).replaceCache(); } } switchTree(ct); return new SmbTreeHandleImpl(loc, this); } } catch ( IOException e ) { last = e; log.warn("Referral failed, trying next", e); } if ( dr != null ) { dr = dr.next(); } } while ( dr != start ); throw last; } /** * @param loc * @param addr * @param trans * @param t * @throws CIFSException */ private SmbTreeImpl connectTree ( SmbResourceLocator loc, String addr, String share, SmbTransportInternal trans, SmbTreeImpl t, DfsReferralData referral ) throws CIFSException { if ( log.isDebugEnabled() && trans.isSigningOptional() && !loc.isIPC() && !this.ctx.getConfig().isSigningEnforced() ) { log.debug("Signatures for file enabled but not required " + this); } if ( referral != null ) { t.markDomainDfs(); } try { if ( log.isTraceEnabled() ) { log.trace("doConnect: " + addr); } t.treeConnect(null, null); return t.acquire(); } catch ( SmbAuthException sae ) { log.debug("Authentication failed", sae); if ( loc.isIPC() ) { // IPC$ - try "anonymous" credentials try ( SmbSessionInternal s = trans.getSmbSession(this.ctx.withAnonymousCredentials()).unwrap(SmbSessionInternal.class); SmbTreeImpl tr = s.getSmbTree(null, null).unwrap(SmbTreeImpl.class) ) { tr.treeConnect(null, null); return tr.acquire(); } } else if ( this.ctx.renewCredentials(loc.getURL().toString(), sae) ) { log.debug("Trying to renew credentials after auth error"); try ( SmbSessionInternal s = trans.getSmbSession(this.ctx).unwrap(SmbSessionInternal.class); SmbTreeImpl tr = s.getSmbTree(share, null).unwrap(SmbTreeImpl.class) ) { if ( referral != null ) { tr.markDomainDfs(); } tr.treeConnect(null, null); return tr.acquire(); } } else { throw sae; } } } SmbResourceLocator ensureDFSResolved ( SmbResourceLocatorImpl loc ) throws CIFSException { return ensureDFSResolved(loc, null); } SmbResourceLocator ensureDFSResolved ( SmbResourceLocatorImpl loc, RequestWithPath request ) throws CIFSException { if ( request instanceof SmbComClose ) return loc; for ( int retries = 0; retries < 1 + this.ctx.getConfig().getMaxRequestRetries(); retries++ ) { try { return resolveDfs0(loc, request); } catch ( SmbException smbe ) { // The connection may have been dropped? if ( smbe.getNtStatus() != NtStatus.NT_STATUS_NOT_FOUND && ! ( smbe.getCause() instanceof TransportException ) ) { throw smbe; } log.debug("resolveDfs", smbe); } // If we get here, we apparently have a bad connection. // Disconnect and try again. if ( log.isDebugEnabled() ) { log.debug("Retrying (" + retries + ") resolveDfs: " + request); } log.debug("Disconnecting tree on DFS retry"); disconnect(true); try { Thread.sleep(500 + RAND.nextInt(5000)); } catch ( InterruptedException e ) { log.debug("resolveDfs", e); } try ( SmbTreeHandle th = connectWrapException(loc) ) {} } return loc; } private SmbResourceLocator resolveDfs0 ( SmbResourceLocatorImpl loc, RequestWithPath request ) throws CIFSException { try ( SmbTreeHandleImpl th = connectWrapException(loc); SmbSessionImpl session = th.getSession(); SmbTransportImpl transport = session.getTransport(); SmbTreeImpl t = getTree() ) { transport.ensureConnected(); String rpath = request != null ? request.getPath() : loc.getUNCPath(); String rfullpath = request != null ? request.getFullUNCPath() : ( '\\' + loc.getServer() + '\\' + loc.getShare() + loc.getUNCPath() ); if ( !t.isPossiblyDfs() ) { if ( t.isInDomainDfs() ) { // need to adjust request path DfsReferralData dr = t.getTreeReferral(); if ( dr != null ) { if ( log.isDebugEnabled() ) { log.debug(String.format("Need to adjust request path %s (full: %s) -> %s", rpath, rfullpath, dr)); } String dunc = loc.handleDFSReferral(dr, rpath); if ( request != null ) { request.setPath(dunc); } return loc; } // fallthrough to normal handling log.debug("No tree referral but in DFS"); } else { log.trace("Not in DFS"); return loc; } } if ( request != null ) { request.setFullUNCPath(session.getTargetDomain(), session.getTargetHost(), rfullpath); } // for standalone DFS we could be checking for a referral here, too DfsReferralData dr = this.ctx.getDfs().resolve(this.ctx, loc.getServer(), loc.getShare(), loc.getUNCPath()); if ( dr != null ) { if ( log.isDebugEnabled() ) { log.debug("Resolved " + rfullpath + " -> " + dr); } String dunc = loc.handleDFSReferral(dr, rpath); if ( request != null ) { request.setPath(dunc); } if ( !t.getShare().equals(dr.getShare()) ) { // this should only happen for standalone roots or if the DC/domain root lookup failed IOException last; DfsReferralData start = dr; do { if ( log.isDebugEnabled() ) { log.debug("Need to switch tree for " + dr); } try ( SmbTreeHandleImpl nt = connectHost(loc, session.getTargetHost(), dr) ) { log.debug("Switched tree"); return loc; } catch ( IOException e ) { log.debug("Failed to connect tree", e); last = e; } dr = dr.next(); } while ( dr != start ); throw new CIFSException("All referral tree connections failed", last); } return loc; } else if ( t.isInDomainDfs() && ! ( request instanceof NtTransQuerySecurityDesc ) && ! ( request instanceof SmbComClose ) && ! ( request instanceof SmbComFindClose2 ) ) { if ( log.isDebugEnabled() ) { log.debug("No referral available for " + rfullpath); } throw new CIFSException("No referral but in domain DFS " + rfullpath); } else { log.trace("Not in DFS"); return loc; } } } /** * Use a exclusive connection for this tree * * If an exclusive connection is used the caller must make sure that the tree handle is kept alive, * otherwise the connection will be disconnected once the usage drops to zero. * * @param np * whether to use an exclusive connection */ void setNonPooled ( boolean np ) { this.nonPooled = np; } /** * @return the currently connected tid */ @SuppressWarnings ( "resource" ) public long getTreeId () { SmbTreeImpl t = getTreeInternal(); if ( t == null ) { return -1; } return t.getTreeNum(); } /** * * Only call this method while holding a tree handle * * @return session that this file has been loaded through */ @SuppressWarnings ( "resource" ) public SmbSessionImpl getSession () { SmbTreeImpl t = getTreeInternal(); if ( t != null ) { return t.getSession(); } return null; } /** * * Only call this method while holding a tree handle * * @param cap * @return whether the capability is available * @throws SmbException */ public boolean hasCapability ( int cap ) throws SmbException { try ( SmbSessionImpl s = getSession() ) { if ( s != null ) { try ( SmbTransportImpl transport = s.getTransport() ) { return transport.hasCapability(cap); } } throw new SmbException("Not connected"); } } /** * Only call this method while holding a tree handle * * @return the connected tree type */ public int getTreeType () { try ( SmbTreeImpl t = getTree() ) { return t.getTreeType(); } } /** * * Only call this method while holding a tree handle * * @return the share we are connected to */ public String getConnectedShare () { try ( SmbTreeImpl t = getTree() ) { return t.getShare(); } } /** * * Only call this method while holding a tree handle * * @param other * @return whether the connection refers to the same tree */ public boolean isSame ( SmbTreeConnection other ) { try ( SmbTreeImpl t1 = getTree(); SmbTreeImpl t2 = other.getTree() ) { return t1.equals(t2); } } }
package jp.afw.plugin; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import jp.afw.business.manager.AbstractManager; import jp.afw.core.util.StringUtility; import jp.afw.persistence.ConfigurationFormatException; import jp.afw.persistence.configuration.Configuration; import jp.afw.persistence.configuration.ConfigurationSupport; import jp.afw.persistence.configuration.InputStreamConfiguration; import jp.afw.persistence.context.Context; import jp.afw.persistence.context.ContextSupport; import jp.afw.persistence.entity.Entity; import org.apache.commons.digester3.Digester; import org.xml.sax.SAXException; /** * * * @since 1.0.0 * @version 1.0.0 12/06/07 * @author Kawakicchi */ public final class PluginManager extends AbstractManager { /** * Instance */ private static final PluginManager INSTANCE = new PluginManager(); /** * plugin list */ private List<PluginEntity> plugins; /** * * <p> * * </p> */ private PluginManager() { super(PluginManager.class); plugins = new ArrayList<PluginEntity>(); } public static void initialize() { INSTANCE.doInitialize(); } public static void destroy() { INSTANCE.doDestory(); } /** * * * @param file * @param context * @throws PluginServiceException * @throws ConfigurationFormatException * @throws IOException */ public static void load(final String file, final Context context) throws PluginServiceException, ConfigurationFormatException, IOException { INSTANCE.doLoad(context.getResourceAsStream(file), context); } /** * * * @param stream * @param context * @throws PluginServiceException * @throws ConfigurationFormatException * @throws IOException */ public static void load(final InputStream stream, final Context context) throws PluginServiceException, ConfigurationFormatException, IOException { INSTANCE.doLoad(stream, context); } /** * * * @return */ public static List<PluginEntity> getPluginList() { return INSTANCE.doGetPluginList(); } private void doInitialize() { synchronized (plugins) { } } private void doDestory() { synchronized (plugins) { for (PluginEntity plugin : plugins) { try { plugin.getPlugin().destroy(); } catch (PluginServiceException ex) { error(ex); } } plugins.clear(); } } /** * * * @param aStream * @param aContext * @throws PluginServiceException * @throws ConfigurationFormatException * @throws IOException */ @SuppressWarnings("unchecked") private void doLoad(final InputStream aStream, final Context aContext) throws PluginServiceException, ConfigurationFormatException, IOException { synchronized (plugins) { // Load plugin xml file. List<PluginXmlEntity> pluginList; try { Digester digester = new Digester(); digester.addObjectCreate("azuki/plugins", ArrayList.class); digester.addObjectCreate("azuki/plugins/plugin", PluginXmlEntity.class); digester.addSetProperties("azuki/plugins/plugin"); digester.addSetNext("azuki/plugins/plugin", "add"); pluginList = digester.parse(aStream); } catch (SAXException ex) { error(ex); throw new ConfigurationFormatException(ex); } catch (IOException ex) { error(ex); throw ex; } try { if (null != pluginList) { for (int i = 0; i < pluginList.size(); i++) { PluginXmlEntity p = pluginList.get(i); Class<Plugin> clazz = (Class<Plugin>) Class.forName(p.getPlugin()); Plugin plugin = clazz.newInstance(); PluginEntity pe = new PluginEntity(); pe.name = p.getName(); pe.config = p.getConfig(); pe.plugin = plugin; plugins.add(pe); } } } catch (ClassNotFoundException ex) { error(ex); throw new PluginServiceException(ex); } catch (IllegalAccessException ex) { error(ex); throw new PluginServiceException(ex); } catch (InstantiationException ex) { error(ex); throw new PluginServiceException(ex); } // Support for (int i = 0; i < plugins.size(); i++) { Plugin plugin = plugins.get(i).getPlugin(); // Support context if (plugin instanceof ContextSupport) { ((ContextSupport) plugin).setContext(aContext); } // Support configuration if (plugin instanceof ConfigurationSupport) { String config = plugins.get(i).config; if (StringUtility.isNotEmpty(config)) { Configuration configuration = new InputStreamConfiguration(aContext.getResourceAsStream(config)); ((ConfigurationSupport) plugin).setConfiguration(configuration); } else { warn("Not setting config file.[" + plugins.get(i).getName() + "]"); } } } // initialize for (int i = 0; i < plugins.size(); i++) { Plugin plugin = plugins.get(i).getPlugin(); plugin.initialize(); } // load for (int i = 0; i < plugins.size(); i++) { Plugin plugin = plugins.get(i).getPlugin(); plugin.load(); } } } /** * * * @return */ private List<PluginEntity> doGetPluginList() { return plugins; } /** * * * @since 1.0.0 * @version 1.0.0 12/07/16 * @author Kawakicchi */ public static class PluginEntity implements Entity { private String name; private Plugin plugin; /** * config */ private String config; private PluginEntity() { } /** * * * @return */ public String getName() { return name; } /** * * * @return */ public Plugin getPlugin() { return plugin; } @Override public boolean isEmpty() { return false; } } /** * XML * * @since 1.0.0 * @version 1.0.0 12/06/14 * @author Kawakicchi */ public static class PluginXmlEntity implements Entity { private String name; private String clazz; private String config; /** * * * @param aName */ public void setName(final String aName) { name = aName; } /** * * * @param aClass */ public void setPlugin(final String aClass) { clazz = aClass; } /** * * * @param aConfig */ public void setConfig(final String aConfig) { config = aConfig; } /** * * * @return */ public String getName() { return name; } /** * * * @return */ public String getPlugin() { return clazz; } /** * * * @return */ public String getConfig() { return config; } @Override public boolean isEmpty() { if (StringUtility.isEmpty(name)) { return true; } if (StringUtility.isEmpty(clazz)) { return true; } if (StringUtility.isEmpty(config)) { return true; } return false; } } }
package me.coley.recaf.util; import com.eclipsesource.json.*; import com.google.common.base.Charsets; import com.google.common.io.Resources; import me.coley.recaf.Logging; import me.coley.recaf.Recaf; import me.coley.recaf.config.impl.ConfUpdate; import me.coley.recaf.ui.component.UpdatePrompt; import javax.swing.*; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.jar.*; /** * Ensures execution on the latest version. * * @author Matt */ @SuppressWarnings("unused") public class Updater { private final static String API_LATEST = "https://api.github.com/repos/Col-E/Recaf/releases/latest"; /** * Download and execute the latest release of Recaf. * * @param args * Launch arguments to pass. */ public static void updateFromRelease(String[] args) { // check if updates should occur if (!ConfUpdate.instance().shouldCheck()) { return; } try { ConfUpdate.instance().lastCheck = System.currentTimeMillis(); // get self data SelfReference self = SelfReference.get(); if (!self.isJar()) { // If the execuatable context is not a runnable jar, do not // attempt to update. // Methods to do so exist should this functionality be wanted in // the future. return; } String selfVersion = Recaf.VERSION; // get latest data URL updateURL = new URL(API_LATEST); String content = Resources.asCharSource(updateURL, Charsets.UTF_8).read(); JsonObject updateJson = Json.parse(content).asObject(); // compare versions String latestVersion = updateJson.getString("tag_name", "1.0.0"); String updateNotes = updateJson.getString("body", "#Error\nCould not fetch update notes."); if (isOutdated(selfVersion, latestVersion)) { if (!UpdatePrompt.consent(selfVersion, latestVersion, updateNotes)) { return; } Logging.info(Lang.get("update.outdated")); JsonArray assets = updateJson.get("assets").asArray(); for (JsonValue assetValue : assets.values()) { JsonObject assetObj = assetValue.asObject(); String file = assetObj.getString("name", "invalid"); if (!file.endsWith(".jar")) { // this is not the right attachment continue; } String fileURL = assetObj.getString("browser_download_url", null); if (fileURL == null) { // this shouldn't happen, but just in case. continue; } byte[] updateContents = Resources.asByteSource(new URL(fileURL)).read(); FileIO.writeFile(file, updateContents); Logging.error(Lang.get("update.complete")); executeUpdated(file, args); return; } Logging.warn(Lang.get("update.fail.nodownload")); return; } } catch (URISyntaxException e) { Logging.error(Lang.get("update.fail.resolve")); } catch (IOException e) { Logging.error(Lang.get("update.fail.jarread")); } catch (Exception e) { Logging.error(Lang.get("update.fail.unknown") + e.getMessage()); } Logging.fine(Lang.get("update.updated")); } /** * Update self with proper dependencies for Java 11 and rerun. * @param args * Launch arguments to pass. */ public static void updateViaJdk11Patch(String[] args) { File patched = new File(String.format("recaf-%s-patched.jar", Recaf.VERSION)); // Generate patched jar with proper dependencies try { if (!patched.exists()) { generatePatched(patched); } } catch(Exception ex) { ex.printStackTrace(); err("Failed auto-patch", ex.toString()); } // Rerun with dependencies try { executeUpdated(patched.getAbsolutePath(), args); } catch(Exception ex) { ex.printStackTrace(); err("Failed re-run", ex.toString()); } } private static void generatePatched(File patched) throws IOException, URISyntaxException { SelfReference self = SelfReference.get(); if(!self.isJar()) { err("Failed auto-patch", "Could not update self, as was not running as a jar-file."); return; } String selfURL = self.getFile().toURI().toURL().toString().replace("%", "%%"); String[] dependencies = new String[] { selfURL, "http://central.maven.org/maven2/org/controlsfx/controlsfx/11.0.0/controlsfx-11.0.0.jar", "http://central.maven.org/maven2/org/openjfx/javafx-web/11.0.2/javafx-web-11.0.2-%s.jar", "http://central.maven.org/maven2/org/openjfx/javafx-media/11.0.2/javafx-media-11.0.2-%s.jar", "http://central.maven.org/maven2/org/openjfx/javafx-controls/11.0.2/javafx-controls-11.0.2-%s.jar", "http://central.maven.org/maven2/org/openjfx/javafx-graphics/11.0.2/javafx-graphics-11.0.2-%s.jar", "http://central.maven.org/maven2/org/openjfx/javafx-base/11.0.2/javafx-base-11.0.2-%s.jar" }; // Items to blacklist copying from the self-jar Collection<String> blacklist = Arrays.asList("controlsfx", "org/controlsfx", "impl"); // master local containing all dependencies Set<String> depLocalNames = new HashSet<>(); JarOutputStream jos = new JarOutputStream(new FileOutputStream(patched)); String os = getOSType(); for (String dependency : dependencies) { URL depURL = new URL(String.format(dependency, os)); File depTemp = File.createTempFile("recaf","dependency"); Files.copy(depURL.openStream(), depTemp.toPath(), StandardCopyOption.REPLACE_EXISTING); if (depTemp.length() == 0) { continue; } // Copy temp dependency into master local JarFile jarFile = new JarFile(depTemp); Enumeration<JarEntry> jarEntries = jarFile.entries(); while(jarEntries.hasMoreElements()) { JarEntry je = jarEntries.nextElement(); String name = je.getName(); // Skip existing paths if (depLocalNames.contains(name)) continue; // Skip self-blacklisted items if (dependency.equals(selfURL) && blacklist.stream().anyMatch(b -> name.startsWith(b))) continue; // write to master jos.putNextEntry(je); try (InputStream is = jarFile.getInputStream(je)) { byte[] data = Streams.from(is); jos.write(data, 0, data.length); } depLocalNames.add(name); jos.closeEntry(); } jarFile.close(); depTemp.delete(); } jos.close(); } /** * Rerun recaf with updated version. * * @param file * Filename of new version. * @param args * Command line args to pass. * @throws IOException * Thrown if the process cannot be started. */ private static void executeUpdated(String file, String[] args) throws IOException { String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; File currentJar = new File(file); // Build process: java -jar recaf.jar -args List<String> procArgs = new ArrayList<>(); procArgs.add(javaBin); procArgs.add("-jar"); procArgs.add(currentJar.getPath()); Collections.addAll(procArgs, args); // run process and terminate current new ProcessBuilder(procArgs).start(); System.out.println("Rerunning"); System.exit(0); } /** * @param self * Current version. * @param latest * Latest online version. * @return Is current is behind latest. */ private static boolean isOutdated(String self, String latest) { try { String[] arrSelf = self.split("\\."); String[] arrLatest = latest.split("\\."); if (arrSelf.length == arrLatest.length) { for (int i = 0; i < arrSelf.length; i++) { int iSelf = Integer.parseInt(arrSelf[i]); int iLatest = Integer.parseInt(arrLatest[i]); if (iSelf == iLatest) { // do nothing continue; } else { return iSelf < iLatest; } } } } catch (Exception e) { e.printStackTrace(); } return false; } private static String getOSType() { String s = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (s.contains("win")) { return "win"; } if (s.contains("mac") || s.contains("osx")) { return "mac"; } return "linux"; } private static void err(String title, String msg) { System.err.println(msg); JOptionPane.showMessageDialog(null, msg, title, JOptionPane.ERROR_MESSAGE); } }
package net.imagej.legacy; import ij.Executer; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.Macro; import ij.Menus; import ij.WindowManager; import ij.gui.ImageWindow; import ij.gui.Toolbar; import ij.io.Opener; import ij.macro.Interpreter; import ij.plugin.Commands; import ij.plugin.PlugIn; import ij.plugin.filter.PlugInFilter; import ij.plugin.filter.PlugInFilterRunner; import java.awt.Component; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Image; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.Window; import java.awt.image.ImageProducer; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.swing.SwingUtilities; import net.imagej.display.ImageDisplay; import net.imagej.patcher.LegacyHooks; import org.scijava.AbstractContextual; import org.scijava.Context; import org.scijava.MenuEntry; import org.scijava.MenuPath; import org.scijava.event.EventHandler; import org.scijava.log.LogService; import org.scijava.module.ModuleInfo; import org.scijava.platform.event.AppAboutEvent; import org.scijava.platform.event.AppOpenFilesEvent; import org.scijava.platform.event.AppPreferencesEvent; import org.scijava.platform.event.AppQuitEvent; import org.scijava.plugin.Parameter; import org.scijava.script.ScriptService; import org.scijava.util.ClassUtils; /** * A helper class to interact with ImageJ 1.x. * <p> * The DefaultLegacyService needs to patch ImageJ 1.x's classes before they are * loaded. Unfortunately, this is tricky: if the DefaultLegacyService already * uses those classes, it is a matter of luck whether we can get the patches in * before those classes are loaded. * </p> * <p> * Therefore, we put as much interaction with ImageJ 1.x as possible into this * class and keep a reference to it in the DefaultLegacyService. * </p> * * @author Johannes Schindelin */ public class IJ1Helper extends AbstractContextual { /** A reference to the legacy service, just in case we need it. */ private final DefaultLegacyService legacyService; @Parameter private LogService log; /** Whether we are in the process of forcibly shutting down ImageJ1. */ private boolean disposing; public IJ1Helper(final DefaultLegacyService legacyService) { setContext(legacyService.getContext()); this.legacyService = legacyService; } public void initialize() { // initialize legacy ImageJ application final ImageJ ij1 = IJ.getInstance(); if (Menus.getCommands() == null) { IJ.runPlugIn("ij.IJ.init", ""); } if (ij1 != null) { // NB: *Always* call System.exit(0) when quitting: // - In the case of batch mode, the JVM needs to terminate at the // conclusion of the macro/script, regardless of the actions performed // by that macro/script. // - In the case of GUI mode, the JVM needs to terminate when the user // quits the program because ImageJ1 has many plugins which do not // properly clean up their resources. This is a vicious cycle: // ImageJ1's main method sets exitWhenQuitting to true, which has // historically masked the problems with these plugins. So we have // little choice but to continue this tradition, at least with the // legacy ImageJ1 user interface. ij1.exitWhenQuitting(true); // make sure that the Event Dispatch Thread's class loader is set SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Thread.currentThread().setContextClassLoader(IJ.getClassLoader()); } }); final LegacyImageMap imageMap = legacyService.getImageMap(); for (int i = 1; i <= WindowManager.getImageCount(); i++) { imageMap.registerLegacyImage(WindowManager.getImage(i)); } // set icon and title of main window (which are instantiated before the // initializer is called) try { final LegacyHooks hooks = (LegacyHooks) IJ.class.getField("_hooks").get(null); ij1.setTitle(hooks.getAppName()); final URL iconURL = hooks.getIconURL(); if (iconURL != null) try { final Object producer = iconURL.getContent(); final Image image = ij1.createImage((ImageProducer) producer); ij1.setIconImage(image); if (IJ.isMacOSX()) try { // NB: We also need to set the dock icon final Class<?> clazz = Class.forName("com.apple.eawt.Application"); final Object app = clazz.getMethod("getApplication").invoke(null); clazz.getMethod("setDockIconImage", Image.class).invoke(app, image); } catch (final Throwable t) { t.printStackTrace(); } } catch (final IOException e) { IJ.handleException(e); } } catch (final Throwable t) { t.printStackTrace(); } // FIXME: handle window location via LegacyUI // This is necessary because the ImageJ 1.x window will not set its location // if created with mode NO_SHOW, which is exactly how it is created right // now by the legacy layer. This is a work-around by ensuring the preferred // (e.g. saved and loaded) location is current at the time the IJ1Helper // is initialized. Ideally we would like to handle positioning via // the LegacyUI though, so that we can restore positions on secondary // monitors and such. ij1.setLocation(ij1.getPreferredLocation()); } } /** * Forcibly shuts down ImageJ1, with no user interaction or opportunity to * cancel. If ImageJ1 is not currently initialized, or if ImageJ1 is already * in the process of quitting (i.e., {@link ij.ImageJ#quitting()} returns * {@code true}), then this method does nothing. */ public synchronized void dispose() { final ImageJ ij = IJ.getInstance(); if (ij == null) return; // no ImageJ1 to dispose if (ij.quitting()) return; // ImageJ1 is already on its way out disposing = true; closeImageWindows(); disposeNonImageWindows(); // quit legacy ImageJ on the same thread ij.exitWhenQuitting(false); // do *not* quit the JVM! ij.run(); disposing = false; } /** Whether we are in the process of forcibly shutting down ImageJ1. */ public boolean isDisposing() { return disposing; } /** Add name aliases for ImageJ1 classes to the ScriptService. */ public void addAliases(final ScriptService scriptService) { scriptService.addAlias(ImagePlus.class); } public boolean isVisible() { final ImageJ ij = IJ.getInstance(); if (ij == null) return false; return ij.isVisible(); } private boolean batchMode; void setBatchMode(boolean batch) { Interpreter.batchMode = batch; batchMode = batch; } void invalidateInstance() { try { final Method cleanup = IJ.class.getDeclaredMethod("cleanup"); cleanup.setAccessible(true); cleanup.invoke(null); } catch (Throwable t) { t.printStackTrace(); log.error(t); } } public void setVisible(boolean toggle) { if (batchMode) return; final ImageJ ij = IJ.getInstance(); if (ij != null) { if (toggle) ij.pack(); ij.setVisible(toggle); } // hide/show the legacy ImagePlus instances final LegacyImageMap imageMap = legacyService.getImageMap(); for (final ImagePlus imp : imageMap.getImagePlusInstances()) { final ImageWindow window = imp.getWindow(); if (window != null) window.setVisible(toggle); } } public void syncActiveImage(final ImageDisplay activeDisplay) { final LegacyImageMap imageMap = legacyService.getImageMap(); final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay); // NB - old way - caused probs with 3d Project // WindowManager.setTempCurrentImage(activeImagePlus); // NB - new way - test thoroughly if (activeImagePlus == null) WindowManager.setCurrentWindow(null); else WindowManager.setCurrentWindow(activeImagePlus.getWindow()); } public void setKeyDown(int keyCode) { IJ.setKeyDown(keyCode); } public void setKeyUp(int keyCode) { IJ.setKeyUp(keyCode); } public boolean hasInstance() { return IJ.getInstance() != null; } /** Gets the version of ImageJ 1.x. */ public String getVersion() { // NB: We cannot hardcode a reference to ImageJ.VERSION. Java often inlines // string constants at compile time. This means that if a different version // of ImageJ 1.x is used at runtime, this method could return an incorrect // value. Calling IJ.getVersion() would be more reliable, except that we // override its behavior to return LegacyHooks#getAppVersion(). So instead, // we resort to referencing the ImageJ#VERSION constant via reflection. try { final Field field = ImageJ.class.getField("VERSION"); if (field != null) { final Object version = field.get(null); if (version != null) return version.toString(); } } catch (NoSuchFieldException exc) { log.error(exc); } catch (IllegalAccessException exc) { log.error(exc); } return "Unknown"; } public boolean isMacintosh() { return IJ.isMacintosh(); } public void setStatus(String message) { IJ.showStatus(message); } public void setProgress(int val, int max) { IJ.showProgress(val, max); } public Component getToolBar() { return Toolbar.getInstance(); } public ImageJ getIJ() { if (hasInstance()) { return IJ.getInstance(); } return null; } public ClassLoader getClassLoader() { return IJ.getClassLoader(); } public void showMessage(String title, String message) { IJ.showMessage(title, message); } public boolean showMessageWithCancel(String title, String message) { return IJ.showMessageWithCancel(title, message); } public String commandsName() { return Commands.class.getName(); } public void updateRecentMenu(final String path) { Menu menu = Menus.getOpenRecentMenu(); if (menu == null) return; int n = menu.getItemCount(); int index = -1; for (int i=0; i<n; i++) { if (menu.getItem(i).getLabel().equals(path)) { index = i; break; } } // Move to most recent if (index > 0) { final MenuItem item = menu.getItem(index); menu.remove(index); menu.insert(item, 0); } // not found, so replace oldest else if (index < 0) { int count = menu.getItemCount(); if (count >= Menus.MAX_OPEN_RECENT_ITEMS) { menu.remove(count - 1); } final MenuItem item = new MenuItem(path); final ImageJ instance = IJ.getInstance(); if (instance != null) item.addActionListener(instance); menu.insert(item, 0); } // if index was 0, already at the head so do nothing } /** * Gets a macro parameter of type <i>boolean</i>. * * @param label * the name of the macro parameter * @param defaultValue * the default value * @return the boolean value */ public static boolean getMacroParameter(String label, boolean defaultValue) { return getMacroParameter(label) != null || defaultValue; } /** * Gets a macro parameter of type <i>double</i>. * * @param label * the name of the macro parameter * @param defaultValue * the default value * @return the double value */ public static double getMacroParameter(String label, double defaultValue) { String value = Macro.getValue(Macro.getOptions(), label, null); return value != null ? Double.parseDouble(value) : defaultValue; } /** * Gets a macro parameter of type {@link String}. * * @param label * the name of the macro parameter * @param defaultValue * the default value * @return the value */ public static String getMacroParameter(String label, String defaultValue) { return Macro.getValue(Macro.getOptions(), label, defaultValue); } /** * Gets a macro parameter of type {@link String}. * * @param label * the name of the macro parameter * @return the value, <code>null</code> if the parameter was not specified */ public static String getMacroParameter(String label) { return Macro.getValue(Macro.getOptions(), label, null); } /** Gets the SciJava application context linked to the ImageJ 1.x instance. */ public static Context getLegacyContext() { // NB: This call instantiates a Context if there is none. // IJ.runPlugIn() will be intercepted by the legacy hooks if they are // installed and return the current Context. // If no legacy hooks are installed, ImageJ 1.x will instantiate the Context // using the PluginClassLoader and the LegacyService will install the legacy // hooks. final Object o = IJ.runPlugIn("org.scijava.Context", ""); if (o == null) return null; if (!(o instanceof Context)) { throw new IllegalStateException("Unexpected type of context: " + o.getClass().getName()); } return (Context) o; } /** * Partial replacement for ImageJ 1.x's MacAdapter. * <p> * ImageJ 1.x has a MacAdapter plugin that intercepts MacOSX-specific events * and handles them. The way it does it is deprecated now, however, and * unfortunately incompatible with the way ImageJ 2's platform service does * it. * </p> * <p> * This class implements the same functionality as the MacAdapter, but in a * way that is compatible with ImageJ 2's platform service. * </p> * <p> * Note that the {@link AppAboutEvent}, {@link AppPreferencesEvent} and * {@link AppQuitEvent} are handled separately, by the * {@link LegacyAppEventService}. See also {@link IJ1Helper#appAbout}, * {@link IJ1Helper#appPrefs} and {@link IJ1Helper#appQuit}. * </p> * * @author Johannes Schindelin */ private static class LegacyEventDelegator extends AbstractContextual { @Parameter(required = false) private LegacyService legacyService; // -- MacAdapter re-implementations -- /** @param event */ @EventHandler private void onEvent(final AppOpenFilesEvent event) { if (isLegacyMode()) { final List<File> files = new ArrayList<File>(event.getFiles()); for (final File file : files) { new Opener().openAndAddToRecent(file.getAbsolutePath()); } } } private boolean isLegacyMode() { // We call setContext() indirectly from DefaultLegacyService#initialize, // therefore legacyService might still be null at this point even if the // context knows a legacy service now. if (legacyService == null) { final Context context = getContext(); if (context != null) legacyService = context.getService(LegacyService.class); } return legacyService != null && legacyService.isLegacyMode(); } } private static LegacyEventDelegator eventDelegator; public static void subscribeEvents(final Context context) { if (context == null) { eventDelegator = null; } else { eventDelegator = new LegacyEventDelegator(); eventDelegator.setContext(context); } } static void run(Class<?> c) { IJ.resetEscape(); if (PlugIn.class.isAssignableFrom(c)) { try { final PlugIn plugin = (PlugIn) c.newInstance(); plugin.run(""); } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } return; } if (PlugInFilter.class.isAssignableFrom(c)) { try { final PlugInFilter plugin = (PlugInFilter) c.newInstance(); ImagePlus image = WindowManager.getCurrentImage(); if (image != null && image.isLocked()) { if (!IJ.showMessageWithCancel("Unlock image?", "The image '" + image.getTitle() + "'appears to be locked... Unlock?")) return; image.unlock(); } new PlugInFilterRunner(plugin, c.getName(), ""); } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } return; } throw new RuntimeException("TODO: construct class loader"); } private boolean menuInitialized; /** * Adds legacy-compatible scripts and commands to the ImageJ1 menu structure. */ public synchronized void addMenuItems() { if (menuInitialized) return; final Map<String, ModuleInfo> modules = legacyService.getScriptsAndNonLegacyCommands(); @SuppressWarnings("unchecked") final Hashtable<String, String> ij1Commands = Menus.getCommands(); final ImageJ ij1 = getIJ(); final IJ1MenuWrapper wrapper = ij1 == null ? null : new IJ1MenuWrapper(ij1); class Item implements Comparable<Item> { private double weight; private MenuPath path; private String name, identifier; private ModuleInfo info; @Override public int compareTo(Item o) { if (weight != o.weight) return Double.compare(weight, o.weight); return compare(path, o.path); } public int compare(final MenuPath a, final MenuPath b) { int i = 0; while (i < a.size() && i < b.size()) { final MenuEntry a2 = a.get(i), b2 = b.get(i); int diff = Double.compare(a.get(i).getWeight(), b.get(i).getWeight()); if (diff != 0) return diff; diff = a2.getName().compareTo(b2.getName()); if (diff != 0) return diff; i++; } return 0; } } final List<Item> items = new ArrayList<Item>(); for (final Entry<String, ModuleInfo> entry : modules.entrySet()) { final String key = entry.getKey(); final ModuleInfo info = entry.getValue(); final MenuEntry leaf = info.getMenuPath().getLeaf(); if (leaf == null) continue; final MenuPath path = info.getMenuPath(); final String name = leaf.getName(); final Item item = new Item(); item.weight = leaf.getWeight(); item.path = path; item.name = name; item.identifier = key; item.info = info; items.add(item); } // sort by menu weight, then alphabetically Collections.sort(items); for (final Item item : items) { if (ij1Commands.containsKey(item.name)) { log.info("Overriding " + item.name + "; identifier: " + item.identifier + "; jar: " + ClassUtils.getLocation(item.info.getDelegateClassName())); if (wrapper != null) try { wrapper.create(item.path, true); } catch (final Throwable t) { log.error(t); } } else if (wrapper != null) try { wrapper.create(item.path, false); } catch (final Throwable t) { log.error(t); } ij1Commands.put(item.name, item.identifier); } menuInitialized = true; } /** * Helper class for wrapping ImageJ2 menu paths to ImageJ1 {@link Menu} * structures, and inserting them into the proper positions of the * {@link MenuBar}. */ private static class IJ1MenuWrapper { final ImageJ ij1; final MenuBar menuBar = Menus.getMenuBar(); final Map<String, Menu> structure = new HashMap<String, Menu>(); final Set<Menu> separators = new HashSet<Menu>(); private IJ1MenuWrapper(final ImageJ ij1) { this.ij1 = ij1; } /** * Creates a {@link MenuItem} matching the structure of the provided path. * Expected path structure is: * <p> * <ul>Level1 > Level2 > ... > Leaf entry</ul> * </p> * <p> * For example, a valid path would be: * </p> * <p> * <ul>Edit > Options > ImageJ2 plugins > Discombobulator</ul> * </p> */ private MenuItem create(final MenuPath path, final boolean reuseExisting) { // Find the menu structure where we can insert our command. // NB: size - 1 is the leaf position, so we want to go to size - 2 to // find the parent menu location final Menu menu = getParentMenu(path, path.size() - 2); final String label = path.getLeaf().getName(); // If we are overriding an item, find the item being overridden if (reuseExisting) { for (int i = 0; i < menu.getItemCount(); i++) { final MenuItem item = menu.getItem(i); if (label.equals(item.getLabel())) { return item; } } } if (!separators.contains(menu)) { if (menu.getItemCount() > 0) menu.addSeparator(); separators.add(menu); } // Otherwise, we are creating a new item final MenuItem item = new MenuItem(label); menu.insert(item, getIndex(menu, label)); item.addActionListener(ij1); return item; } /** * Helper method to look up special cases for menu weighting */ private int getIndex(Menu menu, String label) { // Place export sub-menu after import sub-menu if (menu.getLabel().equals("File") && label.equals("Export")) { for (int i=0; i<menu.getItemCount(); i++) { final MenuItem menuItem = menu.getItem(i); if (menuItem.getLabel().equals("Import")) return i + 1; } } //TODO pass and use actual command weight from IJ2.. maybe? // No special case: append to end of menu return menu.getItemCount(); } /** * Recursive helper method to builds the final {@link Menu} structure. */ private Menu getParentMenu(final MenuPath menuPath, int depth) { final MenuEntry currentItem = menuPath.get(depth); final String currentLabel = currentItem.getName(); // Check to see if we already know the menu associated with the desired // label/path final Menu cached = structure.get(currentLabel); if (cached != null) return cached; // We are at the root of the menu, so see if we have a matching menu if (depth == 0) { // Special case check the help menu if ("Help".equals(currentLabel)) { final Menu menu = menuBar.getHelpMenu(); structure.put(currentLabel, menu); return menu; } // Check the other menus of the menu bar to see if our desired label // already exists for (int i = 0; i < menuBar.getMenuCount(); i++) { final Menu menu = menuBar.getMenu(i); if (currentLabel.equals(menu.getLabel())) { structure.put(currentLabel, menu); return menu; } } // Didn't find a match so we have to create a new menu entry final Menu menu = new Menu(currentLabel); menuBar.add(menu); structure.put(currentLabel, menu); return menu; } final Menu parent = getParentMenu(menuPath, depth - 1); // Once the parent of this entry is obtained, we need to check if it // already contains the current entry. for (int i = 0; i < parent.getItemCount(); i++) { final MenuItem item = parent.getItem(i); if (currentLabel.equals(item.getLabel())) { if (item instanceof Menu) { // Found a menu entry that matches our desired label, so return final Menu menu = (Menu) item; structure.put(currentLabel, menu); return menu; } // Found a match but it was an existing non-menu item, so our menu // structure is invalid. //TODO consider mangling the IJ2 menu name instead... throw new IllegalArgumentException("Not a menu: " + currentLabel); } } if (!separators.contains(parent)) { if (parent.getItemCount() > 0) parent.addSeparator(); separators.add(parent); } // An existing entry in the parent menu was not found, so we need to // create a new entry. final Menu menu = new Menu(currentLabel); parent.insert(menu, getIndex(parent, menu.getLabel())); structure.put(currentLabel, menu); return menu; } } /** * Evaluates the specified macro. * * @param macro the macro to evaluate * @return the return value */ public String runMacro(final String macro) { if (EventQueue.isDispatchThread()) { throw new IllegalStateException("Cannot run macro from the EDT!"); } final Thread thread = Thread.currentThread(); final String name = thread.getName(); try { // to make getOptions() work if (!name.startsWith("Run$_")) thread.setName("Run$_" + name); // to make Macro.abort() work if (!name.endsWith("Macro$")) thread.setName(thread.getName() + "Macro$"); return IJ.runMacro(macro); } finally { thread.setName(name); } } /** * Evaluates the specified macro. * * @param path the macro file to evaluate * @param arg the macro argument * @return the return value */ public String runMacroFile(final String path, final String arg) { if (EventQueue.isDispatchThread()) { throw new IllegalStateException("Cannot run macro from the EDT!"); } final Thread thread = Thread.currentThread(); final String name = thread.getName(); try { // to make getOptions() work if (!name.startsWith("Run$_")) thread.setName("Run$_" + name); return IJ.runMacroFile(path, arg); } finally { thread.setName(name); } } /** * Opens an image using ImageJ 1.x. * * @param path the image file to open * @return the image */ public Object openImage(final String path) { return IJ.openImage(path); } /** * Opens a path using ImageJ 1.x, bypassing the (javassisted) IJ utility * class. * * @param path the image file to open */ public void openPathDirectly(final String path) { new Opener().open(path); } /** * Enables or disables ImageJ 1.x' debug mode. * * @param debug whether to show debug messages or not */ public void setDebugMode(final boolean debug) { IJ.debugMode = debug; } /** * Delegate exception handling to ImageJ 1.x. * * @param e the exception to handle */ public void handleException(Throwable e) { IJ.handleException(e); } /** * Ask ImageJ 1.x whether it thinks whether the Shift key is held down. * * @return whether the Shift key is considered <i>down</i> */ public boolean shiftKeyDown() { return IJ.shiftKeyDown(); } /** * Delegates to ImageJ 1.x' {@link Macro#getOptions()} function. * * @return the macro options, or null */ public Object getOptions() { return Macro.getOptions(); } /** * Delegates to ImageJ 1.x' {@link Macro#setOptions(String)} function. * * @param options the macro options, or null to reset */ public void setOptions(final String options) { Macro.setOptions(options); } /** Handles shutdown of ImageJ 1.x. */ public void appQuit() { if (legacyService.isLegacyMode()) { new Executer("Quit", null); // works with the CommandListener } } /** Displays the About ImageJ 1.x dialog. */ public void appAbout() { if (legacyService.isLegacyMode()) { IJ.run("About ImageJ..."); } } /** Handles display of the ImageJ 1.x preferences. */ public void appPrefs() { if (legacyService.isLegacyMode()) { IJ.error("The ImageJ preferences are in the Edit>Options menu."); } } // -- Helper methods -- /** Closes all image windows on the event dispatch thread. */ private void closeImageWindows() { // TODO: Consider using ThreadService#invoke to simplify this logic. final Runnable run = new Runnable() { @Override public void run() { // close out all image windows, without dialog prompts while (true) { final ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) break; imp.changes = false; imp.close(); } } }; if (EventQueue.isDispatchThread()) { run.run(); } else { try { EventQueue.invokeAndWait(run); } catch (final Exception e) { // report & ignore log.error(e); } } } private void disposeNonImageWindows() { disposeNonImageFrames(); disposeOtherNonImageWindows(); } /** * Disposes all the non-image window frames, as given by * {@link WindowManager#getNonImageWindows()}. */ private void disposeNonImageFrames() { for (Frame frame : WindowManager.getNonImageWindows()) { frame.dispose(); } } /** * Ensures <em>all</em> the non-image windows are closed. * <p> * This is a non-trivial problem, as * {@link WindowManager#getNonImageWindows()} <em>only</em> returns * {@link Frame}s. However there are non-image, non-{@link Frame} windows that * are critical to close: for example, the * {@link ij.plugin.frame.ContrastAdjuster} spawns a polling thread to do its * work, which will continue to run until the {@code ContrastAdjuster} is * explicitly closed. * </p> */ private void disposeOtherNonImageWindows() { // NB: As of v1.49b, getNonImageTitles is not restricted to Frames, // so we can use it to iterate through the available windows. for (String title : WindowManager.getNonImageTitles()) { final Window window = WindowManager.getWindow(title); // NB: We can NOT set these windows as active and run the Commands // plugin with argument "close", because the default behavior is to // try closing the window as an Image. As we know these are not Images, // that is never the right thing to do. WindowManager.removeWindow(window); window.dispose(); } } }
package net.sf.gaboto; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Hashtable; import java.util.Iterator; import net.sf.gaboto.event.GabotoEvent; import net.sf.gaboto.event.InsertionGabotoEvent; import net.sf.gaboto.event.RemovalGabotoEvent; import net.sf.gaboto.event.UpdateListener; import net.sf.gaboto.time.TimeDimensionIndexer; import net.sf.gaboto.time.TimeInstant; import net.sf.gaboto.util.Performance; import net.sf.gaboto.vocabulary.RDFContext; import com.hp.hpl.jena.db.DBConnection; import com.hp.hpl.jena.db.IDBConnection; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ModelMaker; import com.hp.hpl.jena.vocabulary.RDF; import de.fuberlin.wiwiss.ng4j.NamedGraph; import de.fuberlin.wiwiss.ng4j.NamedGraphSet; import de.fuberlin.wiwiss.ng4j.Quad; import de.fuberlin.wiwiss.ng4j.db.NamedGraphSetDB; import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl; /** * Factory class to create Gaboto objects. * * * @author Arno Mittelbach * @version 0.1 */ public class GabotoFactory { private static Gaboto persistentGaboto = null; static Gaboto inMemoryGaboto = null; private static Model contextDescriptiontGraph = null; public static GabotoConfiguration config = GabotoConfiguration.fromConfigFile(); private static Hashtable<String,Gaboto> knownStores = new Hashtable<String,Gaboto>(); private static Hashtable<String,GabotoSnapshot> knownSnapshots = new Hashtable<String,GabotoSnapshot>(); /** * Returns the Gaboto configuration. * @return The Gaboto configuration. */ public static GabotoConfiguration getConfig(){ return config; } /** * @param directoryName name of the store, normnally a diretory name * @return a cached or newly minted Gaboto */ public static Gaboto getGaboto(String directoryName) { if (directoryName == null) throw new NullPointerException(); Gaboto it = null; synchronized(knownStores) { it = knownStores.get(directoryName); if (it == null) knownStores.put(directoryName, readPersistedGaboto(directoryName)); it = knownStores.get(directoryName); } return it; } public static Gaboto refreshedGaboto(String directoryName) { if (directoryName == null) throw new NullPointerException(); Gaboto it = null; synchronized(knownStores) { knownStores.put(directoryName, readPersistedGaboto(directoryName)); it = knownStores.get(directoryName); } return it; } /** * @return a cached or newly minted GabotSnapshot */ public static GabotoSnapshot getSnapshot(String directoryName, TimeInstant timeInstant) { GabotoSnapshot it = null; String key = directoryName + ":" + timeInstant.toString(); synchronized(knownSnapshots){ it = knownSnapshots.get(key); if (it == null) { it = getGaboto(directoryName).getSnapshot(timeInstant); knownSnapshots.put(key, it); } } return it; } private static Gaboto readPersistedGaboto(String directoryName) { return readPersistedGaboto(directoryName, Gaboto.GRAPH_FILE_NAME, Gaboto.CDG_FILE_NAME); } public static Gaboto readPersistedGaboto(String directoryName, String graphName, String contextName) { File graphs = new File(directoryName, graphName); File context = new File(directoryName, contextName); FileInputStream graphsFileInputStream; FileInputStream contextFileInputStream; try { graphsFileInputStream = new FileInputStream(graphs); contextFileInputStream = new FileInputStream(context); } catch (FileNotFoundException e) { throw new GabotoRuntimeException(e); } return readPersistedGaboto(graphsFileInputStream, contextFileInputStream); } public static Gaboto readPersistedGaboto(InputStream graphsInputStream, InputStream contextInputStream) { Gaboto g = getEmptyInMemoryGaboto(); g.read(graphsInputStream, contextInputStream); g.recreateTimeDimensionIndex(); return g; } /** * Creates an empty in memory Gaboto model that is not linked to any persistent data store. * * <p> * A time dimension indexer is set. * </p> * * @return A new Gaboto object. */ public static Gaboto getEmptyInMemoryGaboto() { NamedGraphSet graphset = new NamedGraphSetImpl(); return new Gaboto(createGlobalKnowledgeGraph(ModelFactory.createDefaultModel(), graphset), graphset, new TimeDimensionIndexer()); } /** * Creates a new in-memory Gaboto system that is kept in sync with the persistent Gaboto object. * * <p> * A time dimension indexer is set. * </p> * * <p> * In memory objects should only be used for querying data. * </p> * * @return An Gaboto object with an in-memory store. * * @see #getPersistentGaboto() */ @SuppressWarnings("unchecked") public static Gaboto getInMemoryGaboto() { if(inMemoryGaboto != null) { return inMemoryGaboto; } Gaboto po = getPersistentGaboto(); // Create a new graphset and copy graphs NamedGraphSet graphset = new NamedGraphSetImpl(); Iterator graphIt = po.getNamedGraphSet().listGraphs(); while(graphIt.hasNext()) graphset.createGraph(((NamedGraph)graphIt.next()).getGraphName()); System.err.println("getInMemoryGaboto: have created graphs"); Iterator it = po.getNamedGraphSet().findQuads(Node.ANY, Node.ANY, Node.ANY, Node.ANY); while(it.hasNext()) graphset.addQuad((Quad)it.next()); System.err.println("getInMemoryGaboto: have added quads"); inMemoryGaboto = new Gaboto(createDbBackedCDG(), graphset, new TimeDimensionIndexer()); System.err.println("getInMemoryGaboto: returning"); return inMemoryGaboto; } /** * Creates a new Gaboto model with a persistent data store. * * <p> * The connection to the database is configured in the {@link GabotoConfiguration}. * </p> * * <p> * A time dimension indexer is NOT set. * </p> * * <p> * The Persistent Gaboto object should only be used to add and change data. For * querying the data, an in-memory Gaboto should be used. * </p> * * <p> * Update the persistent and the in-memory copy is updated. * </p> * * @return A new persistent Gaboto * @see #getInMemoryGaboto() * @see GabotoConfiguration */ public static Gaboto getPersistentGaboto() { // does it already exist? if(persistentGaboto != null) return persistentGaboto; // get config GabotoConfiguration c = GabotoFactory.getConfig(); // create persistent gaboto String URL = c.getDbURL(); String USER = c.getDbUser(); String PW = c.getDbPassword(); try { Class.forName(c.getDbDriver()); } catch (ClassNotFoundException e1) { throw new RuntimeException(e1); } Connection connection = null; System.err.println("URL:"+URL + " USER:"+USER+ " PWD:"+PW); try { connection = DriverManager.getConnection(URL, USER, PW); } catch (SQLException e) { throw new RuntimeException(e); } // Create a new graphset Performance.start("GabotoFactory new NamedGraphSetDB"); NamedGraphSet graphset = new NamedGraphSetDB(connection); Performance.stop(); // if graphset is empty, create special graphs Model cdg = createGlobalKnowledgeGraph(createDbBackedCDG(), graphset); // create object Performance.start("GabotoFactory new Gaboto"); persistentGaboto = new Gaboto(cdg, graphset, new TimeDimensionIndexer()); Performance.stop(); Performance.start("GabotoFactory update listener"); // attach update listener persistentGaboto.attachUpdateListener(new UpdateListener(){ public void updateOccured(GabotoEvent e) { // try to cast event to insertion if(e instanceof InsertionGabotoEvent){ InsertionGabotoEvent event = (InsertionGabotoEvent) e; if(event.getTimespan() != null) inMemoryGaboto.add(event.getTimespan(), event.getTriple()); else inMemoryGaboto.add(event.getTriple()); } // try to cast event to removal else if(e instanceof RemovalGabotoEvent){ RemovalGabotoEvent event = (RemovalGabotoEvent) e; if(event.getQuad() != null) inMemoryGaboto.remove(event.getQuad()); else if(event.getTimespan() != null && event.getTriple() != null ) inMemoryGaboto.remove(event.getTimespan(), event.getTriple()); else if(event.getTriple() != null) inMemoryGaboto.remove(event.getTriple()); } else throw new GabotoRuntimeException("Unexpected update type: " + e.getClass()); } }); Performance.stop(); return persistentGaboto; } /** * Adds the cdg to the graphset. */ private static Model createDbBackedCDG() { System.err.println("In createCDG"); if(contextDescriptiontGraph != null) { return contextDescriptiontGraph; } // get config GabotoConfiguration c = GabotoFactory.getConfig(); String M_DB_URL = c.getDbURL(); String M_DB_USER = c.getDbUser(); String M_DB_PASSWD = c.getDbPassword(); String M_DB = c.getDbEngineName(); String M_DBDRIVER_CLASS = c.getDbDriver(); // load the driver class just to provoke error try { Class.forName(M_DBDRIVER_CLASS); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } // create a database connection IDBConnection conn = new DBConnection(M_DB_URL, M_DB_USER, M_DB_PASSWD, M_DB); // create a model maker with the given connection parameters ModelMaker maker = ModelFactory.createModelRDBMaker(conn); // create cdg if(maker.hasModel("cdg")) contextDescriptiontGraph = maker.openModel("cdg"); else contextDescriptiontGraph = maker.createModel("cdg"); return contextDescriptiontGraph; } /** * Adds the Global Knowledge Graph (GKG) to the graphset * @param cdg Context Description Graph * @param graphset */ private static Model createGlobalKnowledgeGraph(Model cdg, NamedGraphSet graphset) { if(graphset.containsGraph(config.getGlobalKnowledgeGraphURI())) throw new IllegalStateException("GlobalKnowledgeGraph already exists."); // Create Global Knowledge Graph graphset.createGraph(config.getGlobalKnowledgeGraphURI()); // add Global Knowledge Graph to Context Description Graph cdg.getGraph().add(new Triple( Node.createURI(config.getGlobalKnowledgeGraphURI()), Node.createURI(RDF.type.getURI()), Node.createURI(RDFContext.GlobalKnowledgeGraph.getURI()) )); return cdg; } }
package net.sf.jabref.gui; import java.awt.BorderLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TimerTask; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.tree.TreePath; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import net.sf.jabref.Globals; import net.sf.jabref.JabRefExecutorService; import net.sf.jabref.collab.ChangeScanner; import net.sf.jabref.collab.FileUpdateListener; import net.sf.jabref.collab.FileUpdatePanel; import net.sf.jabref.gui.actions.Actions; import net.sf.jabref.gui.actions.BaseAction; import net.sf.jabref.gui.actions.CleanupAction; import net.sf.jabref.gui.actions.CopyBibTeXKeyAndLinkAction; import net.sf.jabref.gui.bibtexkeypattern.SearchFixDuplicateLabels; import net.sf.jabref.gui.desktop.JabRefDesktop; import net.sf.jabref.gui.entryeditor.EntryEditor; import net.sf.jabref.gui.exporter.ExportToClipboardAction; import net.sf.jabref.gui.exporter.SaveDatabaseAction; import net.sf.jabref.gui.externalfiles.FindFullTextAction; import net.sf.jabref.gui.externalfiles.SynchronizeFileField; import net.sf.jabref.gui.externalfiles.WriteXMPAction; import net.sf.jabref.gui.externalfiletype.ExternalFileMenuItem; import net.sf.jabref.gui.externalfiletype.ExternalFileType; import net.sf.jabref.gui.externalfiletype.ExternalFileTypes; import net.sf.jabref.gui.fieldeditors.FieldEditor; import net.sf.jabref.gui.filelist.AttachFileAction; import net.sf.jabref.gui.filelist.FileListEntry; import net.sf.jabref.gui.filelist.FileListTableModel; import net.sf.jabref.gui.groups.GroupAddRemoveDialog; import net.sf.jabref.gui.groups.GroupSelector; import net.sf.jabref.gui.groups.GroupTreeNodeViewModel; import net.sf.jabref.gui.importer.actions.AppendDatabaseAction; import net.sf.jabref.gui.journals.AbbreviateAction; import net.sf.jabref.gui.journals.UnabbreviateAction; import net.sf.jabref.gui.keyboard.KeyBinding; import net.sf.jabref.gui.maintable.MainTable; import net.sf.jabref.gui.maintable.MainTableDataModel; import net.sf.jabref.gui.maintable.MainTableFormat; import net.sf.jabref.gui.maintable.MainTableSelectionListener; import net.sf.jabref.gui.mergeentries.FetchAndMergeEntry; import net.sf.jabref.gui.mergeentries.MergeEntriesDialog; import net.sf.jabref.gui.plaintextimport.TextInputDialog; import net.sf.jabref.gui.undo.CountingUndoManager; import net.sf.jabref.gui.undo.NamedCompound; import net.sf.jabref.gui.undo.UndoableChangeType; import net.sf.jabref.gui.undo.UndoableFieldChange; import net.sf.jabref.gui.undo.UndoableInsertEntry; import net.sf.jabref.gui.undo.UndoableKeyChange; import net.sf.jabref.gui.undo.UndoableRemoveEntry; import net.sf.jabref.gui.util.component.CheckBoxMessage; import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.gui.worker.CallBack; import net.sf.jabref.gui.worker.MarkEntriesAction; import net.sf.jabref.gui.worker.SendAsEMailAction; import net.sf.jabref.gui.worker.Worker; import net.sf.jabref.logic.autocompleter.AutoCompletePreferences; import net.sf.jabref.logic.autocompleter.AutoCompleter; import net.sf.jabref.logic.autocompleter.AutoCompleterFactory; import net.sf.jabref.logic.autocompleter.ContentAutoCompleters; import net.sf.jabref.logic.bibtexkeypattern.BibtexKeyPatternUtil; import net.sf.jabref.logic.citationstyle.CitationStyleCache; import net.sf.jabref.logic.exporter.BibtexDatabaseWriter; import net.sf.jabref.logic.exporter.FileSaveSession; import net.sf.jabref.logic.exporter.SaveException; import net.sf.jabref.logic.exporter.SavePreferences; import net.sf.jabref.logic.exporter.SaveSession; import net.sf.jabref.logic.l10n.Encodings; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.layout.Layout; import net.sf.jabref.logic.layout.LayoutHelper; import net.sf.jabref.logic.search.SearchQuery; import net.sf.jabref.logic.util.FileExtensions; import net.sf.jabref.logic.util.UpdateField; import net.sf.jabref.logic.util.io.FileBasedLock; import net.sf.jabref.logic.util.io.FileUtil; import net.sf.jabref.logic.util.io.RegExpFileSearch; import net.sf.jabref.model.FieldChange; import net.sf.jabref.model.bibtexkeypattern.AbstractBibtexKeyPattern; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.database.BibDatabaseContext; import net.sf.jabref.model.database.DatabaseLocation; import net.sf.jabref.model.database.KeyCollisionException; import net.sf.jabref.model.database.event.EntryAddedEvent; import net.sf.jabref.model.database.event.EntryRemovedEvent; import net.sf.jabref.model.entry.BibEntry; import net.sf.jabref.model.entry.EntryType; import net.sf.jabref.model.entry.FieldName; import net.sf.jabref.model.entry.IdGenerator; import net.sf.jabref.model.entry.event.EntryChangedEvent; import net.sf.jabref.model.entry.event.EntryEventSource; import net.sf.jabref.preferences.HighlightMatchingGroupPreferences; import net.sf.jabref.preferences.JabRefPreferences; import net.sf.jabref.preferences.PreviewPreferences; import net.sf.jabref.shared.DBMSSynchronizer; import net.sf.jabref.specialfields.Printed; import net.sf.jabref.specialfields.Priority; import net.sf.jabref.specialfields.Quality; import net.sf.jabref.specialfields.Rank; import net.sf.jabref.specialfields.ReadStatus; import net.sf.jabref.specialfields.Relevance; import net.sf.jabref.specialfields.SpecialFieldAction; import net.sf.jabref.specialfields.SpecialFieldDatabaseChangeListener; import net.sf.jabref.specialfields.SpecialFieldValue; import ca.odell.glazedlists.event.ListEventListener; import com.google.common.eventbus.Subscribe; import com.jgoodies.forms.builder.FormBuilder; import com.jgoodies.forms.layout.FormLayout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class BasePanel extends JPanel implements ClipboardOwner, FileUpdateListener { private static final Log LOGGER = LogFactory.getLog(BasePanel.class); // Divider size for BaseFrame split pane. 0 means non-resizable. private static final int SPLIT_PANE_DIVIDER_SIZE = 4; private final BibDatabaseContext bibDatabaseContext; private final MainTableDataModel tableModel; private final CitationStyleCache citationStyleCache; // To contain instantiated entry editors. This is to save time // As most enums, this must not be null private BasePanelMode mode = BasePanelMode.SHOWING_NOTHING; private EntryEditor currentEditor; private MainTableSelectionListener selectionListener; private ListEventListener<BibEntry> groupsHighlightListener; private JSplitPane splitPane; private final JabRefFrame frame; private String fileMonitorHandle; private boolean saving; private boolean updatedExternally; // AutoCompleter used in the search bar private AutoCompleter<String> searchAutoCompleter; // The undo manager. private final UndoAction undoAction = new UndoAction(); private final RedoAction redoAction = new RedoAction(); private final CountingUndoManager undoManager = new CountingUndoManager(); private final List<BibEntry> previousEntries = new ArrayList<>(); private final List<BibEntry> nextEntries = new ArrayList<>(); private boolean baseChanged; private boolean nonUndoableChange; // Used to track whether the base has changed since last save. private MainTable mainTable; private MainTableFormat tableFormat; private BibEntry showing; // Variable to prevent erroneous update of back/forward histories at the time // when a Back or Forward operation is being processed: private boolean backOrForwardInProgress; // in switching between entries. private PreambleEditor preambleEditor; // Keeps track of the preamble dialog if it is open. private StringDialog stringDialog; // Keeps track of the string dialog if it is open. private final Map<String, Object> actions = new HashMap<>(); private final SidePaneManager sidePaneManager; private ContentAutoCompleters autoCompleters; private SearchQuery currentSearchQuery; public BasePanel(JabRefFrame frame, BibDatabaseContext bibDatabaseContext) { Objects.requireNonNull(frame); Objects.requireNonNull(bibDatabaseContext); this.bibDatabaseContext = bibDatabaseContext; this.sidePaneManager = frame.getSidePaneManager(); this.frame = frame; this.tableModel = new MainTableDataModel(getBibDatabaseContext()); citationStyleCache = new CitationStyleCache(bibDatabaseContext); setupMainPanel(); setupActions(); this.getDatabase().registerListener(new SearchListener()); // ensure that at each addition of a new entry, the entry is added to the groups interface this.bibDatabaseContext.getDatabase().registerListener(new GroupTreeListener()); Optional<File> file = bibDatabaseContext.getDatabaseFile(); if (file.isPresent()) { // Register so we get notifications about outside changes to the file. try { fileMonitorHandle = Globals.getFileUpdateMonitor().addUpdateListener(this, file.get()); } catch (IOException ex) { LOGGER.warn("Could not register FileUpdateMonitor", ex); } } else { if (bibDatabaseContext.getDatabase().hasEntries()) { // if the database is not empty and no file is assigned, // the database came from an import and has to be treated somehow // -> mark as changed this.baseChanged = true; } } } // Returns a collection of AutoCompleters, which are populated from the current database public ContentAutoCompleters getAutoCompleters() { return autoCompleters; } public String getTabTitle() { StringBuilder title = new StringBuilder(); DatabaseLocation databaseLocation = this.bibDatabaseContext.getLocation(); boolean isAutosaveEnabled = Globals.prefs.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE); if (databaseLocation == DatabaseLocation.LOCAL) { if (this.bibDatabaseContext.getDatabaseFile().isPresent()) { // check if file is modified String changeFlag = isModified() && !isAutosaveEnabled ? "*" : ""; title.append(this.bibDatabaseContext.getDatabaseFile().get().getName()).append(changeFlag); } else { title.append(GUIGlobals.UNTITLED_TITLE); if (getDatabase().hasEntries()) { // if the database is not empty and no file is assigned, // the database came from an import and has to be treated somehow // -> mark as changed // This also happens internally at basepanel to ensure consistency line 224 title.append('*'); } } } else if (databaseLocation == DatabaseLocation.SHARED) { title.append( this.bibDatabaseContext.getDBMSSynchronizer().getDBName() + " [" + Localization.lang("shared") + "]"); } return title.toString(); } public boolean isModified() { return baseChanged; } public BasePanelMode getMode() { return mode; } public void setMode(BasePanelMode mode) { this.mode = mode; } public JabRefFrame frame() { return frame; } public void output(String s) { frame.output(s); } private void setupActions() { SaveDatabaseAction saveAction = new SaveDatabaseAction(this); CleanupAction cleanUpAction = new CleanupAction(this, Globals.prefs); actions.put(Actions.UNDO, undoAction); actions.put(Actions.REDO, redoAction); actions.put(Actions.FOCUS_TABLE, (BaseAction) () -> { mainTable.requestFocus(); }); // The action for opening an entry editor. actions.put(Actions.EDIT, (BaseAction) selectionListener::editSignalled); // The action for saving a database. actions.put(Actions.SAVE, saveAction); actions.put(Actions.SAVE_AS, (BaseAction) saveAction::saveAs); actions.put(Actions.SAVE_SELECTED_AS, new SaveSelectedAction(SavePreferences.DatabaseSaveType.ALL)); actions.put(Actions.SAVE_SELECTED_AS_PLAIN, new SaveSelectedAction(SavePreferences.DatabaseSaveType.PLAIN_BIBTEX)); // The action for copying selected entries. actions.put(Actions.COPY, (BaseAction) () -> copy()); actions.put(Actions.PRINT_PREVIEW, new PrintPreviewAction()); actions.put(Actions.CUT, (BaseAction) this::cut); //when you modify this action be sure to adjust Actions.CUT, //they are the same except of the Localization, delete confirmation and Actions.COPY call actions.put(Actions.DELETE, (BaseAction) () -> delete(false)); // The action for pasting entries or cell contents. // - more robust detection of available content flavors (doesn't only look at first one offered) // - support for parsing string-flavor clipboard contents which are bibtex entries. // This allows you to (a) paste entire bibtex entries from a text editor, web browser, etc // (b) copy and paste entries between multiple instances of JabRef (since // only the text representation seems to get as far as the X clipboard, at least on my system) actions.put(Actions.PASTE, (BaseAction) () -> paste()); actions.put(Actions.SELECT_ALL, (BaseAction) mainTable::selectAll); // The action for opening the preamble editor actions.put(Actions.EDIT_PREAMBLE, (BaseAction) () -> { if (preambleEditor == null) { PreambleEditor form = new PreambleEditor(frame, BasePanel.this, bibDatabaseContext.getDatabase()); form.setLocationRelativeTo(frame); form.setVisible(true); preambleEditor = form; } else { preambleEditor.setVisible(true); } }); // The action for opening the string editor actions.put(Actions.EDIT_STRINGS, (BaseAction) () -> { if (stringDialog == null) { StringDialog form = new StringDialog(frame, BasePanel.this, bibDatabaseContext.getDatabase()); form.setVisible(true); stringDialog = form; } else { stringDialog.setVisible(true); } }); actions.put(FindUnlinkedFilesDialog.ACTION_COMMAND, (BaseAction) () -> { final FindUnlinkedFilesDialog dialog = new FindUnlinkedFilesDialog(frame, frame, BasePanel.this); dialog.setLocationRelativeTo(frame); dialog.setVisible(true); }); // The action for auto-generating keys. actions.put(Actions.MAKE_KEY, new AbstractWorker() { List<BibEntry> entries; int numSelected; boolean canceled; // Run first, in EDT: @Override public void init() { entries = getSelectedEntries(); numSelected = entries.size(); if (entries.isEmpty()) { // None selected. Inform the user to select entries first. JOptionPane.showMessageDialog(frame, Localization.lang("First select the entries you want keys to be generated for."), Localization.lang("Autogenerate BibTeX keys"), JOptionPane.INFORMATION_MESSAGE); return; } frame.block(); output(formatOutputMessage(Localization.lang("Generating BibTeX key for"), numSelected)); } // Run second, on a different thread: @Override public void run() { // We don't want to generate keys for entries which already have one thus remove the entries if (Globals.prefs.getBoolean(JabRefPreferences.AVOID_OVERWRITING_KEY)) { entries.removeIf(BibEntry::hasCiteKey); // if we're going to override some cite keys warn the user about it } else if (Globals.prefs.getBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY)) { if (entries.parallelStream().anyMatch(BibEntry::hasCiteKey)) { CheckBoxMessage cbm = new CheckBoxMessage( Localization.lang("One or more keys will be overwritten. Continue?"), Localization.lang("Disable this confirmation dialog"), false); final int answer = JOptionPane.showConfirmDialog(frame, cbm, Localization.lang("Overwrite keys"), JOptionPane.YES_NO_OPTION); Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !cbm.isSelected()); // The user doesn't want to overide cite keys if (answer == JOptionPane.NO_OPTION) { canceled = true; return; } } } // generate the new cite keys for each entry final NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate BibTeX keys")); AbstractBibtexKeyPattern citeKeyPattern = bibDatabaseContext.getMetaData() .getCiteKeyPattern(Globals.prefs.getBibtexKeyPatternPreferences().getKeyPattern()); for (BibEntry entry : entries) { String oldCiteKey = entry.getCiteKeyOptional().orElse(""); BibtexKeyPatternUtil.makeLabel(citeKeyPattern, bibDatabaseContext.getDatabase(), entry, Globals.prefs.getBibtexKeyPatternPreferences()); String newCiteKey = entry.getCiteKeyOptional().orElse(""); if (!oldCiteKey.equals(newCiteKey)) { ce.addEdit(new UndoableKeyChange(entry, oldCiteKey, newCiteKey)); } } ce.end(); // register the undo event only if new cite keys were generated if (ce.hasEdits()) { getUndoManager().addEdit(ce); } } // Run third, on EDT: @Override public void update() { if (canceled) { frame.unblock(); return; } markBaseChanged(); numSelected = entries.size(); // Prevent selection loss for autogenerated BibTeX-Keys for (final BibEntry bibEntry : entries) { SwingUtilities.invokeLater(() -> { final int row = mainTable.findEntry(bibEntry); if ((row >= 0) && (mainTable.getSelectedRowCount() < entries.size())) { mainTable.addRowSelectionInterval(row, row); } }); } output(formatOutputMessage(Localization.lang("Generated BibTeX key for"), numSelected)); frame.unblock(); } }); // The action for cleaning up entry. actions.put(Actions.CLEANUP, cleanUpAction); actions.put(Actions.MERGE_ENTRIES, (BaseAction) () -> new MergeEntriesDialog(BasePanel.this)); actions.put(Actions.SEARCH, (BaseAction) frame.getGlobalSearchBar()::focus); actions.put(Actions.GLOBAL_SEARCH, (BaseAction) frame.getGlobalSearchBar()::performGlobalSearch); // The action for copying the selected entry's key. actions.put(Actions.COPY_KEY, (BaseAction) () -> copyKey()); // The action for copying a cite for the selected entry. actions.put(Actions.COPY_CITE_KEY, (BaseAction) () -> copyCiteKey()); // The action for copying the BibTeX key and the title for the first selected entry actions.put(Actions.COPY_KEY_AND_TITLE, (BaseAction) () -> copyKeyAndTitle()); // The action for copying the BibTeX keys as hyperlinks to the urls of the selected entries actions.put(Actions.COPY_KEY_AND_LINK, new CopyBibTeXKeyAndLinkAction(mainTable)); actions.put(Actions.MERGE_DATABASE, new AppendDatabaseAction(frame, this)); actions.put(Actions.ADD_FILE_LINK, new AttachFileAction(this)); actions.put(Actions.OPEN_EXTERNAL_FILE, (BaseAction) () -> openExternalFile()); actions.put(Actions.OPEN_FOLDER, (BaseAction) () -> JabRefExecutorService.INSTANCE.execute(() -> { final List<File> files = FileUtil.getListOfLinkedFiles(mainTable.getSelectedEntries(), bibDatabaseContext.getFileDirectory(Globals.prefs.getFileDirectoryPreferences())); for (final File f : files) { try { JabRefDesktop.openFolderAndSelectFile(f.getAbsolutePath()); } catch (IOException e) { LOGGER.info("Could not open folder", e); } } })); actions.put(Actions.OPEN_CONSOLE, (BaseAction) () -> JabRefDesktop .openConsole(frame.getCurrentBasePanel().getBibDatabaseContext().getDatabaseFile().orElse(null))); actions.put(Actions.PULL_CHANGES_FROM_SHARED_DATABASE, (BaseAction) () -> { DBMSSynchronizer dbmsSynchronizer = frame.getCurrentBasePanel().getBibDatabaseContext().getDBMSSynchronizer(); dbmsSynchronizer.pullChanges(); }); actions.put(Actions.OPEN_URL, new OpenURLAction()); actions.put(Actions.MERGE_WITH_FETCHED_ENTRY, (BaseAction) () -> { if (mainTable.getSelectedEntries().size() == 1) { BibEntry originalEntry = mainTable.getSelectedEntries().get(0); new FetchAndMergeEntry(originalEntry, this, FetchAndMergeEntry.SUPPORTED_FIELDS); } else { JOptionPane.showMessageDialog(frame(), Localization.lang("This operation requires exactly one item to be selected."), Localization.lang("Merge entry with %0 information", FieldName.orFields(FieldName.getDisplayName(FieldName.DOI), FieldName.getDisplayName(FieldName.ISBN), FieldName.getDisplayName(FieldName.EPRINT))), JOptionPane.INFORMATION_MESSAGE); } }); actions.put(Actions.REPLACE_ALL, (BaseAction) () -> { final ReplaceStringDialog rsd = new ReplaceStringDialog(frame); rsd.setVisible(true); if (!rsd.okPressed()) { return; } int counter = 0; final NamedCompound ce = new NamedCompound(Localization.lang("Replace string")); if (rsd.selOnly()) { for (BibEntry be : mainTable.getSelectedEntries()) { counter += rsd.replace(be, ce); } } else { for (BibEntry entry : bibDatabaseContext.getDatabase().getEntries()) { counter += rsd.replace(entry, ce); } } output(Localization.lang("Replaced") + ' ' + counter + ' ' + (counter == 1 ? Localization.lang("occurrence") : Localization.lang("occurrences")) + '.'); if (counter > 0) { ce.end(); getUndoManager().addEdit(ce); markBaseChanged(); } }); actions.put(Actions.DUPLI_CHECK, (BaseAction) () -> JabRefExecutorService.INSTANCE.execute(new DuplicateSearch(BasePanel.this))); actions.put(Actions.PLAIN_TEXT_IMPORT, (BaseAction) () -> { // get Type of new entry EntryTypeDialog etd = new EntryTypeDialog(frame); etd.setLocationRelativeTo(BasePanel.this); etd.setVisible(true); EntryType tp = etd.getChoice(); if (tp == null) { return; } String id = IdGenerator.next(); BibEntry bibEntry = new BibEntry(id, tp.getName()); TextInputDialog tidialog = new TextInputDialog(frame, bibEntry); tidialog.setLocationRelativeTo(BasePanel.this); tidialog.setVisible(true); if (tidialog.okPressed()) { UpdateField.setAutomaticFields(Collections.singletonList(bibEntry), false, false, Globals.prefs.getUpdateFieldPreferences()); insertEntry(bibEntry); } }); actions.put(Actions.MARK_ENTRIES, new MarkEntriesAction(frame, 0)); actions.put(Actions.UNMARK_ENTRIES, (BaseAction) () -> { try { List<BibEntry> bes = mainTable.getSelectedEntries(); if (bes.isEmpty()) { output(Localization.lang("This operation requires one or more entries to be selected.")); return; } NamedCompound ce = new NamedCompound(Localization.lang("Unmark entries")); for (BibEntry be : bes) { EntryMarker.unmarkEntry(be, false, bibDatabaseContext.getDatabase(), ce); } ce.end(); getUndoManager().addEdit(ce); markBaseChanged(); String outputStr; if (bes.size() == 1) { outputStr = Localization.lang("Unmarked selected entry"); } else { outputStr = Localization.lang("Unmarked all %0 selected entries", Integer.toString(bes.size())); } output(outputStr); } catch (Throwable ex) { LOGGER.warn("Could not unmark", ex); } }); actions.put(Actions.UNMARK_ALL, (BaseAction) () -> { NamedCompound ce = new NamedCompound(Localization.lang("Unmark all")); for (BibEntry be : bibDatabaseContext.getDatabase().getEntries()) { EntryMarker.unmarkEntry(be, false, bibDatabaseContext.getDatabase(), ce); } ce.end(); getUndoManager().addEdit(ce); markBaseChanged(); output(Localization.lang("Unmarked all entries")); }); // Note that we can't put the number of entries that have been reverted into the undoText as the concrete number cannot be injected actions.put(Relevance.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Relevance.getInstance(), Relevance.getInstance().getValues().get(0).getFieldValue().get(), true, Localization.lang("Toggle relevance"))); actions.put(Quality.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Quality.getInstance(), Quality.getInstance().getValues().get(0).getFieldValue().get(), true, Localization.lang("Toggle quality assured"))); actions.put(Printed.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Printed.getInstance(), Printed.getInstance().getValues().get(0).getFieldValue().get(), true, Localization.lang("Toggle print status"))); for (SpecialFieldValue prio : Priority.getInstance().getValues()) { actions.put(prio.getActionName(), prio.getAction(this.frame)); } for (SpecialFieldValue rank : Rank.getInstance().getValues()) { actions.put(rank.getActionName(), rank.getAction(this.frame)); } for (SpecialFieldValue status : ReadStatus.getInstance().getValues()) { actions.put(status.getActionName(), status.getAction(this.frame)); } actions.put(Actions.TOGGLE_PREVIEW, (BaseAction) () -> { PreviewPreferences previewPreferences = Globals.prefs.getPreviewPreferences(); boolean enabled = !previewPreferences.isPreviewPanelEnabled(); PreviewPreferences newPreviewPreferences = previewPreferences .getBuilder() .withPreviewPanelEnabled(enabled) .build(); Globals.prefs.storePreviewPreferences(newPreviewPreferences); setPreviewActiveBasePanels(enabled); frame.setPreviewToggle(enabled); }); actions.put(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ANY, (BaseAction) () -> { new HighlightMatchingGroupPreferences(Globals.prefs).setToAny(); // ping the listener so it updates: groupsHighlightListener.listChanged(null); }); actions.put(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ALL, (BaseAction) () -> { new HighlightMatchingGroupPreferences(Globals.prefs).setToAll(); // ping the listener so it updates: groupsHighlightListener.listChanged(null); }); actions.put(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_DISABLE, (BaseAction) () -> { new HighlightMatchingGroupPreferences(Globals.prefs).setToDisabled(); // ping the listener so it updates: groupsHighlightListener.listChanged(null); }); actions.put(Actions.NEXT_PREVIEW_STYLE, (BaseAction) selectionListener::nextPreviewStyle); actions.put(Actions.PREVIOUS_PREVIEW_STYLE, (BaseAction) selectionListener::previousPreviewStyle); actions.put(Actions.EXPORT_TO_CLIPBOARD, new ExportToClipboardAction(frame)); actions.put(Actions.SEND_AS_EMAIL, new SendAsEMailAction(frame)); actions.put(Actions.WRITE_XMP, new WriteXMPAction(this)); actions.put(Actions.ABBREVIATE_ISO, new AbbreviateAction(this, true)); actions.put(Actions.ABBREVIATE_MEDLINE, new AbbreviateAction(this, false)); actions.put(Actions.UNABBREVIATE, new UnabbreviateAction(this)); actions.put(Actions.AUTO_SET_FILE, new SynchronizeFileField(this)); actions.put(Actions.BACK, (BaseAction) BasePanel.this::back); actions.put(Actions.FORWARD, (BaseAction) BasePanel.this::forward); actions.put(Actions.RESOLVE_DUPLICATE_KEYS, new SearchFixDuplicateLabels(this)); actions.put(Actions.ADD_TO_GROUP, new GroupAddRemoveDialog(this, true, false)); actions.put(Actions.REMOVE_FROM_GROUP, new GroupAddRemoveDialog(this, false, false)); actions.put(Actions.MOVE_TO_GROUP, new GroupAddRemoveDialog(this, true, true)); actions.put(Actions.DOWNLOAD_FULL_TEXT, new FindFullTextAction(this)); } private void copy() { List<BibEntry> bes = mainTable.getSelectedEntries(); if (bes.isEmpty()) { // The user maybe selected a single cell. // TODO: Check if this can actually happen int[] rows = mainTable.getSelectedRows(); int[] cols = mainTable.getSelectedColumns(); if ((cols.length == 1) && (rows.length == 1)) { // Copy single value. Object o = mainTable.getValueAt(rows[0], cols[0]); if (o != null) { StringSelection ss = new StringSelection(o.toString()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, BasePanel.this); output(Localization.lang("Copied cell contents") + '.'); } } } else { TransferableBibtexEntry trbe = new TransferableBibtexEntry(bes); // ! look at ClipBoardManager Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trbe, BasePanel.this); output(formatOutputMessage(Localization.lang("Copied"), bes.size())); } } private void cut() { runCommand(Actions.COPY); // cannot call runCommand(Actions.DELETE), b/c it will call delete(false) with the wrong parameter delete(true); } /** * Removes the selected entries from the database * @param cut If false the user will get asked if he really wants to delete the entries, and it will be localized * as "deleted". * If true it will be localized as "cut" */ private void delete(boolean cut) { List<BibEntry> entries = mainTable.getSelectedEntries(); if (entries.isEmpty()) { return; } if (!cut && !showDeleteConfirmationDialog(entries.size())) { return; } // select the next entry to stay at the same place as before (or the previous if we're already at the end) if (mainTable.getSelectedRow() != mainTable.getRowCount() -1){ selectNextEntry(); } else { selectPreviousEntry(); } NamedCompound compound; if (!cut) { compound = new NamedCompound( (entries.size() > 1 ? Localization.lang("delete entries") : Localization.lang("delete entry"))); } else { compound = new NamedCompound( (entries.size() > 1 ? Localization.lang("cut entries") : Localization.lang("cut entry"))); } for (BibEntry entry : entries) { compound.addEdit(new UndoableRemoveEntry(bibDatabaseContext.getDatabase(), entry, BasePanel.this)); bibDatabaseContext.getDatabase().removeEntry(entry); ensureNotShowingBottomPanel(entry); } compound.end(); getUndoManager().addEdit(compound); markBaseChanged(); frame.output(formatOutputMessage(!cut ? Localization.lang("Deleted") : Localization.lang("Cut"), entries.size())); // prevent the main table from loosing focus mainTable.requestFocus(); } private void paste() { Collection<BibEntry> bes = new ClipBoardManager().extractBibEntriesFromClipboard(); // finally we paste in the entries (if any), which either came from TransferableBibtexEntries // or were parsed from a string if (!bes.isEmpty()) { NamedCompound ce = new NamedCompound( (bes.size() > 1 ? Localization.lang("paste entries") : Localization.lang("paste entry"))); // Store the first inserted bibtexentry. // bes[0] does not work as bes[0] is first clonded, // then inserted. // This entry is used to open up an entry editor // for the first inserted entry. BibEntry firstBE = null; for (BibEntry be1 : bes) { BibEntry be = (BibEntry) be1.clone(); if (firstBE == null) { firstBE = be; } UpdateField.setAutomaticFields(be, Globals.prefs.getUpdateFieldPreferences()); // We have to clone the // entries, since the pasted // entries must exist // independently of the copied // ones. be.setId(IdGenerator.next()); bibDatabaseContext.getDatabase().insertEntry(be); ce.addEdit(new UndoableInsertEntry(bibDatabaseContext.getDatabase(), be, BasePanel.this)); } ce.end(); getUndoManager().addEdit(ce); output(formatOutputMessage(Localization.lang("Pasted"), bes.size())); markBaseChanged(); highlightEntry(firstBE); mainTable.requestFocus(); if (Globals.prefs.getBoolean(JabRefPreferences.AUTO_OPEN_FORM)) { selectionListener.editSignalled(firstBE); } } } private void copyCiteKey() { List<BibEntry> bes = mainTable.getSelectedEntries(); if (!bes.isEmpty()) { storeCurrentEdit(); List<String> keys = new ArrayList<>(bes.size()); // Collect all non-null keys. for (BibEntry be : bes) { be.getCiteKeyOptional().ifPresent(keys::add); } if (keys.isEmpty()) { output(Localization.lang("None of the selected entries have BibTeX keys.")); return; } String sb = String.join(",", keys); StringSelection ss = new StringSelection("\\cite{" + sb + '}'); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, BasePanel.this); if (keys.size() == bes.size()) { // All entries had keys. output(bes.size() > 1 ? Localization.lang("Copied keys") : Localization.lang("Copied key") + '.'); } else { output(Localization.lang("Warning: %0 out of %1 entries have undefined BibTeX key.", Integer.toString(bes.size() - keys.size()), Integer.toString(bes.size()))); } } } private void copyKey() { List<BibEntry> bes = mainTable.getSelectedEntries(); if (!bes.isEmpty()) { storeCurrentEdit(); List<String> keys = new ArrayList<>(bes.size()); // Collect all non-null keys. for (BibEntry be : bes) { be.getCiteKeyOptional().ifPresent(keys::add); } if (keys.isEmpty()) { output(Localization.lang("None of the selected entries have BibTeX keys.")); return; } StringSelection ss = new StringSelection(String.join(",", keys)); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, BasePanel.this); if (keys.size() == bes.size()) { // All entries had keys. output((bes.size() > 1 ? Localization.lang("Copied keys") : Localization.lang("Copied key")) + '.'); } else { output(Localization.lang("Warning: %0 out of %1 entries have undefined BibTeX key.", Integer.toString(bes.size() - keys.size()), Integer.toString(bes.size()))); } } } private void copyKeyAndTitle() { List<BibEntry> bes = mainTable.getSelectedEntries(); if (!bes.isEmpty()) { storeCurrentEdit(); // OK: in a future version, this string should be configurable to allow arbitrary exports StringReader sr = new StringReader( "\\bibtexkey - \\begin{title}\\format[RemoveBrackets]{\\title}\\end{title}\n"); Layout layout; try { layout = new LayoutHelper(sr, Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader)) .getLayoutFromText(); } catch (IOException e) { LOGGER.info("Could not get layout", e); return; } StringBuilder sb = new StringBuilder(); int copied = 0; // Collect all non-null keys. for (BibEntry be : bes) { if (be.hasCiteKey()) { copied++; sb.append(layout.doLayout(be, bibDatabaseContext.getDatabase())); } } if (copied == 0) { output(Localization.lang("None of the selected entries have BibTeX keys.")); return; } final StringSelection ss = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, BasePanel.this); if (copied == bes.size()) { // All entries had keys. output((bes.size() > 1 ? Localization.lang("Copied keys") : Localization.lang("Copied key")) + '.'); } else { output(Localization.lang("Warning: %0 out of %1 entries have undefined BibTeX key.", Integer.toString(bes.size() - copied), Integer.toString(bes.size()))); } } } private void openExternalFile() { JabRefExecutorService.INSTANCE.execute(() -> { final List<BibEntry> bes = mainTable.getSelectedEntries(); if (bes.size() != 1) { output(Localization.lang("This operation requires exactly one item to be selected.")); return; } final BibEntry entry = bes.get(0); if (!entry.hasField(FieldName.FILE)) { // no bibtex field new SearchAndOpenFile(entry, BasePanel.this).searchAndOpen(); return; } FileListTableModel fileListTableModel = new FileListTableModel(); entry.getField(FieldName.FILE).ifPresent(fileListTableModel::setContent); if (fileListTableModel.getRowCount() == 0) { // content in BibTeX field is not readable new SearchAndOpenFile(entry, BasePanel.this).searchAndOpen(); return; } FileListEntry flEntry = fileListTableModel.getEntry(0); ExternalFileMenuItem item = new ExternalFileMenuItem(frame(), entry, "", flEntry.link, flEntry.type.get().getIcon(), bibDatabaseContext, flEntry.type); item.openLink(); }); } /** * This method is called from JabRefFrame if a database specific action is requested by the user. Runs the command * if it is defined, or prints an error message to the standard error stream. * * @param _command The name of the command to run. */ public void runCommand(final String _command) { if (!actions.containsKey(_command)) { LOGGER.info("No action defined for '" + _command + '\''); return; } Object o = actions.get(_command); try { if (o instanceof BaseAction) { ((BaseAction) o).action(); } else { // This part uses Spin's features: Worker wrk = ((AbstractWorker) o).getWorker(); // The Worker returned by getWorker() has been wrapped // by Spin.off(), which makes its methods be run in // a different thread from the EDT. CallBack clb = ((AbstractWorker) o).getCallBack(); ((AbstractWorker) o).init(); // This method runs in this same thread, the EDT. // Useful for initial GUI actions, like printing a message. // The CallBack returned by getCallBack() has been wrapped // by Spin.over(), which makes its methods be run on // the EDT. wrk.run(); // Runs the potentially time-consuming action // without freezing the GUI. The magic is that THIS line // of execution will not continue until run() is finished. clb.update(); // Runs the update() method on the EDT. } } catch (Throwable ex) { // If the action has blocked the JabRefFrame before crashing, we need to unblock it. // The call to unblock will simply hide the glasspane, so there is no harm in calling // it even if the frame hasn't been blocked. frame.unblock(); LOGGER.error("runCommand error: " + ex.getMessage(), ex); } } private boolean saveDatabase(File file, boolean selectedOnly, Charset enc, SavePreferences.DatabaseSaveType saveType) throws SaveException { SaveSession session; frame.block(); final String SAVE_DATABASE = Localization.lang("Save database"); try { SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withEncoding(enc) .withSaveType(saveType); BibtexDatabaseWriter<SaveSession> databaseWriter = new BibtexDatabaseWriter<>( FileSaveSession::new); if (selectedOnly) { session = databaseWriter.savePartOfDatabase(bibDatabaseContext, mainTable.getSelectedEntries(), prefs); } else { session = databaseWriter.saveDatabase(bibDatabaseContext, prefs); } registerUndoableChanges(session); } // FIXME: not sure if this is really thrown anywhere catch (UnsupportedCharsetException ex) { JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + ' ' + Localization.lang("Character encoding '%0' is not supported.", enc.displayName()), SAVE_DATABASE, JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } catch (SaveException ex) { if (ex.specificEntry()) { // Error occurred during processing of the entry. Highlight it: highlightEntry(ex.getEntry()); showEntry(ex.getEntry()); } else { LOGGER.warn("Could not save", ex); } JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + ex.getMessage(), SAVE_DATABASE, JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } finally { frame.unblock(); } boolean commit = true; if (!session.getWriter().couldEncodeAll()) { FormBuilder builder = FormBuilder.create() .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref")); JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters()); ta.setEditable(false); builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName())).xy(1, 1); builder.add(ta).xy(3, 1); builder.add(Localization.lang("What do you want to do?")).xy(1, 3); String tryDiff = Localization.lang("Try different encoding"); int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), SAVE_DATABASE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {Localization.lang("Save"), tryDiff, Localization.lang("Cancel")}, tryDiff); if (answer == JOptionPane.NO_OPTION) { // The user wants to use another encoding. Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"), SAVE_DATABASE, JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, enc); if (choice == null) { commit = false; } else { Charset newEncoding = Charset.forName((String) choice); return saveDatabase(file, selectedOnly, newEncoding, saveType); } } else if (answer == JOptionPane.CANCEL_OPTION) { commit = false; } } if (commit) { session.commit(file.toPath()); this.bibDatabaseContext.getMetaData().setEncoding(enc); // Make sure to remember which encoding we used. } else { session.cancel(); } return commit; } public void registerUndoableChanges(SaveSession session) { NamedCompound ce = new NamedCompound(Localization.lang("Save actions")); for (FieldChange change : session.getFieldChanges()) { ce.addEdit(new UndoableFieldChange(change)); } ce.end(); if (ce.hasEdits()) { getUndoManager().addEdit(ce); } } /** * This method is called from JabRefFrame when the user wants to create a new entry. If the argument is null, the * user is prompted for an entry type. * * @param type The type of the entry to create. * @return The newly created BibEntry or null the operation was canceled by the user. */ public BibEntry newEntry(EntryType type) { EntryType actualType = type; if (actualType == null) { // Find out what type is wanted. final EntryTypeDialog etd = new EntryTypeDialog(frame); // We want to center the dialog, to make it look nicer. etd.setLocationRelativeTo(frame); etd.setVisible(true); actualType = etd.getChoice(); } if (actualType != null) { // Only if the dialog was not canceled. String id = IdGenerator.next(); final BibEntry be = new BibEntry(id, actualType.getName()); try { bibDatabaseContext.getDatabase().insertEntry(be); // Set owner/timestamp if options are enabled: List<BibEntry> list = new ArrayList<>(); list.add(be); UpdateField.setAutomaticFields(list, true, true, Globals.prefs.getUpdateFieldPreferences()); // Create an UndoableInsertEntry object. getUndoManager().addEdit(new UndoableInsertEntry(bibDatabaseContext.getDatabase(), be, BasePanel.this)); output(Localization.lang("Added new '%0' entry.", actualType.getName().toLowerCase())); // We are going to select the new entry. Before that, make sure that we are in // show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR // mode which makes sure the selection will trigger display of the entry editor // and adjustment of the splitter. if (mode != BasePanelMode.SHOWING_EDITOR) { mode = BasePanelMode.WILL_SHOW_EDITOR; } highlightEntry(be); // The database just changed. markBaseChanged(); final EntryEditor entryEditor = getEntryEditor(be); this.showEntryEditor(entryEditor); entryEditor.requestFocus(); return be; } catch (KeyCollisionException ex) { LOGGER.info(ex.getMessage(), ex); } } return null; } private class GroupTreeListener { private final Runnable task = new Runnable() { @Override public void run() { // Update group display (for example to reflect that the number of contained entries has changed) frame.getGroupSelector().revalidateGroups(); } }; /** * Only access when you have the lock of the task instance * * Guarded by "task" */ private TimerTask timerTask = new TimerTask() { @Override public void run() { task.run(); } }; @Subscribe public void listen(EntryAddedEvent addedEntryEvent) { // if the added entry is an undo don't add it to the current group if (addedEntryEvent.getEntryEventSource() == EntryEventSource.UNDO) { scheduleUpdate(); return; } // Automatically add new entry to the selected group (or set of groups) if (Globals.prefs.getBoolean(JabRefPreferences.AUTO_ASSIGN_GROUP) && frame.getGroupSelector().getToggleAction().isSelected()) { final List<BibEntry> entries = Collections.singletonList(addedEntryEvent.getBibEntry()); final TreePath[] selection = frame.getGroupSelector().getGroupsTree().getSelectionPaths(); if (selection != null) { // it is possible that the user selected nothing. Therefore, checked for "!= null" for (final TreePath tree : selection) { ((GroupTreeNodeViewModel) tree.getLastPathComponent()).addEntriesToGroup(entries); } } SwingUtilities.invokeLater(() -> BasePanel.this.getGroupSelector().valueChanged(null)); } scheduleUpdate(); } private void scheduleUpdate() { // This is a quickfix/dirty hack. // a better solution would be using RxJava or something reactive instead // nevertheless it works correctly synchronized (task) { timerTask.cancel(); timerTask = new TimerTask() { @Override public void run() { task.run(); } }; JabRefExecutorService.INSTANCE.submit(timerTask, 200); } } } /** * Ensures that the search auto completer is up to date when entries are changed AKA Let the auto completer, if any, * harvest words from the entry */ private class SearchAutoCompleteListener { @Subscribe public void listen(EntryAddedEvent addedEntryEvent) { searchAutoCompleter.addBibtexEntry(addedEntryEvent.getBibEntry()); } @Subscribe public void listen(EntryChangedEvent entryChangedEvent) { searchAutoCompleter.addBibtexEntry(entryChangedEvent.getBibEntry()); } } /** * Ensures that auto completers are up to date when entries are changed AKA Let the auto completer, if any, harvest * words from the entry */ private class AutoCompleteListener { @Subscribe public void listen(EntryAddedEvent addedEntryEvent) { BasePanel.this.autoCompleters.addEntry(addedEntryEvent.getBibEntry()); } @Subscribe public void listen(EntryChangedEvent entryChangedEvent) { BasePanel.this.autoCompleters.addEntry(entryChangedEvent.getBibEntry()); } } /** * Ensures that the results of the current search are updated when a new entry is inserted into the database */ private class SearchListener { @Subscribe public void listen(EntryAddedEvent addedEntryEvent) { frame.getGlobalSearchBar().performSearch(); } @Subscribe public void listen(EntryChangedEvent entryChangedEvent) { frame.getGlobalSearchBar().setDontSelectSearchBar(true); frame.getGlobalSearchBar().performSearch(); } @Subscribe public void listen(EntryRemovedEvent removedEntryEvent) { // IMO only used to update the status (found X entries) frame.getGlobalSearchBar().performSearch(); } } /** * This method is called from JabRefFrame when the user wants to create a new entry. * * @param bibEntry The new entry. */ public void insertEntry(final BibEntry bibEntry) { if (bibEntry != null) { try { bibDatabaseContext.getDatabase().insertEntry(bibEntry); if (Globals.prefs.getBoolean(JabRefPreferences.USE_OWNER)) { // Set owner field to default value UpdateField.setAutomaticFields(bibEntry, true, true, Globals.prefs.getUpdateFieldPreferences()); } // Create an UndoableInsertEntry object. getUndoManager() .addEdit(new UndoableInsertEntry(bibDatabaseContext.getDatabase(), bibEntry, BasePanel.this)); output(Localization.lang("Added new '%0' entry.", bibEntry.getType())); markBaseChanged(); // The database just changed. if (Globals.prefs.getBoolean(JabRefPreferences.AUTO_OPEN_FORM)) { selectionListener.editSignalled(bibEntry); } highlightEntry(bibEntry); } catch (KeyCollisionException ex) { LOGGER.info("Collision for bibtex key" + bibEntry.getId(), ex); } } } public void editEntryByKeyAndFocusField(final String bibtexKey, final String fieldName) { final List<BibEntry> entries = bibDatabaseContext.getDatabase().getEntriesByKey(bibtexKey); if (entries.size() == 1) { mainTable.setSelected(mainTable.findEntry(entries.get(0))); selectionListener.editSignalled(); final EntryEditor editor = getEntryEditor(entries.get(0)); editor.setFocusToField(fieldName); this.showEntryEditor(editor); editor.requestFocus(); } } public void updateTableFont() { mainTable.updateFont(); } private void createMainTable() { bibDatabaseContext.getDatabase().registerListener(tableModel.getListSynchronizer()); bibDatabaseContext.getDatabase().registerListener(SpecialFieldDatabaseChangeListener.getInstance()); tableFormat = new MainTableFormat(bibDatabaseContext.getDatabase()); tableFormat.updateTableFormat(); mainTable = new MainTable(tableFormat, tableModel, frame, this); selectionListener = new MainTableSelectionListener(this, mainTable); mainTable.updateFont(); mainTable.addSelectionListener(selectionListener); mainTable.addMouseListener(selectionListener); mainTable.addKeyListener(selectionListener); mainTable.addFocusListener(selectionListener); // Add the listener that will take care of highlighting groups as the selection changes: groupsHighlightListener = listEvent -> { HighlightMatchingGroupPreferences highlightMatchingGroupPreferences = new HighlightMatchingGroupPreferences( Globals.prefs); if (highlightMatchingGroupPreferences.isAny()) { getGroupSelector().showMatchingGroups(mainTable.getSelectedEntries(), false); } else if (highlightMatchingGroupPreferences.isAll()) { getGroupSelector().showMatchingGroups(mainTable.getSelectedEntries(), true); } else { // no highlight getGroupSelector().showMatchingGroups(null, true); } }; mainTable.addSelectionListener(groupsHighlightListener); String clearSearch = "clearSearch"; mainTable.getInputMap().put(Globals.getKeyPrefs().getKey(KeyBinding.CLEAR_SEARCH), clearSearch); mainTable.getActionMap().put(clearSearch, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { // need to close these here, b/c this action overshadows the responsible actions when the main table is selected switch (mode) { case SHOWING_NOTHING: frame.getGlobalSearchBar().endSearch(); break; case SHOWING_PREVIEW: getPreviewPanel().close(); break; case SHOWING_EDITOR: case WILL_SHOW_EDITOR: getCurrentEditor().close(); break; default: LOGGER.warn("unknown BasePanelMode: '" + mode + "', doing nothing"); break; } } }); mainTable.getActionMap().put(Actions.CUT, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { runCommand(Actions.CUT); } catch (Throwable ex) { LOGGER.warn("Could not cut", ex); } } }); mainTable.getActionMap().put(Actions.COPY, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { runCommand(Actions.COPY); } catch (Throwable ex) { LOGGER.warn("Could not copy", ex); } } }); mainTable.getActionMap().put(Actions.PASTE, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { runCommand(Actions.PASTE); } catch (Throwable ex) { LOGGER.warn("Could not paste", ex); } } }); mainTable.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { final int keyCode = e.getKeyCode(); final TreePath path = frame.getGroupSelector().getSelectionPath(); final GroupTreeNodeViewModel node = path == null ? null : (GroupTreeNodeViewModel) path .getLastPathComponent(); if (e.isControlDown()) { switch (keyCode) { // The up/down/left/rightkeystrokes are displayed in the // GroupSelector's popup menu, so if they are to be changed, // edit GroupSelector.java accordingly! case KeyEvent.VK_UP: e.consume(); if (node != null) { frame.getGroupSelector().moveNodeUp(node, true); } break; case KeyEvent.VK_DOWN: e.consume(); if (node != null) { frame.getGroupSelector().moveNodeDown(node, true); } break; case KeyEvent.VK_LEFT: e.consume(); if (node != null) { frame.getGroupSelector().moveNodeLeft(node, true); } break; case KeyEvent.VK_RIGHT: e.consume(); if (node != null) { frame.getGroupSelector().moveNodeRight(node, true); } break; case KeyEvent.VK_PAGE_DOWN: frame.nextTab.actionPerformed(null); e.consume(); break; case KeyEvent.VK_PAGE_UP: frame.prevTab.actionPerformed(null); e.consume(); break; default: break; } } else if (keyCode == KeyEvent.VK_ENTER) { e.consume(); try { runCommand(Actions.EDIT); } catch (Throwable ex) { LOGGER.warn("Could not run action based on key press", ex); } } } }); } public void setupMainPanel() { splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setDividerSize(SPLIT_PANE_DIVIDER_SIZE); adjustSplitter(); // restore last splitting state (before mainTable is created as creation affects the stored size of the entryEditors) // check whether a mainTable already existed and a floatSearch was active boolean floatSearchActive = (mainTable != null) && (this.tableModel.getSearchState() == MainTableDataModel.DisplayOption.FLOAT); createMainTable(); splitPane.setTopComponent(mainTable.getPane()); // Remove borders splitPane.setBorder(BorderFactory.createEmptyBorder()); setBorder(BorderFactory.createEmptyBorder()); // If an entry is currently being shown, make sure it stays shown, // otherwise set the bottom component to null. if (mode == BasePanelMode.SHOWING_PREVIEW) { mode = BasePanelMode.SHOWING_NOTHING; highlightEntry(selectionListener.getPreview().getEntry()); } else if (mode == BasePanelMode.SHOWING_EDITOR) { mode = BasePanelMode.SHOWING_NOTHING; } else { splitPane.setBottomComponent(null); } setLayout(new BorderLayout()); removeAll(); add(splitPane, BorderLayout.CENTER); // Set up name autocompleter for search: instantiateSearchAutoCompleter(); this.getDatabase().registerListener(new SearchAutoCompleteListener()); AutoCompletePreferences autoCompletePreferences = new AutoCompletePreferences(Globals.prefs); // Set up AutoCompleters for this panel: if (Globals.prefs.getBoolean(JabRefPreferences.AUTO_COMPLETE)) { autoCompleters = new ContentAutoCompleters(getDatabase(), autoCompletePreferences, Globals.journalAbbreviationLoader); // ensure that the autocompleters are in sync with entries this.getDatabase().registerListener(new AutoCompleteListener()); } else { // create empty ContentAutoCompleters() if autoCompletion is deactivated autoCompleters = new ContentAutoCompleters(); } // restore floating search result // (needed if preferences have been changed which causes a recreation of the main table) if (floatSearchActive) { mainTable.showFloatSearch(); } splitPane.revalidate(); revalidate(); repaint(); // saves the divider position as soon as it changes splitPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, event -> saveDividerLocation()); } public void updateSearchManager() { frame.getGlobalSearchBar().setAutoCompleter(searchAutoCompleter); } private void instantiateSearchAutoCompleter() { AutoCompletePreferences autoCompletePreferences = new AutoCompletePreferences(Globals.prefs); AutoCompleterFactory autoCompleterFactory = new AutoCompleterFactory(autoCompletePreferences, Globals.journalAbbreviationLoader); searchAutoCompleter = autoCompleterFactory.getPersonAutoCompleter(); for (BibEntry entry : bibDatabaseContext.getDatabase().getEntries()) { searchAutoCompleter.addBibtexEntry(entry); } } public void updatePreamble() { if (preambleEditor != null) { preambleEditor.updatePreamble(); } } public void assureStringDialogNotEditing() { if (stringDialog != null) { stringDialog.assureNotEditing(); } } public void updateStringDialog() { if (stringDialog != null) { stringDialog.refreshTable(); } } public void adjustSplitter() { if (mode == BasePanelMode.SHOWING_PREVIEW) { splitPane.setDividerLocation( splitPane.getHeight() - Globals.prefs.getPreviewPreferences().getPreviewPanelHeight()); } else { splitPane.setDividerLocation( splitPane.getHeight() - Globals.prefs.getInt(JabRefPreferences.ENTRY_EDITOR_HEIGHT)); } } private boolean isShowingEditor() { return (splitPane.getBottomComponent() != null) && (splitPane.getBottomComponent() instanceof EntryEditor); } public void showEntry(final BibEntry be) { if (getShowing() == be) { if (splitPane.getBottomComponent() == null) { // This is the special occasion when showing is set to an // entry, but no entry editor is in fact shown. This happens // after Preferences dialog is closed, and it means that we // must make sure the same entry is shown again. We do this by // setting showing to null, and recursively calling this method. newEntryShowing(null); showEntry(be); } else { // The correct entry is already being shown. Make sure the editor // is updated. ((EntryEditor) splitPane.getBottomComponent()).updateAllFields(); } return; } EntryEditor entryEditor; int divLoc = -1; String visName = null; if ((getShowing() != null) && isShowingEditor()) { visName = ((EntryEditor) splitPane.getBottomComponent()).getVisiblePanelName(); } if (getShowing() != null) { divLoc = splitPane.getDividerLocation(); } // We must instantiate a new editor. entryEditor = new EntryEditor(frame, BasePanel.this, be); if (visName != null) { entryEditor.setVisiblePanel(visName); } splitPane.setBottomComponent(entryEditor); if (divLoc > 0) { splitPane.setDividerLocation(divLoc); } else { splitPane.setDividerLocation( splitPane.getHeight() - Globals.prefs.getInt(JabRefPreferences.ENTRY_EDITOR_HEIGHT)); } newEntryShowing(be); setEntryEditorEnabled(true); // Make sure it is enabled. } /** * Get an entry editor ready to edit the given entry. If an appropriate editor is already cached, it will be updated * and returned. * * @param entry The entry to be edited. * @return A suitable entry editor. */ public EntryEditor getEntryEditor(BibEntry entry) { EntryEditor entryEditor; // We must instantiate a new editor. First make sure the old one // stores its last edit: storeCurrentEdit(); // Then start the new one: entryEditor = new EntryEditor(frame, BasePanel.this, entry); return entryEditor; } public EntryEditor getCurrentEditor() { return currentEditor; } /** * Sets the given entry editor as the bottom component in the split pane. If an entry editor already was shown, * makes sure that the divider doesn't move. Updates the mode to SHOWING_EDITOR. * * @param editor The entry editor to add. */ public void showEntryEditor(EntryEditor editor) { if (mode == BasePanelMode.SHOWING_EDITOR) { Globals.prefs.putInt(JabRefPreferences.ENTRY_EDITOR_HEIGHT, splitPane.getHeight() - splitPane.getDividerLocation()); } mode = BasePanelMode.SHOWING_EDITOR; currentEditor = editor; splitPane.setBottomComponent(editor); if (editor.getEntry() != getShowing()) { newEntryShowing(editor.getEntry()); } adjustSplitter(); } /** * Sets the given preview panel as the bottom component in the split panel. Updates the mode to SHOWING_PREVIEW. * * @param preview The preview to show. */ public void showPreview(PreviewPanel preview) { mode = BasePanelMode.SHOWING_PREVIEW; splitPane.setBottomComponent(preview); adjustSplitter(); } /** * Removes the bottom component. */ public void hideBottomComponent() { mode = BasePanelMode.SHOWING_NOTHING; splitPane.setBottomComponent(null); } /** * This method selects the given entry, and scrolls it into view in the table. If an entryEditor is shown, it is * given focus afterwards. */ public void highlightEntry(final BibEntry bibEntry) { highlightEntry(mainTable.findEntry(bibEntry)); } /** * This method selects the entry on the given position, and scrolls it into view in the table. * If an entryEditor is shown, it is given focus afterwards. */ public void highlightEntry(int pos) { if ((pos >= 0) && (pos < mainTable.getRowCount())) { mainTable.setRowSelectionInterval(pos, pos); mainTable.ensureVisible(pos); } } public void selectPreviousEntry() { highlightEntry(((mainTable.getSelectedRow() - 1) + mainTable.getRowCount()) % mainTable.getRowCount()); } public void selectNextEntry() { highlightEntry((mainTable.getSelectedRow() + 1) % mainTable.getRowCount()); } public void selectFirstEntry() { highlightEntry(0); } public void selectLastEntry() { highlightEntry(mainTable.getRowCount() - 1); } /** * This method is called from an EntryEditor when it should be closed. We relay to the selection listener, which * takes care of the rest. * * @param editor The entry editor to close. */ public void entryEditorClosing(EntryEditor editor) { // Store divider location for next time: Globals.prefs.putInt(JabRefPreferences.ENTRY_EDITOR_HEIGHT, splitPane.getHeight() - splitPane.getDividerLocation()); selectionListener.entryEditorClosing(editor); } /** * Closes the entry editor or preview panel if it is showing the given entry. */ public void ensureNotShowingBottomPanel(BibEntry entry) { if (((mode == BasePanelMode.SHOWING_EDITOR) && (currentEditor.getEntry() == entry)) || ((mode == BasePanelMode.SHOWING_PREVIEW) && (selectionListener.getPreview().getEntry() == entry))) { hideBottomComponent(); } } public void updateEntryEditorIfShowing() { if (mode == BasePanelMode.SHOWING_EDITOR) { if (currentEditor.getDisplayedBibEntryType().equals(currentEditor.getEntry().getType())) { currentEditor.updateAllFields(); currentEditor.updateSource(); } else { // The entry has changed type, so we must get a new editor. newEntryShowing(null); final EntryEditor newEditor = getEntryEditor(currentEditor.getEntry()); showEntryEditor(newEditor); } } } /** * If an entry editor is showing, make sure its currently focused field stores its changes, if any. */ public void storeCurrentEdit() { if (isShowingEditor()) { final EntryEditor editor = (EntryEditor) splitPane.getBottomComponent(); editor.storeCurrentEdit(); } } public void markBaseChanged() { baseChanged = true; if (SwingUtilities.isEventDispatchThread()) { markBasedChangedInternal(); } else { try { SwingUtilities.invokeAndWait(() -> markBasedChangedInternal()); } catch (InvocationTargetException | InterruptedException e) { LOGGER.info("Problem marking database as changed", e); } } } private void markBasedChangedInternal() { // Put an asterisk behind the filename to indicate the database has changed. frame.setWindowTitle(); frame.updateAllTabTitles(); // If the status line states that the base has been saved, we // remove this message, since it is no longer relevant. If a // different message is shown, we leave it. if (frame.getStatusLineText().startsWith(Localization.lang("Saved database"))) { frame.output(" "); } } public void markNonUndoableBaseChanged() { nonUndoableChange = true; markBaseChanged(); } private synchronized void markChangedOrUnChanged() { if (getUndoManager().hasChanged()) { if (!baseChanged) { markBaseChanged(); } } else if (baseChanged && !nonUndoableChange) { baseChanged = false; if (getBibDatabaseContext().getDatabaseFile().isPresent()) { frame.setTabTitle(this, getTabTitle(), getBibDatabaseContext().getDatabaseFile().get().getAbsolutePath()); } else { frame.setTabTitle(this, GUIGlobals.UNTITLED_TITLE, null); } } frame.setWindowTitle(); } public BibDatabase getDatabase() { return bibDatabaseContext.getDatabase(); } public void preambleEditorClosing() { preambleEditor = null; } public void stringsClosing() { stringDialog = null; } public void changeTypeOfSelectedEntries(String newType) { List<BibEntry> bes = mainTable.getSelectedEntries(); changeType(bes, newType); } private void changeType(List<BibEntry> entries, String newType) { if ((entries == null) || (entries.isEmpty())) { LOGGER.error("At least one entry must be selected to be able to change the type."); return; } if (entries.size() > 1) { int choice = JOptionPane.showConfirmDialog(this, Localization.lang("Multiple entries selected. Do you want to change the type of all these to '%0'?", newType), Localization.lang("Change entry type"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) { return; } } NamedCompound compound = new NamedCompound(Localization.lang("Change entry type")); for (BibEntry entry : entries) { compound.addEdit(new UndoableChangeType(entry, entry.getType(), newType)); entry.setType(newType); } output(formatOutputMessage(Localization.lang("Changed type to '%0' for", newType), entries.size())); compound.end(); getUndoManager().addEdit(compound); markBaseChanged(); updateEntryEditorIfShowing(); } public boolean showDeleteConfirmationDialog(int numberOfEntries) { if (Globals.prefs.getBoolean(JabRefPreferences.CONFIRM_DELETE)) { String msg; msg = Localization.lang("Really delete the selected entry?"); String title = Localization.lang("Delete entry"); if (numberOfEntries > 1) { msg = Localization.lang("Really delete the %0 selected entries?", Integer.toString(numberOfEntries)); title = Localization.lang("Delete multiple entries"); } CheckBoxMessage cb = new CheckBoxMessage(msg, Localization.lang("Disable this confirmation dialog"), false); int answer = JOptionPane.showConfirmDialog(frame, cb, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (cb.isSelected()) { Globals.prefs.putBoolean(JabRefPreferences.CONFIRM_DELETE, false); } return answer == JOptionPane.YES_OPTION; } else { return true; } } /** * If the relevant option is set, autogenerate keys for all entries that are lacking keys. */ public void autoGenerateKeysBeforeSaving() { if (Globals.prefs.getBoolean(JabRefPreferences.GENERATE_KEYS_BEFORE_SAVING)) { NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate BibTeX keys")); for (BibEntry bes : bibDatabaseContext.getDatabase().getEntries()) { Optional<String> oldKey = bes.getCiteKeyOptional(); if (!(oldKey.isPresent()) || oldKey.get().isEmpty()) { BibtexKeyPatternUtil.makeLabel(bibDatabaseContext.getMetaData() .getCiteKeyPattern(Globals.prefs.getBibtexKeyPatternPreferences().getKeyPattern()), bibDatabaseContext.getDatabase(), bes, Globals.prefs.getBibtexKeyPatternPreferences()); ce.addEdit(new UndoableKeyChange(bes, oldKey.orElse(""), bes.getCiteKeyOptional().get())); } } // Store undo information, if any: if (ce.hasEdits()) { ce.end(); getUndoManager().addEdit(ce); } } } /** * Activates or deactivates the entry preview, depending on the argument. When deactivating, makes sure that any * visible preview is hidden. * * @param enabled */ private void setPreviewActive(boolean enabled) { selectionListener.setPreviewActive(enabled); } /** * Depending on whether a preview or an entry editor is showing, save the current divider location in the correct * preference setting. */ public void saveDividerLocation() { if (mode == BasePanelMode.SHOWING_PREVIEW) { int previewPanelHeight = splitPane.getHeight() - splitPane.getDividerLocation(); PreviewPreferences previewPreferences = Globals.prefs.getPreviewPreferences() .getBuilder() .withPreviewPanelHeight(previewPanelHeight) .build(); Globals.prefs.storePreviewPreferences(previewPreferences); } else if (mode == BasePanelMode.SHOWING_EDITOR) { Globals.prefs.putInt(JabRefPreferences.ENTRY_EDITOR_HEIGHT, splitPane.getHeight() - splitPane.getDividerLocation()); } } private class UndoAction implements BaseAction { @Override public void action() { try { JComponent focused = Globals.getFocusListener().getFocused(); if ((focused != null) && (focused instanceof FieldEditor) && focused.hasFocus()) { // User is currently editing a field: // Check if it is the preamble: if ((preambleEditor != null) && (focused == preambleEditor.getFieldEditor())) { preambleEditor.storeCurrentEdit(); } else { storeCurrentEdit(); } } getUndoManager().undo(); markBaseChanged(); frame.output(Localization.lang("Undo")); } catch (CannotUndoException ex) { LOGGER.warn("Nothing to undo", ex); frame.output(Localization.lang("Nothing to undo") + '.'); } markChangedOrUnChanged(); } } private class OpenURLAction implements BaseAction { @Override public void action() { final List<BibEntry> bes = mainTable.getSelectedEntries(); if (bes.size() == 1) { String field = FieldName.DOI; Optional<String> link = bes.get(0).getField(FieldName.DOI); if (bes.get(0).hasField(FieldName.URL)) { link = bes.get(0).getField(FieldName.URL); field = FieldName.URL; } if (link.isPresent()) { try { JabRefDesktop.openExternalViewer(bibDatabaseContext, link.get(), field); output(Localization.lang("External viewer called") + '.'); } catch (IOException ex) { output(Localization.lang("Error") + ": " + ex.getMessage()); } } else { // No URL or DOI found in the "url" and "doi" fields. // Look for web links in the "file" field as a fallback: FileListEntry entry = null; FileListTableModel tm = new FileListTableModel(); bes.get(0).getField(FieldName.FILE).ifPresent(tm::setContent); for (int i = 0; i < tm.getRowCount(); i++) { FileListEntry flEntry = tm.getEntry(i); if (FieldName.URL.equalsIgnoreCase(flEntry.type.get().getName()) || FieldName.PS.equalsIgnoreCase(flEntry.type.get().getName()) || FieldName.PDF.equalsIgnoreCase(flEntry.type.get().getName())) { entry = flEntry; break; } } if (entry == null) { output(Localization.lang("No URL defined") + '.'); } else { try { JabRefDesktop.openExternalFileAnyFormat(bibDatabaseContext, entry.link, entry.type); output(Localization.lang("External viewer called") + '.'); } catch (IOException e) { output(Localization.lang("Could not open link")); LOGGER.info("Could not open link", e); } } } } else { output(Localization.lang("This operation requires exactly one item to be selected.")); } } } private class RedoAction implements BaseAction { @Override public void action() { try { JComponent focused = Globals.getFocusListener().getFocused(); if ((focused != null) && (focused instanceof FieldEditor) && focused.hasFocus()) { // User is currently editing a field: storeCurrentEdit(); } getUndoManager().redo(); markBaseChanged(); frame.output(Localization.lang("Redo")); } catch (CannotRedoException ex) { frame.output(Localization.lang("Nothing to redo") + '.'); } markChangedOrUnChanged(); } } private class PrintPreviewAction implements BaseAction { @Override public void action() throws Exception { selectionListener.setPreviewActive(true); showPreview(selectionListener.getPreview()); selectionListener.getPreview().getPrintAction().actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)); } } // Method pertaining to the ClipboardOwner interface. @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { // Nothing } private void setEntryEditorEnabled(boolean enabled) { if ((getShowing() != null) && (splitPane.getBottomComponent() instanceof EntryEditor)) { EntryEditor ed = (EntryEditor) splitPane.getBottomComponent(); if (ed.isEnabled() != enabled) { ed.setEnabled(enabled); } } } public String fileMonitorHandle() { return fileMonitorHandle; } @Override public void fileUpdated() { if (saving) { // We are just saving the file, so this message is most likely due to bad timing. // If not, we'll handle it on the next polling. return; } updatedExternally = true; final ChangeScanner scanner = new ChangeScanner(frame, BasePanel.this, getBibDatabaseContext().getDatabaseFile().orElse(null)); // Test: running scan automatically in background if ((getBibDatabaseContext().getDatabaseFile().isPresent()) && !FileBasedLock.waitForFileLock(getBibDatabaseContext().getDatabaseFile().get().toPath())) { // The file is locked even after the maximum wait. Do nothing. LOGGER.error("File updated externally, but change scan failed because the file is locked."); // Perturb the stored timestamp so successive checks are made: Globals.getFileUpdateMonitor().perturbTimestamp(getFileMonitorHandle()); return; } JabRefExecutorService.INSTANCE.executeWithLowPriorityInOwnThreadAndWait(scanner); // Adding the sidepane component is Swing work, so we must do this in the Swing // thread: Runnable t = () -> { // Check if there is already a notification about external // changes: boolean hasAlready = sidePaneManager.hasComponent(FileUpdatePanel.class); if (hasAlready) { sidePaneManager.hideComponent(FileUpdatePanel.class); sidePaneManager.unregisterComponent(FileUpdatePanel.class); } FileUpdatePanel pan = new FileUpdatePanel(BasePanel.this, sidePaneManager, getBibDatabaseContext().getDatabaseFile().orElse(null), scanner); sidePaneManager.register(pan); sidePaneManager.show(FileUpdatePanel.class); }; if (scanner.changesFound()) { SwingUtilities.invokeLater(t); } else { setUpdatedExternally(false); } } @Override public void fileRemoved() { LOGGER.info("File '" + getBibDatabaseContext().getDatabaseFile().get().getPath() + "' has been deleted."); } /** * Perform necessary cleanup when this BasePanel is closed. */ public void cleanUp() { if (fileMonitorHandle != null) { Globals.getFileUpdateMonitor().removeUpdateListener(fileMonitorHandle); } // Check if there is a FileUpdatePanel for this BasePanel being shown. If so, // remove it: if (sidePaneManager.hasComponent(FileUpdatePanel.class)) { FileUpdatePanel fup = (FileUpdatePanel) sidePaneManager.getComponent(FileUpdatePanel.class); if (fup.getPanel() == this) { sidePaneManager.hideComponent(FileUpdatePanel.class); } } } public void setUpdatedExternally(boolean b) { updatedExternally = b; } /** * Get an array containing the currently selected entries. The array is stable and not changed if the selection * changes * * @return A list containing the selected entries. Is never null. */ public List<BibEntry> getSelectedEntries() { return mainTable.getSelectedEntries(); } public BibDatabaseContext getBibDatabaseContext() { return this.bibDatabaseContext; } public GroupSelector getGroupSelector() { return frame.getGroupSelector(); } public boolean isUpdatedExternally() { return updatedExternally; } public String getFileMonitorHandle() { return fileMonitorHandle; } public void setFileMonitorHandle(String fileMonitorHandle) { this.fileMonitorHandle = fileMonitorHandle; } public SidePaneManager getSidePaneManager() { return sidePaneManager; } public void setNonUndoableChange(boolean nonUndoableChange) { this.nonUndoableChange = nonUndoableChange; } public void setBaseChanged(boolean baseChanged) { this.baseChanged = baseChanged; } public void setSaving(boolean saving) { this.saving = saving; } public boolean isSaving() { return saving; } private BibEntry getShowing() { return showing; } /** * Update the pointer to the currently shown entry in all cases where the user has moved to a new entry, except when * using Back and Forward commands. Also updates history for Back command, and clears history for Forward command. * * @param entry The entry that is now to be shown. */ public void newEntryShowing(BibEntry entry) { // If this call is the result of a Back or Forward operation, we must take // care not to make any history changes, since the necessary changes will // already have been done in the back() or forward() method: if (backOrForwardInProgress) { showing = entry; backOrForwardInProgress = false; setBackAndForwardEnabledState(); return; } nextEntries.clear(); if (!Objects.equals(entry, showing)) { // Add the entry we are leaving to the history: if (showing != null) { previousEntries.add(showing); if (previousEntries.size() > GUIGlobals.MAX_BACK_HISTORY_SIZE) { previousEntries.remove(0); } } showing = entry; setBackAndForwardEnabledState(); } } /** * Go back (if there is any recorded history) and update the histories for the Back and Forward commands. */ private void back() { if (!previousEntries.isEmpty()) { BibEntry toShow = previousEntries.get(previousEntries.size() - 1); previousEntries.remove(previousEntries.size() - 1); // Add the entry we are going back from to the Forward history: if (showing != null) { nextEntries.add(showing); } backOrForwardInProgress = true; // to avoid the history getting updated erroneously highlightEntry(toShow); } } private void forward() { if (!nextEntries.isEmpty()) { BibEntry toShow = nextEntries.get(nextEntries.size() - 1); nextEntries.remove(nextEntries.size() - 1); // Add the entry we are going forward from to the Back history: if (showing != null) { previousEntries.add(showing); } backOrForwardInProgress = true; // to avoid the history getting updated erroneously highlightEntry(toShow); } } public void setBackAndForwardEnabledState() { frame.getBackAction().setEnabled(!previousEntries.isEmpty()); frame.getForwardAction().setEnabled(!nextEntries.isEmpty()); } private String formatOutputMessage(String start, int count) { return String.format("%s %d %s.", start, count, (count > 1 ? Localization.lang("entries") : Localization.lang("entry"))); } private class SaveSelectedAction implements BaseAction { private final SavePreferences.DatabaseSaveType saveType; public SaveSelectedAction(SavePreferences.DatabaseSaveType saveType) { this.saveType = saveType; } @Override public void action() throws SaveException { FileDialog dialog = new FileDialog(frame).withExtension(FileExtensions.BIBTEX_DB); dialog.setDefaultExtension(FileExtensions.BIBTEX_DB); Optional<Path> chosenFile = dialog.saveNewFile(); if (chosenFile.isPresent()) { Path path = chosenFile.get(); saveDatabase(path.toFile(), true, Globals.prefs.getDefaultEncoding(), saveType); frame.getFileHistory().newFile(path.toString()); frame.output(Localization.lang("Saved selected to '%0'.", path.toString())); } } } private static class SearchAndOpenFile { private final BibEntry entry; private final BasePanel basePanel; public SearchAndOpenFile(final BibEntry entry, final BasePanel basePanel) { this.entry = entry; this.basePanel = basePanel; } public Optional<String> searchAndOpen() { if (!Globals.prefs.getBoolean(JabRefPreferences.RUN_AUTOMATIC_FILE_SEARCH)) { return Optional.empty(); } /* The search can lead to an unexpected 100% CPU usage which is perceived as a bug, if the search incidentally starts at a directory with lots of stuff below. It is now disabled by default. */ // see if we can fall back to a filename based on the bibtex key final List<BibEntry> entries = Collections.singletonList(entry); final Set<ExternalFileType> types = ExternalFileTypes.getInstance().getExternalFileTypeSelection(); final List<File> dirs = new ArrayList<>(); final List<String> mdDirs = basePanel.getBibDatabaseContext() .getFileDirectory(Globals.prefs.getFileDirectoryPreferences()); for (final String mdDir : mdDirs) { dirs.add(new File(mdDir)); } final List<String> extensions = new ArrayList<>(); for (final ExternalFileType type : types) { extensions.add(type.getExtension()); } // Run the search operation: Map<BibEntry, List<File>> result; if (Globals.prefs.getBoolean(JabRefPreferences.AUTOLINK_USE_REG_EXP_SEARCH_KEY)) { String regExp = Globals.prefs.get(JabRefPreferences.REG_EXP_SEARCH_EXPRESSION_KEY); result = RegExpFileSearch.findFilesForSet(entries, extensions, dirs, regExp, Globals.prefs.getKeywordDelimiter()); } else { boolean autoLinkExactKeyOnly = Globals.prefs.getBoolean(JabRefPreferences.AUTOLINK_EXACT_KEY_ONLY); result = FileUtil.findAssociatedFiles(entries, extensions, dirs, autoLinkExactKeyOnly); } if (result.containsKey(entry)) { final List<File> res = result.get(entry); if (!res.isEmpty()) { final String filepath = res.get(0).getPath(); final Optional<String> extension = FileUtil.getFileExtension(filepath); if (extension.isPresent()) { Optional<ExternalFileType> type = ExternalFileTypes.getInstance() .getExternalFileTypeByExt(extension.get()); if (type.isPresent()) { try { JabRefDesktop.openExternalFileAnyFormat(basePanel.getBibDatabaseContext(), filepath, type); basePanel.output(Localization.lang("External viewer called") + '.'); return Optional.of(filepath); } catch (IOException ex) { basePanel.output(Localization.lang("Error") + ": " + ex.getMessage()); } } } } } return Optional.empty(); } } /** * Set the preview active state for all BasePanel instances. * * @param enabled */ private void setPreviewActiveBasePanels(boolean enabled) { for (int i = 0; i < frame.getTabbedPane().getTabCount(); i++) { frame.getBasePanelAt(i).setPreviewActive(enabled); } } public CountingUndoManager getUndoManager() { return undoManager; } public MainTable getMainTable() { return mainTable; } public BibDatabaseContext getDatabaseContext() { return bibDatabaseContext; } public SearchQuery getCurrentSearchQuery() { return currentSearchQuery; } public void setCurrentSearchQuery(SearchQuery currentSearchQuery) { this.currentSearchQuery = currentSearchQuery; } public CitationStyleCache getCitationStyleCache() { return citationStyleCache; } public PreviewPanel getPreviewPanel() { if (selectionListener == null) { // only occurs if this is called while instantiating this BasePanel return null; } return selectionListener.getPreview(); } }
/** * @author gurnoor * The Class Table. Contain various information about table, including the Columns that further contains cells */ package nl.esciencecenter.qtm; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import nl.esciencecenter.qtm.solr.tagger.utils.TagResponse; import nl.esciencecenter.qtm.utils.Configs; import nl.esciencecenter.qtm.solr.tagger.recognize.Evaluate; public class Table { private int tab_num; private String xml; private String documentFileName; public String pragmaticClass; public boolean isEmptyOnlyHeaders = true; private boolean isTraitTable = false; private String[] tableHeadersColumns; private Columns[] tableCol; public enum StructureType { LIST, MATRIX, SUBHEADER, MULTI, NULL }; private String sectionOfTable; /** The num_of_rows. */ private int num_of_rows; public int tableInTable; /** The num_of_columns. */ private int num_of_columns; /** The table_title. */ private String table_label; /** The table_caption. */ private String table_caption; /** The table_footer. */ private String table_footer; private boolean hasHeader = true; private boolean hasBody = true; private boolean isNoXMLTable = false; private boolean isRowSpanning = false; private boolean isColSpanning = false; private int structureClass = 0; // 0 - no class,1- simplest, 2 - simple, 3 - // medium, 4 - complex private StructureType tableStructureType; // Constructors /** * Instantiates a new table. * * @param label * the title */ public Table(String label) { table_label = label; hasHeader = true; hasBody = true; isNoXMLTable = false; isRowSpanning = false; isColSpanning = false; } /** * Instantiates a new table. * * @param label * the title * @param Caption * the caption * @param Footer * the footer */ public Table(String label, String Caption, String Footer) { table_label = label; table_caption = Caption; table_footer = Footer; // stat = new TableStats(); } /** * Instantiates a new table. * * @param label * the title * @param Caption * the caption * @param Footer * the footer * @param Columns * the columns * @param Rows * the rows */ public Table(String label, String Caption, String Footer, int Columns, int Rows) { table_label = label; table_caption = Caption; table_footer = Footer; num_of_rows = Rows; num_of_columns = Columns; // stat = new TableStats(); } public boolean isaTraitTable() { String word1 = "QTL"; String word2 = "trait"; // String word3="Quantitavie Trait loci"; if (this.table_caption.toLowerCase().indexOf(word1.toLowerCase()) != -1 || this.table_caption.toLowerCase() .indexOf(word2.toLowerCase()) != -1) return true; if (this.table_footer.toLowerCase().indexOf(word1.toLowerCase()) != -1 || this.table_footer.toLowerCase() .indexOf(word2.toLowerCase()) != -1) return true; Columns tc[] = this.getTableCol(); String word3 = "phenotype"; for (Columns col : tc) { if (col.getColumns_type().indexOf("QTL value") == -1) { if (col.getHeader().toLowerCase() .indexOf(word1.toLowerCase()) != -1 || col.getHeader().toLowerCase() .indexOf(word2.toLowerCase()) != -1 || col.getHeader().toLowerCase() .indexOf(word3.toLowerCase()) != -1) { return true; } } } return false; } // Getters and setters public int getTabnum() { return tab_num; } public void setTableid(int tab_num) { this.tab_num = tab_num; } public String[] getTableHeadersColumns() { return tableHeadersColumns; } public void setTableHeadersColumns(String[] tableHeadersCols) { tableHeadersColumns = tableHeadersCols; } public boolean getisTraitTable() { return isTraitTable; } public void setisTraitTable(boolean isTraitTable) { this.isTraitTable = isTraitTable; } public Columns[] getTableCol() { return tableCol; } public void setTableCol(Columns[] tCol) { tableCol = tCol; } /** * Gets the num_of_rows. * * @return the num_of_rows */ public int getNum_of_rows() { return num_of_rows; } /** * Sets the num_of_rows. * * @param num_of_rows * the new num_of_rows */ public void setNum_of_rows(int num_of_rows) { this.num_of_rows = num_of_rows; } /** * Gets the num_of_columns. * * @return the num_of_columns */ public int getNum_of_columns() { return num_of_columns; } /** * Sets the num_of_columns. * * @param num_of_columns * the new num_of_columns */ public void setNum_of_columns(int num_of_columns) { this.num_of_columns = num_of_columns; } /** * Gets the table_title. * * @return the table_title */ public String getTable_label() { return table_label; } /** * Sets the table_title. * * @param table_title * the new table_title */ public void setTable_label(String table_label) { this.table_label = table_label; } /** * Gets the table_caption. * * @return the table_caption */ public String getTable_caption() { return table_caption; } /** * Sets the table_caption. * * @param table_caption * the new table_caption */ public void setTable_caption(String table_caption) { this.table_caption = table_caption; } /** * Gets the table_footer. * * @return the table_footer */ public String getTable_footer() { return table_footer; } /** * Sets the table_footer. * * @param table_footer * the new table_footer */ public void setTable_footer(String table_footer) { this.table_footer = table_footer; } /** * Gets the table_cells. * * @return the table_cells */ // public C[][] getTable_cells() { // return cells; // public Hc[][] getTable_Headercells() { // return header_cells; // public List<C[]> getTable_cellList() { // return LOC; /** * Sets the table_cells. * * @param cells * the new table_cells */ // public void setTableHeadercells(Hc[][] cells) { // this.header_cells = cells; // public void setTable_cells(C[][] cells) { // this.cells = cells; // public void setTable_cellList(List<C[]> L) { // this.LOC=L; public boolean isHasHeader() { return hasHeader; } public void setHasHeader(boolean hasHeader) { this.hasHeader = hasHeader; } public boolean isHasBody() { return hasBody; } public void setHasBody(boolean hasBody) { this.hasBody = hasBody; } public boolean isNoXMLTable() { return isNoXMLTable; } public void setNoXMLTable(boolean isNoXMLTable) { this.isNoXMLTable = isNoXMLTable; } public boolean isRowSpanning() { return isRowSpanning; } public void setRowSpanning(boolean isRowSpanning) { this.isRowSpanning = isRowSpanning; } public boolean isColSpanning() { return isColSpanning; } public void setColSpanning(boolean isColSpanning) { this.isColSpanning = isColSpanning; } public String getXml() { return xml; } public void setXml(String xml) { this.xml = xml; } public String getDocumentFileName() { return documentFileName; } public void setDocumentFileName(String documentFileName) { this.documentFileName = documentFileName; } public int getStructureClass() { return structureClass; } public void setStructureClass(int sClass) { structureClass = sClass; } /** * @return the tableStructureType */ public StructureType getTableStructureType() { return tableStructureType; } /** * @param tableStructureType * the tableStructureType to set */ public void setTableStructureType(StructureType tStructureType) { tableStructureType = tStructureType; } /** * @return the sectionOfTable */ public String getSectionOfTable() { return sectionOfTable; } /** * @param sectionOfTable * the sectionOfTable to set */ public void setSectionOfTable(String secOfTable) { sectionOfTable = secOfTable; } public void printTable2() throws Exception { StringBuffer sb = new StringBuffer(); for (Columns c : this.getTableCol()) { sb.append( c.getHeader() + "(" + c.getColumns_type() + ")" + "\t\t"); } Main.logger.debug(sb.toString()); int i = 0; while (i < this.num_of_rows) { sb = new StringBuffer(); for (Columns c : this.getTableCol()) { try { sb.append(c.getcelz()[i].getcell_value() + "(" + c.getcelz()[i].getCell_type() + ")" + "\t\t"); } catch (Exception e) { sb.append("Null(Null" + "\t\t"); } } Main.logger.debug(sb.toString()); i++; } } public Table tableClassification() { // C[][] cells=this.getTable_cells(); Columns[] tc = this.getTableCol(); // int rows = cells.length; int cols = this.num_of_columns; HashMap<String, Integer> ColTypes = new HashMap<String, Integer>(); for (int l = 0; l < tc.length; l++) { ColTypes.clear(); ColTypes.put("Partially Numeric", 0); ColTypes.put("Numeric", 0); ColTypes.put("Text", 0); ColTypes.put("Empty", 0); try { for (int k = 0; k < tc[l].getcelz().length; k++) { if (tc[l].getcelz()[k].getCell_type() == "Numeric") { ColTypes.put("Numeric", ColTypes.get("Numeric") + 1); } else if (tc[l].getcelz()[k] .getCell_type() == "Partially Numeric") { ColTypes.put("Partially Numeric", ColTypes.get("Partially Numeric") + 1); } else if (tc[l].getcelz()[k].getCell_type() == "Text") { ColTypes.put("Text", ColTypes.get("Text") + 1); } else if (tc[l].getcelz()[k].getCell_type() == "Empty") { ColTypes.put("Empty", ColTypes.get("Empty") + 1); } } } catch (Exception e) { Main.logger.debug(e); } String word1 = "qtl"; String word2 = "trait"; String word3 = "phenotype"; float totalNumeric = (float) ColTypes.get("Numeric") / (float) (tc[l].getcelz().length - ColTypes.get("Empty")); float totalPartiallyNumeric = (float) ColTypes .get("Partially Numeric") / (float) (tc[l].getcelz().length - ColTypes.get("Empty")); float totalText = (float) ColTypes.get("Text") / (float) (tc[l].getcelz().length - ColTypes.get("Empty")); if (totalNumeric >= 0.60) tc[l].setColumns_type("QTL value"); else tc[l].setColumns_type("QTL property"); int countwords = 0; try { if (tc[l].getColumns_type().equals("QTL property")) { for (int k = 0; k < tc[l].getcelz().length; k++) { if (tc[l].getcelz()[k].getcell_value().toLowerCase() .indexOf(word1) != -1 || tc[l].getcelz()[k].getcell_value() .toLowerCase().indexOf(word2) != -1 || tc[l].getcelz()[k].getcell_value() .toLowerCase().indexOf(word3) != -1) { countwords++; } } if (tc[l].getHeader().toLowerCase().indexOf(word1) != -1 || tc[l].getHeader().toLowerCase().toLowerCase() .indexOf(word2) != -1 || tc[l].getHeader().toLowerCase().toLowerCase() .indexOf(word3) != -1) countwords++; } } catch (Exception e) { Main.logger.warn("Failed to classify column #" + l + " header."); Main.logger.debug(e); } if (countwords > 0) tc[l].setColumns_type("QTL descriptor"); if (tc[l].getColumns_type() == null) { tc[l].setColumns_type("NotIdentified"); } } // filter out 1 QTL descriptor based on annotations int num_QTLdescriptors = 0; List<Integer> QTLdescriptorPosition = new ArrayList<Integer>(); for (int l = 0; l < tc.length; l++) { if (tc[l].getColumns_type().equals("QTL descriptor")) { num_QTLdescriptors++; QTLdescriptorPosition.add(l); } } if (num_QTLdescriptors > 1) { Iterator<Integer> myListIterator = QTLdescriptorPosition.iterator(); int bestmatch = QTLdescriptorPosition.get(0); int numofbestmatchAnnotations = 0; try { while (myListIterator.hasNext()) { int numofannotatedTerms = 0; Integer j = myListIterator.next(); tc[j].setColumns_type("QTL property"); for (int k = 0; k < tc[j].getcelz().length; k++) { TagResponse QTLannotation = Evaluate.processString(tc[j] .getcelz()[k] .getcell_value() .toLowerCase(), Configs.getPropertyQTM("coreTraitDescriptors"), Configs.getPropertyQTM("match"), Configs.getPropertyQTM("type")); if (QTLannotation.getItems().size() != 0) { numofannotatedTerms++; } } if (numofannotatedTerms > numofbestmatchAnnotations) { numofbestmatchAnnotations = numofannotatedTerms; bestmatch = j; } } tc[bestmatch].setColumns_type("QTL descriptor"); } catch (Exception e) { Main.logger.debug(e); } } return this; } }
package ob.geocoding; import java.io.FileInputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.InputStreamReader; public class LocationHelper { public static List<City> cities; public static List<City> getCities() throws IOException { if (cities != null) { return cities; } else { String filePath = "C:\\city.txt"; String line = null; cities = new ArrayList<City>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); while ((line = reader.readLine()) != null) { String[] parts = line.split("\t", 2); if (parts.length >= 2) { City c = new City(Integer.valueOf(parts[0]), parts[1]); cities.add(c); } } reader.close(); return cities; } } public static List<Town> towns; public static List<Town> getTowns() throws IOException{ if (towns !=null) { return towns; }else{ String filePath="C:\\towns.txt"; String line=null; towns=new ArrayList<Town>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); while ((line = reader.readLine()) != null) { String[] parts = line.split("/t", 2); if (parts.length >= 2 ) { Town t = new Town(Integer.valueOf(parts[0]), parts[1]); towns.add(t); } else { System.out.println(line); } } reader.close(); return towns; } } public static List<District> districts; public static List<District> getDistrict() throws IOException{ if (towns !=null) { return districts; }else{ String filePath="C:\\district.txt"; String line=null; towns=new ArrayList<Town>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); while ((line = reader.readLine()) != null) { String[] parts = line.split("/t", 3); if (parts.length >= 2 ) { District d = new District(Integer.valueOf(parts[0]),Integer.valueOf(parts[1]),parts[2]); districts.add(d); } else { System.out.println(line); } } reader.close(); return districts; } } }
package org.monarch.golr; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.inject.Inject; import org.apache.commons.lang3.ClassUtils; import org.monarch.golr.beans.Closure; import org.monarch.golr.beans.GolrCypherQuery; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Result; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; import edu.sdsc.scigraph.frames.CommonProperties; import edu.sdsc.scigraph.internal.CypherUtil; import edu.sdsc.scigraph.internal.TinkerGraphUtil; import edu.sdsc.scigraph.neo4j.Graph; import edu.sdsc.scigraph.neo4j.GraphUtil; public class GolrLoader { private static String EVIDENCE_GRAPH = "evidence_graph"; private static String EVIDENCE_FIELD = "evidence"; private final GraphDatabaseService graphDb; private final ResultSerializerFactory factory; private final EvidenceProcessor processor; private final Graph graph; private final CypherUtil cypherUtil; @Inject GolrLoader(GraphDatabaseService graphDb, Graph graph, CypherUtil cypherUtil, ResultSerializerFactory factory, EvidenceProcessor processor) { this.graphDb = graphDb; this.cypherUtil = cypherUtil; this.graph = graph; this.factory = factory; this.processor = processor; } void process(GolrCypherQuery query, Writer writer) throws IOException { Result result = cypherUtil.execute(query.getQuery()); JsonGenerator generator = new JsonFactory().createGenerator(writer); ResultSerializer serializer = factory.create(generator); generator.writeStartArray(); while (result.hasNext()) { generator.writeStartObject(); Map<String, Object> row = result.next(); com.tinkerpop.blueprints.Graph evidenceGraph = new TinkerGraph(); Set<Long> ignoredNodes = new HashSet<>(); for (Entry<String, Object> entry: row.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (null == value) { continue; } // Add evidence if (value instanceof PropertyContainer) { TinkerGraphUtil.addElement(evidenceGraph, (PropertyContainer) value); } else if (value instanceof Path) { TinkerGraphUtil.addPath(evidenceGraph, (Path) value); } // Add any projections if (query.getProjection().keySet().contains(key)) { String alias = query.getProjection().get(key); if (value instanceof Node) { // Don't include projected nodes in the evidence closure ignoredNodes.add(((Node)value).getId()); } if (query.getCollectedTypes().containsKey(key)) { serializer.serialize(alias, (Node) value, query.getCollectedTypes().get(key)); } else if (value instanceof Relationship) { String objectPropertyIri = GraphUtil.getProperty((Relationship) value, CommonProperties.URI, String.class).get(); Node objectProperty = graphDb.getNodeById(graph.getNode(objectPropertyIri).get()); serializer.serialize(alias, objectProperty); } else { serializer.serialize(alias, value); } } else if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || value instanceof String) { // Serialize primitive types and Strings serializer.serialize(key, value); } } processor.addAssociations(evidenceGraph); serializer.serialize(EVIDENCE_GRAPH, processor.getEvidenceGraph(evidenceGraph)); Closure closure = processor.getEvidenceIds(evidenceGraph, ignoredNodes); serializer.writeArray(EVIDENCE_FIELD + ResultSerializer.ID_SUFFIX, closure.getCuries()); serializer.writeArray(EVIDENCE_FIELD + ResultSerializer.LABEL_SUFFIX, closure.getLabels()); closure = processor.entailEvidence(evidenceGraph, ignoredNodes); serializer.writeArray(EVIDENCE_FIELD + ResultSerializer.ID_CLOSURE_SUFFIX, closure.getCuries()); serializer.writeArray(EVIDENCE_FIELD + ResultSerializer.LABEL_CLOSURE_SUFFIX, closure.getLabels()); generator.writeEndObject(); } generator.writeEndArray(); generator.close(); } }
package org.scijava.util; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Useful methods for working with {@link Class} objects and primitive types. * * @author Curtis Rueden */ public final class ClassUtils { private ClassUtils() { // prevent instantiation of utility class } // -- Class loading, querying and reflection -- /** * Loads the class with the given name, using the current thread's context * class loader, or null if it cannot be loaded. * * @see #loadClass(String, ClassLoader) */ public static Class<?> loadClass(final String className) { return loadClass(className, null); } /** * Loads the class with the given name, using the specified * {@link ClassLoader}, or null if it cannot be loaded. * <p> * This method is capable of parsing several different class name syntaxes. * In particular, array classes (including primitives) represented using * either square brackets or internal Java array name syntax are supported. * Examples: * </p> * <ul> * <li>{@code boolean} is loaded as {@code boolean.class}</li> * <li>{@code Z} is loaded as {@code boolean.class}</li> * <li>{@code double[]} is loaded as {@code double[].class}</li> * <li>{@code string[]} is loaded as {@code java.lang.String.class}</li> * <li>{@code [F} is loaded as {@code float[].class}</li> * </ul> * * @param name The name of the class to load. * @param classLoader The class loader with which to load the class; if null, * the current thread's context class loader will be used. */ public static Class<?> loadClass(final String name, final ClassLoader classLoader) { // handle primitive types if (name.equals("Z") || name.equals("boolean")) return boolean.class; if (name.equals("B") || name.equals("byte")) return byte.class; if (name.equals("C") || name.equals("char")) return char.class; if (name.equals("D") || name.equals("double")) return double.class; if (name.equals("F") || name.equals("float")) return float.class; if (name.equals("I") || name.equals("int")) return int.class; if (name.equals("J") || name.equals("long")) return long.class; if (name.equals("S") || name.equals("short")) return short.class; if (name.equals("V") || name.equals("void")) return void.class; // handle built-in class shortcuts final String className; if (name.equals("string")) className = "java.lang.String"; else className = name; // handle source style arrays (e.g.: "java.lang.String[]") if (name.endsWith("[]")) { final String elementClassName = name.substring(0, name.length() - 2); return getArrayClass(loadClass(elementClassName, classLoader)); } // handle non-primitive internal arrays (e.g.: "[Ljava.lang.String;") if (name.startsWith("[L") && name.endsWith(";")) { final String elementClassName = name.substring(2, name.length() - 1); return getArrayClass(loadClass(elementClassName, classLoader)); } // handle other internal arrays (e.g.: "[I", "[[I", "[[Ljava.lang.String;") if (name.startsWith("[")) { final String elementClassName = name.substring(1); return getArrayClass(loadClass(elementClassName, classLoader)); } // load the class! try { final ClassLoader cl = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader; return cl.loadClass(className); } catch (final ClassNotFoundException e) { return null; } } /** * Gets the array class corresponding to the given element type. * <p> * For example, {@code getArrayClass(double.class)} returns * {@code double[].class}. * </p> */ public static Class<?> getArrayClass(final Class<?> elementClass) { if (elementClass == null) return null; // NB: It appears the reflection API has no built-in way to do this. // So unfortunately, we must allocate a new object and then inspect it. try { return Array.newInstance(elementClass, 0).getClass(); } catch (final IllegalArgumentException exc) { return null; } } /** Checks whether a class with the given name exists. */ public static boolean hasClass(final String className) { return hasClass(className, null); } /** Checks whether a class with the given name exists. */ public static boolean hasClass(final String className, final ClassLoader classLoader) { return loadClass(className, classLoader) != null; } /** * Gets the base location of the given class. * <p> * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "/path/to/my-jar.jar"). * </p> * * @param className The name of the class whose location is desired. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final String className) { return getLocation(className, null); } /** * Gets the base location of the given class. * <p> * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "/path/to/my-jar.jar"). * </p> * * @param className The name of the class whose location is desired. * @param classLoader The class loader to use when loading the class. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final String className, final ClassLoader classLoader) { final Class<?> c = loadClass(className, classLoader); return getLocation(c); } /** * Gets the base location of the given class. * <p> * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "file:/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "file:/path/to/my-jar.jar"). * </p> * * @param c The class whose location is desired. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final Class<?> c) { if (c == null) return null; // could not load the class // try the easy way first try { final URL codeSourceLocation = c.getProtectionDomain().getCodeSource().getLocation(); if (codeSourceLocation != null) return codeSourceLocation; } catch (final SecurityException e) { // NB: Cannot access protection domain. } catch (final NullPointerException e) { // NB: Protection domain or code source is null. } // NB: The easy way failed, so we try the hard way. We ask for the class // itself as a resource, then strip the class's path from the URL string, // leaving the base path. // get the class's raw resource path final URL classResource = c.getResource(c.getSimpleName() + ".class"); if (classResource == null) return null; // cannot find class resource final String url = classResource.toString(); final String suffix = c.getCanonicalName().replace('.', '/') + ".class"; if (!url.endsWith(suffix)) return null; // weird URL // strip the class's path from the URL string final String base = url.substring(0, url.length() - suffix.length()); String path = base; // remove the "jar:" prefix and "!/" suffix, if present if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2); try { return new URL(path); } catch (final MalformedURLException e) { e.printStackTrace(); return null; } } /** * Gets the given class's {@link Method}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getMethods()}, the result will include any non-public * methods, including methods defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated methods. * @param annotationClass The type of annotation for which to scan. * @return A new list containing all methods with the requested annotation. */ public static <A extends Annotation> List<Method> getAnnotatedMethods( final Class<?> c, final Class<A> annotationClass) { final ArrayList<Method> methods = new ArrayList<Method>(); getAnnotatedMethods(c, annotationClass, methods); return methods; } /** * Gets the given class's {@link Method}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getMethods()}, the result will include any non-public * methods, including methods defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated methods. * @param annotationClass The type of annotation for which to scan. * @param methods The list to which matching methods will be added. */ public static <A extends Annotation> void getAnnotatedMethods(final Class<?> c, final Class<A> annotationClass, final List<Method> methods) { // NB: The java.lang.Object class does not have any annotated methods. // And even if it did, it definitely does not have any methods annotated // with SciJava annotations such as org.scijava.event.EventHandler, which // are the main sorts of methods we are interested in. if (c == null || c == Object.class) return; // check supertypes for annotated methods first getAnnotatedMethods(c.getSuperclass(), annotationClass, methods); // NB: In some cases, we may not need to recursively scan interfaces. // In particular, for the @EventHandler annotation, we only care about // concrete methods, not interface method declarations. So we could have // additional method signatures with a boolean toggle indicating whether // to include interfaces in the recursive scan. But initial benchmarks // suggest that the performance difference, even when creating a // full-blown Context with a large classpath, is negligible. for (final Class<?> iface : c.getInterfaces()) { getAnnotatedMethods(iface, annotationClass, methods); } for (final Method m : c.getDeclaredMethods()) { final A ann = m.getAnnotation(annotationClass); if (ann != null) methods.add(m); } } /** * Gets the given class's {@link Field}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getFields()}, the result will include any non-public * fields, including fields defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated fields. * @param annotationClass The type of annotation for which to scan. * @return A new list containing all fields with the requested annotation. */ public static <A extends Annotation> List<Field> getAnnotatedFields( final Class<?> c, final Class<A> annotationClass) { final ArrayList<Field> fields = new ArrayList<Field>(); getAnnotatedFields(c, annotationClass, fields); return fields; } /** * Gets the given class's {@link Field}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getFields()}, the result will include any non-public * fields, including fields defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated fields. * @param annotationClass The type of annotation for which to scan. * @param fields The list to which matching fields will be added. */ public static <A extends Annotation> void getAnnotatedFields( final Class<?> c, final Class<A> annotationClass, final List<Field> fields) { // NB: The java.lang.Object class does not have any annotated fields. // And even if it did, it definitely does not have any fields annotated // with SciJava annotations such as org.scijava.plugin.Parameter, which // are the main sorts of fields we are interested in. if (c == null || c == Object.class) return; // check supertypes for annotated fields first getAnnotatedFields(c.getSuperclass(), annotationClass, fields); for (final Class<?> iface : c.getInterfaces()) { getAnnotatedFields(iface, annotationClass, fields); } for (final Field f : c.getDeclaredFields()) { final A ann = f.getAnnotation(annotationClass); if (ann != null) fields.add(f); } } /** * Gets the specified field of the given class, or null if it does not exist. */ public static Field getField(final String className, final String fieldName) { return getField(loadClass(className), fieldName); } /** * Gets the specified field of the given class, or null if it does not exist. */ public static Field getField(final Class<?> c, final String fieldName) { if (c == null) return null; try { return c.getDeclaredField(fieldName); } catch (final NoSuchFieldException e) { return null; } } /** * Gets the given field's value of the specified object instance, or null if * the value cannot be obtained. */ public static Object getValue(final Field field, final Object instance) { try { field.setAccessible(true); return field.get(instance); } catch (final IllegalAccessException e) { return null; } } // FIXME: Move to ConvertService and deprecate this signature. public static void setValue(final Field field, final Object instance, final Object value) { try { field.setAccessible(true); final Object compatibleValue; if (field.getType().isInstance(value)) { // the given value is compatible with the field compatibleValue = value; } else { // the given value needs to be converted to a compatible type final Type fieldType = GenericUtils.getFieldType(field, instance.getClass()); compatibleValue = ConversionUtils.convert(value, fieldType); } field.set(instance, compatibleValue); } catch (final IllegalAccessException e) { throw new IllegalArgumentException("No access to field: " + field.getName(), e); } } // -- Type querying -- public static boolean isBoolean(final Class<?> type) { return type == boolean.class || Boolean.class.isAssignableFrom(type); } public static boolean isByte(final Class<?> type) { return type == byte.class || Byte.class.isAssignableFrom(type); } public static boolean isCharacter(final Class<?> type) { return type == char.class || Character.class.isAssignableFrom(type); } public static boolean isDouble(final Class<?> type) { return type == double.class || Double.class.isAssignableFrom(type); } public static boolean isFloat(final Class<?> type) { return type == float.class || Float.class.isAssignableFrom(type); } public static boolean isInteger(final Class<?> type) { return type == int.class || Integer.class.isAssignableFrom(type); } public static boolean isLong(final Class<?> type) { return type == long.class || Long.class.isAssignableFrom(type); } public static boolean isShort(final Class<?> type) { return type == short.class || Short.class.isAssignableFrom(type); } public static boolean isNumber(final Class<?> type) { return Number.class.isAssignableFrom(type) || type == byte.class || type == double.class || type == float.class || type == int.class || type == long.class || type == short.class; } public static boolean isText(final Class<?> type) { return String.class.isAssignableFrom(type) || isCharacter(type); } // -- Comparison -- /** * Compares two {@link Class} objects using their fully qualified names. * <p> * Note: this method provides a natural ordering that may be inconsistent with * equals. Specifically, two unequal classes may return 0 when compared in * this fashion if they represent the same class loaded using two different * {@link ClassLoader}s. Hence, if this method is used as a basis for * implementing {@link Comparable#compareTo} or * {@link java.util.Comparator#compare}, that implementation may want to * impose logic beyond that of this method, for breaking ties, if a total * ordering consistent with equals is always required. * </p> * * @see org.scijava.Priority#compare(org.scijava.Prioritized, * org.scijava.Prioritized) */ public static int compare(final Class<?> c1, final Class<?> c2) { if (c1 == c2) return 0; final String name1 = c1 == null ? null : c1.getName(); final String name2 = c2 == null ? null : c2.getName(); return MiscUtils.compare(name1, name2); } // -- Deprecated methods -- /** @deprecated use {@link ConversionUtils#convert(Object, Class)} */ @Deprecated public static <T> T convert(final Object value, final Class<T> type) { return ConversionUtils.convert(value, type); } /** @deprecated use {@link ConversionUtils#canConvert(Class, Class)} */ @Deprecated public static boolean canConvert(final Class<?> c, final Class<?> type) { return ConversionUtils.canConvert(c, type); } /** @deprecated use {@link ConversionUtils#canConvert(Object, Class)} */ @Deprecated public static boolean canConvert(final Object value, final Class<?> type) { return ConversionUtils.canConvert(value, type); } /** @deprecated use {@link ConversionUtils#cast(Object, Class)} */ @Deprecated public static <T> T cast(final Object obj, final Class<T> type) { return ConversionUtils.cast(obj, type); } /** @deprecated use {@link ConversionUtils#canCast(Class, Class)} */ @Deprecated public static boolean canCast(final Class<?> c, final Class<?> type) { return ConversionUtils.canCast(c, type); } /** @deprecated use {@link ConversionUtils#canCast(Object, Class)} */ @Deprecated public static boolean canCast(final Object obj, final Class<?> type) { return ConversionUtils.canCast(obj, type); } /** @deprecated use {@link ConversionUtils#getNonprimitiveType(Class)} */ @Deprecated public static <T> Class<T> getNonprimitiveType(final Class<T> type) { return ConversionUtils.getNonprimitiveType(type); } /** @deprecated use {@link ConversionUtils#getNullValue(Class)} */ @Deprecated public static <T> T getNullValue(final Class<T> type) { return ConversionUtils.getNullValue(type); } /** @deprecated use {@link GenericUtils#getFieldClasses(Field, Class)} */ @Deprecated public static List<Class<?>> getTypes(final Field field, final Class<?> type) { return GenericUtils.getFieldClasses(field, type); } /** @deprecated use {@link GenericUtils#getFieldType(Field, Class)} */ @Deprecated public static Type getGenericType(final Field field, final Class<?> type) { return GenericUtils.getFieldType(field, type); } }
package pointGroups.gui; import java.awt.BorderLayout; import java.awt.Color; import java.util.logging.Logger; import javax.swing.JPanel; import pointGroups.geometry.Fundamental; import pointGroups.gui.event.EventDispatcher; import pointGroups.gui.event.types.ChangeCoordinate3DPointEvent; import pointGroups.gui.event.types.ChangeCoordinate3DPointHandler; import pointGroups.gui.event.types.ChangeCoordinate4DPointEvent; import pointGroups.gui.event.types.ChangeCoordinate4DPointHandler; import pointGroups.gui.event.types.DimensionSwitchEvent; import pointGroups.gui.event.types.DimensionSwitchHandler; import pointGroups.gui.event.types.FundamentalResultEvent; import pointGroups.gui.event.types.FundamentalResultHandler; import pointGroups.gui.event.types.ScaleFundamentalDomainEvent; import pointGroups.gui.event.types.ScaleFundamentalDomainHandler; import pointGroups.gui.event.types.Schlegel3DComputeEvent; import pointGroups.gui.event.types.Schlegel4DComputeEvent; import pointGroups.gui.event.types.Symmetry3DChooseEvent; import pointGroups.gui.event.types.Symmetry3DChooseHandler; import pointGroups.gui.event.types.Symmetry4DChooseEvent; import pointGroups.gui.event.types.Symmetry4DChooseHandler; import pointGroups.util.LoggerFactory; import pointGroups.util.jreality.JRealityUtility; import pointGroups.util.point.PointUtil; import de.jreality.geometry.Primitives; import de.jreality.scene.Appearance; import de.jreality.scene.Geometry; import de.jreality.scene.PointSet; import de.jreality.scene.SceneGraphComponent; import de.jreality.scene.data.Attribute; import de.jreality.scene.data.StorageModel; import de.jreality.shader.DefaultGeometryShader; import de.jreality.shader.DefaultPointShader; import de.jreality.shader.ShaderUtility; import de.jreality.tools.DragEventTool; import de.jreality.tools.PointDragEvent; import de.jreality.tools.PointDragListener; public class PointPicker extends JPanel implements FundamentalResultHandler, DimensionSwitchHandler, ChangeCoordinate3DPointHandler, ChangeCoordinate4DPointHandler, Symmetry3DChooseHandler, Symmetry4DChooseHandler, ScaleFundamentalDomainHandler { private static final long serialVersionUID = -3642299900579728806L; private final boolean responsive; private double scale = 1; private final double SHOWSIZE = 3.0; private double showScale = 1; private Symmetry3DChooseEvent lastSymmetry3DChooseEvent; private Symmetry4DChooseEvent lastSymmetry4DChooseEvent; final protected Logger logger = LoggerFactory.getSingle(PointPicker.class); // Moved Outside of UiViewer to manipulate. public final SceneGraphComponent viewerPointScene = new SceneGraphComponent(); public final SceneGraphComponent viewerFundamentalScene = new SceneGraphComponent(); protected final UiViewer uiViewer = new UiViewer(this) { public final Appearance pointAppearance = new Appearance(); @Override public void onInitialized() { SceneGraphComponent root = getSceneRoot(); viewerPointScene.setGeometry(Primitives.point(new double[] { 0, 0, 0 })); setPointAppearance(pointAppearance); viewerPointScene.setAppearance(pointAppearance); root.addChild(viewerFundamentalScene); root.addChild(viewerPointScene); DragEventTool dragTool = new DragEventTool(); dragTool.addPointDragListener(new PointDragListener() { @Override public void pointDragStart(PointDragEvent e) { logger.finest("drag start of vertex no " + e.getIndex()); } @Override public void pointDragged(PointDragEvent e) { PointSet pointSet = e.getPointSet(); if (pointSet.getNumPoints() == 0) return; double[][] points = new double[pointSet.getNumPoints()][]; pointSet.getVertexAttributes(Attribute.COORDINATES).toDoubleArrayArray( points); double[] startPoint = points[0]; double[] dragPoint = e.getPosition(); double[] fundamentalPoint = viewerPointToFundamentalPoint(dragPoint); if (!fundamental.inFundamental(fundamentalPoint)) { dragPoint = startPoint; return; } points[e.getIndex()] = dragPoint; pointSet.setVertexAttributes(Attribute.COORDINATES, StorageModel.DOUBLE_ARRAY.array(3).createReadOnly(points)); // TODO: // because the point scene has only one vertex, pointSet should only // contain one point; and therefore only the statements below should // be sufficient for point picking. if (responsive) selectPoint(dragPoint); } @Override public void pointDragEnd(PointDragEvent e) { logger.finest("drag end of vertex no " + e.getIndex()); if (!responsive) selectPoint(e.getPosition()); } }); viewerPointScene.addTool(dragTool); } private void setPointAppearance(Appearance ap) { // make points a little bigger, than the default. DefaultGeometryShader dgs; DefaultPointShader dpts; dgs = ShaderUtility.createDefaultGeometryShader(ap, true); dgs.setShowPoints(true); dpts = (DefaultPointShader) dgs.createPointShader("default"); dpts.setDiffuseColor(Color.MAGENTA); dpts.setSpheresDraw(true); dpts.setPointSize(0.1); dpts.setPointRadius(0.1); } }; public void setPoint(double[] coords) { logger.fine("Set Fundamental Pick Point to: " + PointUtil.showPoint(coords)); if (dim == 2) { this.viewerPointScene.setGeometry(Primitives.point(new double[] { coords[0], coords[1], 0.0 })); return; } this.viewerPointScene.setGeometry(Primitives.point(coords)); } // The current Fundamental Domain protected Fundamental fundamental; protected boolean isSet; protected EventDispatcher dispatcher; protected int dim; /** * Creates the Point Picker, to choose a point graphically. * * @param responsive - true => ChangeCoordinateEvent on Drag, False => Change * Coordinate Event on Release */ public PointPicker(boolean responsive) { super(); setLayout(new BorderLayout()); this.isSet = false; this.dim = 2; this.dispatcher = EventDispatcher.get(); this.responsive = responsive; // Register PointPicker on Events this.dispatcher.addHandler(FundamentalResultEvent.TYPE, this); this.dispatcher.addHandler(DimensionSwitchEvent.TYPE, this); this.dispatcher.addHandler(ChangeCoordinate3DPointEvent.TYPE, this); this.dispatcher.addHandler(ChangeCoordinate4DPointEvent.TYPE, this); this.dispatcher.addHandler(Symmetry4DChooseEvent.TYPE, this); this.dispatcher.addHandler(Symmetry3DChooseEvent.TYPE, this); this.dispatcher.addHandler(ScaleFundamentalDomainEvent.TYPE, this); } public void dispose() { uiViewer.dispose(); } @Override public void onFundamentalResultEvent(FundamentalResultEvent event) { this.isSet = true; this.fundamental = event.getResult(); // Maybe check for dimension this.showFundamental(); } // Maybe i need this. @Override public void onDimensionSwitchEvent(DimensionSwitchEvent event) { uiViewer.setDimensionMode(uiViewer.uiState.isPointPicker3DMode()); if (event.switchedTo3D()) { logger.fine("Point Picker switched to 2D Mode."); this.dim = 2; } else if (event.switchedTo4D()) { logger.fine("Point Picker switched to 3D Mode."); this.dim = 3; } else { this.dim = 0; this.isSet = false; } } protected double[] viewerPointToFundamentalPoint(double[] viewerPoint) { double[] fundamentalPoint = new double[this.dim]; for (int i = 0; i < this.dim; i++) { fundamentalPoint[i] = viewerPoint[i]; } if (fundamental.isKnown()) { fundamentalPoint = PointUtil.div(showScale, fundamentalPoint); } return fundamentalPoint; } // Method to fire coordinate Changed Event, should be executed by click inside // the fundamental domain. protected void selectPoint(double[] point) { if (!isSet || (this.dim != 2 && this.dim != 3)) { logger.info("Point was picked with no useable Fundamental Region."); return; } logger.info("Selected Point (" + point[0] + "," + point[1] + (this.dim == 3 ? "," + point[2] : "") + ")"); if (!isSet) return; // Maybe the view is translated or smt // point = Rotate * point - translation // Recalculate to Unitsphere on dim+1 dimensions // Only take the first dim components double[] selComp = viewerPointToFundamentalPoint(point); double[] resP = this.fundamental.revertPoint(selComp); logger.fine("Point Picker calculated Point (" + resP[0] + "," + resP[1] + "," + resP[2] + (this.dim == 3 ? "," + resP[3] : "") + ")"); resP = PointUtil.mult(this.scale, resP); logger.fine("Scale: " + this.scale + ", point : " + PointUtil.showPoint(resP)); // Fire Event, that the coordinate changed if (dim == 2) { this.dispatcher.fireEvent(new ChangeCoordinate3DPointEvent( JRealityUtility.asPoint3D(resP), this)); // if (responsive) this.dispatcher.fireEvent(new Schlegel3DComputeEvent( lastSymmetry3DChooseEvent, JRealityUtility.asPoint3D(resP))); } else if (dim == 3) { this.dispatcher.fireEvent(new ChangeCoordinate4DPointEvent( JRealityUtility.asPoint4D(resP), this)); // if (responsive) this.dispatcher.fireEvent(new Schlegel4DComputeEvent( lastSymmetry4DChooseEvent, JRealityUtility.asPoint4D(resP))); } } protected void showFundamental() { logger.info("Showing new Fundamental Domain."); Geometry g; // Calculate the new fundamental if (this.fundamental.isKnown()) { double[][] points = this.fundamental.getVertices(); double dia = PointUtil.diameter(points); showScale = SHOWSIZE / dia; int[][] edges = JRealityUtility.convertEdges(this.fundamental.getEdges()); int[][] faces = null; for (int i = 0; i < points.length; i++) { points[i] = PointUtil.mult(showScale, points[i]); } g = JRealityUtility.generateGraph(points, edges, faces); } else { if (this.dim == 2) g = JRealityUtility.circle(0, 0, 1); else g = Primitives.sphere(20); } // Reset tools (3D rotation, 2D no Rotation) logger.fine("A new Fundamental Region is shown."); viewerFundamentalScene.setGeometry(g); setPoint(new double[] { 0.0, 0.0, 0.0 }); } @Override public void onChangeCoordinate4DPointEvent(ChangeCoordinate4DPointEvent event) { // Calculate if the point is in the Fundamental Domain and // show it, if possible // For start test just show the point // uiViewer.setGeometry(Primitives.point(new double[] { 0.5, 0.5 })); return; } @Override public void onChangeCoordinate3DPointEvent(ChangeCoordinate3DPointEvent event) { // Calculate if the point is in the Fundamental Domain and // show it, if possible // For start test just show the point // uiViewer.setGeometry(Primitives.point(new double[] { 0.5, 0.5 })); return; } @Override public void onSymmetry4DChooseEvent(Symmetry4DChooseEvent event) { this.lastSymmetry4DChooseEvent = event; this.dim = 3; } @Override public void onSymmetry3DChooseEvent(Symmetry3DChooseEvent event) { this.lastSymmetry3DChooseEvent = event; this.dim = 2; } @Override public void onScaleFundamentalDomainEvent(ScaleFundamentalDomainEvent event) { this.scale = 1.0 * event.getScale(); } }
package starpunk.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import starpunk.StarPunkGame; public abstract class BaseScreen implements Screen { private final StarPunkGame _game; protected BaseScreen( final StarPunkGame game ) { _game = game; } protected final StarPunkGame getGame() { return _game; } public abstract void update( float delta ); public abstract void draw( float delta ); @Override public void render( final float delta ) { update( delta ); draw( delta ); } @Override public void resize( final int width, final int height ) { log( "Resizing screen to: " + width + " x " + height ); } @Override public void show() { log( "Showing screen" ); } @Override public void hide() { log( "Hiding screen" ); } @Override public void pause() { log( "Pausing screen" ); } @Override public void resume() { log( "Resuming screen" ); } @Override public void dispose() { log( "Disposing screen" ); } private void log( final String message ) { Gdx.app.log( getClass().getSimpleName(), message ); } }
package uk.co.omegaprime.mdbi; import javax.annotation.Nonnull; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** Useful methods for constructing instances of the {@link Read} interface. */ public class Reads { public static final Read<Boolean> PRIM_BOOLEAN = new AbstractUnaryRead<Boolean>(boolean.class) { @Override public Boolean get(ResultSet rs, int ix) throws SQLException { boolean result = rs.getBoolean(ix); if (rs.wasNull()) throw new NullPointerException("Found null in result"); return result; } }; public static final Read<Boolean> BOOLEAN = new AbstractUnaryRead<Boolean>(Boolean.class) { @Override public Boolean get(ResultSet rs, int ix) throws SQLException { boolean result = rs.getBoolean(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<Byte> PRIM_BYTE = new AbstractUnaryRead<Byte>(byte.class) { @Override protected Byte get(ResultSet rs, int ix) throws SQLException { byte result = rs.getByte(ix); if (rs.wasNull()) throw new NullPointerException("Found null in result"); return result; } }; public static final Read<Byte> BYTE = new AbstractUnaryRead<Byte>(Byte.class) { @Override public Byte get(ResultSet rs, int ix) throws SQLException { byte result = rs.getByte(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<Character> PRIM_CHAR = new AbstractUnaryRead<Character>(char.class) { @Override protected Character get(ResultSet rs, int ix) throws SQLException { String result = rs.getString(ix); if (rs.wasNull()) throw new NullPointerException("Found null in result"); if (result.length() != 1) throw new IllegalArgumentException("Found string " + result + " but was expecting single char"); return result.charAt(0); } }; public static final Read<Character> CHARACTER = new AbstractUnaryRead<Character>(Character.class) { @Override public Character get(ResultSet rs, int ix) throws SQLException { String result = rs.getString(ix); if (rs.wasNull()) return null; if (result.length() != 1) throw new IllegalArgumentException("Found string " + result + " but was expecting single char"); return result.charAt(0); } }; public static final Read<Short> PRIM_SHORT = new AbstractUnaryRead<Short>(short.class) { @Override protected Short get(ResultSet rs, int ix) throws SQLException { short result = rs.getShort(ix); if (rs.wasNull()) throw new NullPointerException("Found null in result"); return result; } }; public static final Read<Short> SHORT = new AbstractUnaryRead<Short>(Short.class) { @Override public Short get(ResultSet rs, int ix) throws SQLException { short result = rs.getShort(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<Integer> PRIM_INT = new AbstractUnaryRead<Integer>(int.class) { @Override public Integer get(ResultSet rs, int ix) throws SQLException { final int result = rs.getInt(ix); if (rs.wasNull()) throw new NullPointerException("Found null in result"); return result; } }; public static final Read<Integer> INTEGER = new AbstractUnaryRead<Integer>(Integer.class) { @Override public Integer get(ResultSet rs, int ix) throws SQLException { final int result = rs.getInt(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<Long> PRIM_LONG = new AbstractUnaryRead<Long>(long.class) { @Override protected Long get(ResultSet rs, int ix) throws SQLException { long result = rs.getLong(ix); if (rs.wasNull()) throw new NullPointerException("Found null in result"); return result; } }; public static final Read<Long> LONG = new AbstractUnaryRead<Long>(Long.class) { @Override public Long get(ResultSet rs, int ix) throws SQLException { long result = rs.getLong(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<Float> PRIM_FLOAT = new AbstractUnaryRead<Float>(float.class) { @Override public Float get(ResultSet rs, int ix) throws SQLException { final float result = rs.getFloat(ix); if (rs.wasNull()) return Float.NaN; return result; } }; public static final Read<Float> FLOAT = new AbstractUnaryRead<Float>(Float.class) { @Override public Float get(ResultSet rs, int ix) throws SQLException { final float result = rs.getFloat(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<Double> PRIM_DOUBLE = new AbstractUnaryRead<Double>(double.class) { @Override public Double get(ResultSet rs, int ix) throws SQLException { final double result = rs.getDouble(ix); if (rs.wasNull()) return Double.NaN; return result; } }; public static final Read<Double> DOUBLE = new AbstractUnaryRead<Double>(Double.class) { @Override public Double get(ResultSet rs, int ix) throws SQLException { final double result = rs.getDouble(ix); if (rs.wasNull()) return null; return result; } }; public static final Read<String> STRING = new AbstractUnaryRead<String>(String.class) { @Override public String get(ResultSet rs, int ix) throws SQLException { return rs.getString(ix); } }; public static final Read<LocalDate> LOCAL_DATE = new AbstractUnaryRead<LocalDate>(LocalDate.class) { @Override public LocalDate get(ResultSet rs, int ix) throws SQLException { final Timestamp ts = rs.getTimestamp(ix, Time.UTC_CALENDAR.get()); return ts == null ? null : Instant.ofEpochMilli(ts.getTime()).atZone(Time.UTC_ZONE_ID).toLocalDate(); } }; public static final Read<LocalTime> LOCAL_TIME = new AbstractUnaryRead<LocalTime>(LocalTime.class) { @Override public LocalTime get(ResultSet rs, int ix) throws SQLException { final Timestamp ts = rs.getTimestamp(ix, Time.UTC_CALENDAR.get()); return ts == null ? null : Instant.ofEpochMilli(ts.getTime()).atZone(Time.UTC_ZONE_ID).toLocalTime(); } }; public static final Read<LocalDateTime> LOCAL_DATE_TIME = new AbstractUnaryRead<LocalDateTime>(LocalDateTime.class) { @Override public LocalDateTime get(ResultSet rs, int ix) throws SQLException { final Timestamp ts = rs.getTimestamp(ix, Time.UTC_CALENDAR.get()); return ts == null ? null : Instant.ofEpochMilli(ts.getTime()).atZone(Time.UTC_ZONE_ID).toLocalDateTime(); } }; public static final Read<byte[]> BYTE_ARRAY = new AbstractUnaryRead<byte[]>(byte[].class) { @Override protected byte[] get(ResultSet rs, int ix) throws SQLException { return rs.getBytes(ix); } }; /** A {@code Read} instance that simply defers to the {@link Context} to decide how to construct an instance of the given class. */ public static <T> Read<T> useContext(Class<T> klass) { return new ContextRead<>(klass); } /** Constructs a type that has only one public constructor. Constructor arguments are recursively constructed using the {@link Context}. */ public static <T> Read<T> tuple(Class<T> klass) { return new TupleRead<T>(klass); } /** Constructs a type that has only one public constructor. Constructor arguments are constructed using the context-default {@code Read} instance for the supplied classes. */ public static <T> Read<T> tupleWithFieldClasses(Class<T> klass, Collection<Class<?>> klasses) { return tuple(klass, klasses.stream().map(argklass -> new ContextRead<>(argklass)).collect(Collectors.toList())); } /** Constructs a type that has only one public constructor. Constructor arguments are constructed using the supplied {@code Read} instances. */ public static <T> Read<T> tuple(Class<T> klass, Collection<Read<?>> reads) { return new TupleRead<T>(klass, reads); } /** Mapping treating {@code Read} as a functor. */ public static <T, U> Read<U> map(Class<U> klass, Class<T> readKlass, Function<T, U> f) { return map(klass, new ContextRead<>(readKlass), f); } /** Mapping treating {@code Read} as a functor. */ public static <T, U> Read<U> map(Class<U> klass, Read<T> read, Function<T, U> f) { return new Read<U>() { @Override public Class<U> getElementClass() { return klass; } @Override public BoundRead<? extends U> bind(Context ctxt) { final BoundRead<? extends T> boundRead = read.bind(ctxt); return (rs, ix) -> f.apply(boundRead.get(rs, ix)); } }; } private Reads() {} static class Map implements Read.Context { private final HashMap<Class<?>, Read<?>> map = new HashMap<>(); public Map() {} public Map(Map that) { map.putAll(that.map); } public <T> void put(Class<? super T> klass, Read<T> write) { map.put(klass, write); } @SuppressWarnings("unchecked") public <T> Read<? extends T> get(Class<T> klass) { final Read<? extends T> result = (Read<? extends T>) map.get(klass); if (result == null) { throw new IllegalArgumentException("Don't know how to transfer " + klass + " objects from JDBC"); } else { return result; } } } private abstract static class AbstractUnaryRead<T> implements Read<T> { private final Class<T> klass; public AbstractUnaryRead(Class<T> klass) { this.klass = klass; } @Override public Class<T> getElementClass() { return klass; } @Override public BoundRead<T> bind(Context ctxt) { return new BoundRead<T>() { @Override public T get(@Nonnull ResultSet rs, @Nonnull IndexRef ix) throws SQLException { return AbstractUnaryRead.this.get(rs, ix.take()); } }; } protected abstract T get(ResultSet rs, int ix) throws SQLException; } /** * Constructs a bean using reflection. * <p> * The named bean properties are extracted from the SQL result in the order given. The value of the bean * property is constructed using the default {@code Read} associated for that type in the {@link Context}. */ public static <T> Read<T> bean(Class<T> klass, String... fields) { return new BeanRead<>(klass, fields); } /** As {@link #bean(Class, String...)}, but allows you to explicitly specify the types of the fields. */ public static <T> Read<T> beanWithFieldClasses(Class<T> klass, Collection<String> fields, Collection<Class<?>> klasses) { return new BeanRead<>(klass, fields, klasses.stream().map(argklass -> new ContextRead<>(argklass)).collect(Collectors.toList())); } /** As {@link #bean(Class, String...)}, but allows you to customize how the property values are constructed. */ public static <T> Read<T> bean(Class<T> klass, Collection<String> fields, Collection<Read<?>> reads) { return new BeanRead<>(klass, fields, reads); } /** Reads the given classes one after another, aggregating the results from the row into a {@code List} */ public static <T> Read<List<T>> listWithClasses(Collection<Class<? extends T>> klasses) { return list(klasses.stream().map(klass -> new ContextRead<>(klass)).collect(Collectors.toList())); } /** Reads the given elements one after another, aggregating the results from the row into a {@code List} */ public static <T> Read<List<T>> list(Collection<Read<? extends T>> reads) { return new Read<List<T>>() { @SuppressWarnings("unchecked") @Override public Class<List<T>> getElementClass() { return (Class<List<T>>)(Class)List.class; } @Override public BoundRead<? extends List<T>> bind(Context ctxt) { final List<BoundRead<? extends T>> bounds = reads.stream().map(read -> read.bind(ctxt)).collect(Collectors.toList()); return (rs, ix) -> { final List<T> result = new ArrayList<>(); for (BoundRead<? extends T> bound : bounds) { result.add(bound.get(rs, ix)); } return result; }; } }; } /** As {@link #labelledMap(Collection)}, but using the {@code Read} instance associated with the class in the {@link Context}. */ public static <T> Read<java.util.Map<String, T>> labelledMapWithClasses(Collection<Class<? extends T>> klasses) { return labelledMap(klasses.stream().map(klass -> new ContextRead<>(klass)).collect(Collectors.toList())); } public static <T> Read<java.util.Map<String, T>> labelledMap(Collection<Read<? extends T>> reads) { return new Read<java.util.Map<String, T>>() { @SuppressWarnings("unchecked") @Override public Class<java.util.Map<String, T>> getElementClass() { return (Class<java.util.Map<String, T>>)(Class)java.util.Map.class; } @Override public BoundRead<? extends java.util.Map<String, T>> bind(Context ctxt) { final List<BoundRead<? extends T>> bounds = reads.stream().map(read -> read.bind(ctxt)).collect(Collectors.toList()); return (rs, ix) -> { final java.util.Map<String, T> result = new LinkedHashMap<>(); for (BoundRead<? extends T> bound : bounds) { // TODO: refactor so that we can do this lookup only once per query.. final String columnName = rs.getMetaData().getColumnName(ix.peek()); if (result.containsKey(columnName)) { throw new IllegalArgumentException("Column " + columnName + " occurs twice in the result"); } result.put(columnName, bound.get(rs, ix)); } return result; }; } }; } }
package utils; import function.external.flanking.FlankingCommand; import function.genotype.base.GenotypeLevelFilterCommand; import global.Data; import function.genotype.base.SampleManager; import function.variant.base.VariantLevelFilterCommand; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Vector; /** * * @author nick */ public class ThirdPartyToolManager { private static final String R_SCRIPT_SYSTEM_PATH = "/nfs/goldstein/software/R-3.2.5/bin/Rscript"; private static final String COLLAPSED_REGRESSION_R = "/nfs/goldstein/software/atav_home/lib/collapsed_regression_2.0.R"; private static final String PVALS_QQPLOT_R = "/nfs/goldstein/software/atav_home/lib/pvals_qqplot.R"; private static final String QQPLOT_FOR_COLLAPSING_R = "/nfs/goldstein/software/atav_home/lib/qqplot_for_collapsing.R"; private static final String PERL_SYSTEM_PATH = "perl"; private static final String FLANKING_SEQ_PERL = "/nfs/goldstein/software/atav_home/lib/flanking_seq.pl"; private static final String TRIO_DENOVO_TIER = "/nfs/goldstein/software/atav_home/lib/r0.4_trio_denovo_tier.R"; private static final String TRIO_COMP_HET_TIER = "/nfs/goldstein/software/atav_home/lib/r0.4_trio_comp_het_tier.R"; private static final String NON_TRIO_TIER = "/nfs/goldstein/software/atav_home/lib/non_trio_tier.R"; public static int systemCall(String[] cmd) { LogManager.writeAndPrintNoNewLine("System call start"); int exitValue = Data.NA; try { Process myProc; if (cmd.length > 1) { LogManager.writeAndPrintNoNewLine(cmd[2]); myProc = Runtime.getRuntime().exec(cmd); } else { LogManager.writeAndPrintNoNewLine(cmd[0]); myProc = Runtime.getRuntime().exec(cmd[0]); } InputStream is = myProc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; Vector<String> result = new Vector<>(); while ((line = br.readLine()) != null) { result.add(line); } exitValue = myProc.waitFor(); } catch (Exception e) { ErrorManager.send(e); } if (exitValue != 0) { LogManager.writeAndPrint("System call failed."); } else { LogManager.writeAndPrint("System call complete."); } return exitValue; } public static void callCollapsedRegression(String outputFile, String geneSampleMatrixFilePath, String method) { String cmd = R_SCRIPT_SYSTEM_PATH + " " + COLLAPSED_REGRESSION_R + " " + "--samples " + SampleManager.getTempCovarPath() + " " + "--clps " + geneSampleMatrixFilePath + " " + "--out " + outputFile + " " + "--method " + method + " " + "--transpose " + "--log " + CommonCommand.outputPath + "regress.log"; int exitValue = systemCall(new String[]{cmd}); if (exitValue != 0) { LogManager.writeAndPrint("\nwarning: the application failed to run Collapsed " + "Regression script (" + method + "). \n"); deleteFile(outputFile); } } public static void callFlankingSeq(String baseFlankingSeqFilePath) { String cmd = PERL_SYSTEM_PATH + " " + FLANKING_SEQ_PERL + " --variant " + VariantLevelFilterCommand.includeVariantId + " --width " + FlankingCommand.width + " --out " + baseFlankingSeqFilePath; int exitValue = systemCall(new String[]{cmd}); if (exitValue != 0) { LogManager.writeAndPrint("\nwarning: the application failed to run flanking " + "sequence script. \n"); deleteFile(baseFlankingSeqFilePath); } } public static void callPvalueQQPlot(String pvalueFile, int col, String outputPath) { String cmd = R_SCRIPT_SYSTEM_PATH + " " + PVALS_QQPLOT_R + " " + pvalueFile + " " + col + " " + outputPath; int exitValue = systemCall(new String[]{cmd}); if (exitValue != 0) { deleteFile(outputPath); } } public static void generatePvaluesQQPlot(String title, String pvalueName, String pvalueFile, String outputPath) { String[] temp = title.split(","); int col = 0; for (String str : temp) { col++; if (str.trim().equalsIgnoreCase(pvalueName)) { break; } } callPvalueQQPlot(pvalueFile, col, outputPath); } public static void generateQQPlot4CollapsingFetP(String matrixFilePath, String outputPath) { String cmd = R_SCRIPT_SYSTEM_PATH + " " + QQPLOT_FOR_COLLAPSING_R + " " + GenotypeLevelFilterCommand.sampleFile + " " + matrixFilePath + " " + "1000 " // permutation + outputPath; // output path int exitValue = systemCall(new String[]{cmd}); if (exitValue != 0) { deleteFile(outputPath); } } private static void deleteFile(String filePath) { File f = new File(filePath); f.deleteOnExit(); } public static void gzipFile(String path) { String cmd = "gzip -9 " + path; systemCall(new String[]{cmd}); } public static void runTrioDenovoTier(String denovoFilePath) { String cmd = R_SCRIPT_SYSTEM_PATH + " " + TRIO_DENOVO_TIER + " " + denovoFilePath; systemCall(new String[]{cmd}); } public static void runTrioCompHetTier(String compHetFilePath) { String cmd = R_SCRIPT_SYSTEM_PATH + " " + TRIO_COMP_HET_TIER + " " + compHetFilePath; systemCall(new String[]{cmd}); } public static void runNonTrioTier(String variantFilePath) { String cmd = R_SCRIPT_SYSTEM_PATH + " " + NON_TRIO_TIER + " " + variantFilePath; systemCall(new String[]{cmd}); } }
package yokohama.unit.ast; import java.util.List; import lombok.EqualsAndHashCode; import lombok.Value; import yokohama.unit.position.Span; import yokohama.unit.util.Lists; @Value @EqualsAndHashCode(exclude={"span"}) public class CodeBlock implements Definition { Heading heading; String lang; List<String> lines; Span span; public String getCode( String lineSeparator, boolean appendLineSeparatorAtTheEnd) { StringBuilder sb = new StringBuilder(); Lists.mapInitAndLast(lines, line -> { sb.append(line); sb.append(lineSeparator); return null; }, line -> { sb.append(line); if (appendLineSeparatorAtTheEnd) { sb.append(lineSeparator); } return null; }); return sb.toString(); } @Override public <T> T accept(DefinitionVisitor<T> visitor) { return visitor.visitCodeBlock(this); } }
package mondrian.olap.fun; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Collection; import java.util.HashSet; import mondrian.olap.FunTable; import mondrian.olap.Syntax; import mondrian.olap.Util; import mondrian.olap.type.Type; import mondrian.resource.MondrianResource; import mondrian.spi.UserDefinedFunction; import org.apache.log4j.Logger; /** * Global function table contains builtin functions and global user-defined functions. * * @author Gang Chen * @version $Id$ */ public class GlobalFunTable extends FunTableImpl { private static Logger logger = Logger.getLogger(GlobalFunTable.class); private static GlobalFunTable instance = new GlobalFunTable(); public static GlobalFunTable instance() { return instance; } private GlobalFunTable() { super(); init(); } protected void defineFunctions() { final FunTable builtinFunTable = BuiltinFunTable.instance(); final List reservedWords = builtinFunTable.getReservedWords(); for (int i = 0; i < reservedWords.size(); i++) { String reservedWord = (String) reservedWords.get(i); defineReserved(reservedWord); } final List resolvers = builtinFunTable.getResolvers(); for (int i = 0; i < resolvers.size(); i++) { Resolver resolver = (Resolver) resolvers.get(i); define(resolver); } for (Iterator it = lookupUdfImplClasses().iterator(); it.hasNext(); ) { String className = (String)it.next(); defineUdf(className); } } private Collection lookupUdfImplClasses() { ClassLoader cl = this.getClass().getClassLoader(); List serviceUrls = new ArrayList(); try { Enumeration serviceEnum = cl.getResources("META-INF/services/mondrian.spi.UserDefinedFunction"); for (; serviceEnum.hasMoreElements();) { serviceUrls.add(serviceEnum.nextElement()); } } catch (IOException e) { logger.warn("Error while finding service files for user-defined functions", e); } Set classNames = new HashSet(); for (Iterator it = serviceUrls.iterator(); it.hasNext();) { URL url = (URL) it.next(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { if (line.charAt(0) == '#') continue; int comment = line.indexOf(' if (comment != -1) { line = line.substring(0, comment).trim(); } classNames.add(line); } } } catch (IOException e) { logger.warn("Error when loading service file '" + url + "'", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } return classNames; } /** * Defines a user-defined function in this table. * * <p>If the function is not valid, throws an error. * * @param className Name of the class which implements the function. * The class must implement {@link mondrian.spi.UserDefinedFunction} * (otherwise it is a user-error). */ private void defineUdf(String className) { // Load class. final Class udfClass; try { udfClass = Class.forName(className); } catch (ClassNotFoundException e) { throw MondrianResource.instance().UdfClassNotFound.ex("",className); } // Instantiate class with default constructor. final UserDefinedFunction udf; try { udf = (UserDefinedFunction) udfClass.newInstance(); } catch (InstantiationException e) { throw MondrianResource.instance().UdfClassWrongIface.ex("", className, UserDefinedFunction.class.getName()); } catch (IllegalAccessException e) { throw MondrianResource.instance().UdfClassWrongIface.ex("", className, UserDefinedFunction.class.getName()); } catch (ClassCastException e) { throw MondrianResource.instance().UdfClassWrongIface.ex("", className, UserDefinedFunction.class.getName()); } // Validate function. validateFunction(udf); // Define function. define(new UdfResolver(udf)); } /** * Throws an error if a user-defined function does not adhere to the * API. */ private void validateFunction(final UserDefinedFunction udf) { // Check that the name is not null or empty. final String udfName = udf.getName(); if (udfName == null || udfName.equals("")) { throw Util.newInternal("User-defined function defined by class '" + udf.getClass() + "' has empty name"); } // It's OK for the description to be null. //final String description = udf.getDescription(); final Type[] parameterTypes = udf.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Type parameterType = parameterTypes[i]; if (parameterType == null) { throw Util.newInternal("Invalid user-defined function '" + udfName + "': parameter type " is null"); } } // It's OK for the reserved words to be null or empty. //final String[] reservedWords = udf.getReservedWords(); // Test that the function returns a sensible type when given the FORMAL // types. It may still fail when we give it the ACTUAL types, but it's // impossible to check that now. final Type returnType = udf.getReturnType(parameterTypes); if (returnType == null) { throw Util.newInternal("Invalid user-defined function '" + udfName + "': return type is null"); } final Syntax syntax = udf.getSyntax(); if (syntax == null) { throw Util.newInternal("Invalid user-defined function '" + udfName + "': syntax is null"); } } } // End GlobalFunTable.java
package com.rnfs; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import android.os.StatFs; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.util.Base64; import android.util.SparseArray; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.net.URL; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RNFSManager extends ReactContextBaseJavaModule { private static final String RNFSDocumentDirectoryPath = "RNFSDocumentDirectoryPath"; private static final String RNFSExternalDirectoryPath = "RNFSExternalDirectoryPath"; private static final String RNFSExternalStorageDirectoryPath = "RNFSExternalStorageDirectoryPath"; private static final String RNFSPicturesDirectoryPath = "RNFSPicturesDirectoryPath"; private static final String RNFSTemporaryDirectoryPath = "RNFSTemporaryDirectoryPath"; private static final String RNFSCachesDirectoryPath = "RNFSCachesDirectoryPath"; private static final String RNFSExternalCachesDirectoryPath = "RNFSExternalCachesDirectoryPath"; private static final String RNFSDocumentDirectory = "RNFSDocumentDirectory"; private static final String RNFSFileTypeRegular = "RNFSFileTypeRegular"; private static final String RNFSFileTypeDirectory = "RNFSFileTypeDirectory"; private SparseArray<Downloader> downloaders = new SparseArray<Downloader>(); private SparseArray<Uploader> uploaders = new SparseArray<Uploader>(); private ReactApplicationContext reactContext; public RNFSManager(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNFSManager"; } private Uri getFileUri(String filepath) throws IORejectionException { Uri uri = Uri.parse(filepath); if (uri.getScheme() == null) { // No prefix, assuming that provided path is absolute path to file File file = new File(filepath); if (file.isDirectory()) { throw new IORejectionException("EISDIR", "EISDIR: illegal operation on a directory, read '" + filepath + "'"); } uri = Uri.parse("file://" + filepath); } return uri; } private String getOriginalFilepath(String filepath) throws IORejectionException { Uri uri = getFileUri(filepath); String originalFilepath = filepath; if (uri.getScheme().equals("content")) { try { Cursor cursor = reactContext.getContentResolver().query(uri, null, null, null, null); if (cursor.moveToFirst()) { originalFilepath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } } catch (IllegalArgumentException ignored) { } } return originalFilepath; } private InputStream getInputStream(String filepath) throws IORejectionException { Uri uri = getFileUri(filepath); InputStream stream; try { stream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException ex) { throw new IORejectionException("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } if (stream == null) { throw new IORejectionException("ENOENT", "ENOENT: could not open an input stream for '" + filepath + "'"); } return stream; } private OutputStream getOutputStream(String filepath, boolean append) throws IORejectionException { Uri uri = getFileUri(filepath); OutputStream stream; try { stream = reactContext.getContentResolver().openOutputStream(uri, append ? "wa" : "w"); } catch (FileNotFoundException ex) { throw new IORejectionException("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } if (stream == null) { throw new IORejectionException("ENOENT", "ENOENT: could not open an output stream for '" + filepath + "'"); } return stream; } private static byte[] getInputStreamBytes(InputStream inputStream) throws IOException { byte[] bytesResult; ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; try { int len; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } bytesResult = byteBuffer.toByteArray(); } finally { try { byteBuffer.close(); } catch (IOException ignored) { } } return bytesResult; } @ReactMethod public void writeFile(String filepath, String base64Content, ReadableMap options, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); OutputStream outputStream = getOutputStream(filepath, false); outputStream.write(bytes); outputStream.close(); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void appendFile(String filepath, String base64Content, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); OutputStream outputStream = getOutputStream(filepath, true); outputStream.write(bytes); outputStream.close(); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void write(String filepath, String base64Content, int position, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); if (position < 0) { OutputStream outputStream = getOutputStream(filepath, true); outputStream.write(bytes); outputStream.close(); } else { RandomAccessFile file = new RandomAccessFile(filepath, "rw"); file.seek(position); file.write(bytes); file.close(); } promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void exists(String filepath, Promise promise) { try { File file = new File(filepath); promise.resolve(file.exists()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void readFile(String filepath, Promise promise) { try { InputStream inputStream = getInputStream(filepath); byte[] inputData = getInputStreamBytes(inputStream); String base64Content = Base64.encodeToString(inputData, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void read(String filepath, int length, int position, Promise promise) { try { InputStream inputStream = getInputStream(filepath); byte[] buffer = new byte[length]; inputStream.skip(position); int bytesRead = inputStream.read(buffer, 0, length); String base64Content = Base64.encodeToString(buffer, 0, bytesRead, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void readFileAssets(String filepath, Promise promise) { InputStream stream = null; try { // ensure isn't a directory AssetManager assetManager = getReactApplicationContext().getAssets(); stream = assetManager.open(filepath, 0); if (stream == null) { reject(promise, filepath, new Exception("Failed to open file")); return; } byte[] buffer = new byte[stream.available()]; stream.read(buffer); String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } finally { if (stream != null) { try { stream.close(); } catch (IOException ignored) { } } } } @ReactMethod public void hash(String filepath, String algorithm, Promise promise) { try { Map<String, String> algorithms = new HashMap<>(); algorithms.put("md5", "MD5"); algorithms.put("sha1", "SHA-1"); algorithms.put("sha224", "SHA-224"); algorithms.put("sha256", "SHA-256"); algorithms.put("sha384", "SHA-384"); algorithms.put("sha512", "SHA-512"); if (!algorithms.containsKey(algorithm)) throw new Exception("Invalid hash algorithm"); File file = new File(filepath); if (file.isDirectory()) { rejectFileIsDirectory(promise); return; } if (!file.exists()) { rejectFileNotFound(promise, filepath); return; } MessageDigest md = MessageDigest.getInstance(algorithms.get(algorithm)); FileInputStream inputStream = new FileInputStream(filepath); byte[] buffer = new byte[1024 * 10]; // 10 KB Buffer int read; while ((read = inputStream.read(buffer)) != -1) { md.update(buffer, 0, read); } StringBuilder hexString = new StringBuilder(); for (byte digestByte : md.digest()) hexString.append(String.format("%02x", digestByte)); promise.resolve(hexString.toString()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void moveFile(String filepath, String destPath, ReadableMap options, Promise promise) { try { File inFile = new File(filepath); if (!inFile.renameTo(new File(destPath))) { new CopyFileTask() { protected void onPostExecute (Exception ex) { if (ex == null) { inFile.delete(); promise.resolve(true); } else { ex.printStackTrace(); reject(promise, filepath, ex); } }.execute(filepath, destPath); } else { promise.resolve(true); } } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void copyFile(final String filepath, final String destPath, ReadableMap options, final Promise promise) { new CopyFileTask() { protected void onPostExecute (Exception ex) { if (ex == null) { promise.resolve(null); } else { ex.printStackTrace(); reject(promise, filepath, ex); } }.execute(filepath, destPath); } private class CopyFileTask extends AsyncTask<String, Void, Exception> { protected Exception doInBackground(String... paths) { try { String filepath = paths[0]; String destPath = paths[1]; InputStream in = getInputStream(filepath); OutputStream out = getOutputStream(destPath, false); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); Thread.yield(); } in.close(); out.close(); return null; } catch (Exception ex) { return ex; } } } @ReactMethod public void readDir(String directory, Promise promise) { try { File file = new File(directory); if (!file.exists()) throw new Exception("Folder does not exist"); File[] files = file.listFiles(); WritableArray fileMaps = Arguments.createArray(); for (File childFile : files) { WritableMap fileMap = Arguments.createMap(); fileMap.putDouble("mtime", (double) childFile.lastModified() / 1000); fileMap.putString("name", childFile.getName()); fileMap.putString("path", childFile.getAbsolutePath()); fileMap.putInt("size", (int) childFile.length()); fileMap.putInt("type", childFile.isDirectory() ? 1 : 0); fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (Exception ex) { ex.printStackTrace(); reject(promise, directory, ex); } } @ReactMethod public void readDirAssets(String directory, Promise promise) { try { AssetManager assetManager = getReactApplicationContext().getAssets(); String[] list = assetManager.list(directory); WritableArray fileMaps = Arguments.createArray(); for (String childFile : list) { WritableMap fileMap = Arguments.createMap(); fileMap.putString("name", childFile); String path = directory.isEmpty() ? childFile : String.format("%s/%s", directory, childFile); // don't allow / at the start when directory is "" fileMap.putString("path", path); int length = 0; boolean isDirectory = true; try { AssetFileDescriptor assetFileDescriptor = assetManager.openFd(path); if (assetFileDescriptor != null) { length = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); isDirectory = false; } } catch (IOException ex) { //.. ah.. is a directory or a compressed file? isDirectory = ex.getMessage().indexOf("compressed") == -1; } fileMap.putInt("size", length); fileMap.putInt("type", isDirectory ? 1 : 0); // if 0, probably a folder.. fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (IOException e) { reject(promise, directory, e); } } @ReactMethod public void copyFileAssets(String assetPath, String destination, Promise promise) { AssetManager assetManager = getReactApplicationContext().getAssets(); try { InputStream in = assetManager.open(assetPath); copyInputStream(in, assetPath, destination, promise); } catch (IOException e) { // Default error message is just asset name, so make a more helpful error here. reject(promise, assetPath, new Exception(String.format("Asset '%s' could not be opened", assetPath))); } } @ReactMethod public void existsAssets(String filepath, Promise promise) { try { AssetManager assetManager = getReactApplicationContext().getAssets(); try { String[] list = assetManager.list(filepath); if (list != null && list.length > 0) { promise.resolve(true); return; } } catch (Exception ignored) { //.. probably not a directory then } // Attempt to open file (win = exists) InputStream fileStream = null; try { fileStream = assetManager.open(filepath); promise.resolve(true); } catch (Exception ex) { promise.resolve(false); // don't throw an error, resolve false } finally { if (fileStream != null) { try { fileStream.close(); } catch (Exception ignored) { } } } } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } /** * Internal method for copying that works with any InputStream * * @param in InputStream from assets or file * @param source source path (only used for logging errors) * @param destination destination path * @param promise React Callback */ private void copyInputStream(InputStream in, String source, String destination, Promise promise) { OutputStream out = null; try { out = getOutputStream(destination, false); byte[] buffer = new byte[1024 * 10]; // 10k buffer int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } // Success! promise.resolve(null); } catch (Exception ex) { reject(promise, source, new Exception(String.format("Failed to copy '%s' to %s (%s)", source, destination, ex.getLocalizedMessage()))); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } if (out != null) { try { out.close(); } catch (IOException ignored) { } } } } @ReactMethod public void setReadable(String filepath, Boolean readable, Boolean ownerOnly, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); file.setReadable(readable, ownerOnly); promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void stat(String filepath, Promise promise) { try { String originalFilepath = getOriginalFilepath(filepath); File file = new File(originalFilepath); if (!file.exists()) throw new Exception("File does not exist"); WritableMap statMap = Arguments.createMap(); statMap.putInt("ctime", (int) (file.lastModified() / 1000)); statMap.putInt("mtime", (int) (file.lastModified() / 1000)); statMap.putInt("size", (int) file.length()); statMap.putInt("type", file.isDirectory() ? 1 : 0); statMap.putString("originalFilepath", originalFilepath); promise.resolve(statMap); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void unlink(String filepath, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); DeleteRecursive(file); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); } } fileOrDirectory.delete(); } @ReactMethod public void mkdir(String filepath, ReadableMap options, Promise promise) { try { File file = new File(filepath); file.mkdirs(); boolean exists = file.exists(); if (!exists) throw new Exception("Directory could not be created"); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } @ReactMethod public void downloadFile(final ReadableMap options, final Promise promise) { try { File file = new File(options.getString("toFile")); URL url = new URL(options.getString("fromUrl")); final int jobId = options.getInt("jobId"); ReadableMap headers = options.getMap("headers"); int progressDivider = options.getInt("progressDivider"); int readTimeout = options.getInt("readTimeout"); int connectionTimeout = options.getInt("connectionTimeout"); DownloadParams params = new DownloadParams(); params.src = url; params.dest = file; params.headers = headers; params.progressDivider = progressDivider; params.readTimeout = readTimeout; params.connectionTimeout = connectionTimeout; params.onTaskCompleted = new DownloadParams.OnTaskCompleted() { public void onTaskCompleted(DownloadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putInt("bytesWritten", res.bytesWritten); promise.resolve(infoMap); } else { reject(promise, options.getString("toFile"), res.exception); } } }; params.onDownloadBegin = new DownloadParams.OnDownloadBegin() { public void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers) { WritableMap headersMap = Arguments.createMap(); for (Map.Entry<String, String> entry : headers.entrySet()) { headersMap.putString(entry.getKey(), entry.getValue()); } WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("statusCode", statusCode); data.putInt("contentLength", contentLength); data.putMap("headers", headersMap); sendEvent(getReactApplicationContext(), "DownloadBegin-" + jobId, data); } }; params.onDownloadProgress = new DownloadParams.OnDownloadProgress() { public void onDownloadProgress(int contentLength, int bytesWritten) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("contentLength", contentLength); data.putInt("bytesWritten", bytesWritten); sendEvent(getReactApplicationContext(), "DownloadProgress-" + jobId, data); } }; Downloader downloader = new Downloader(); downloader.execute(params); this.downloaders.put(jobId, downloader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, options.getString("toFile"), ex); } } @ReactMethod public void stopDownload(int jobId) { Downloader downloader = this.downloaders.get(jobId); if (downloader != null) { downloader.stop(); } } @ReactMethod public void uploadFiles(final ReadableMap options, final Promise promise) { try { ReadableArray files = options.getArray("files"); URL url = new URL(options.getString("toUrl")); final int jobId = options.getInt("jobId"); ReadableMap headers = options.getMap("headers"); ReadableMap fields = options.getMap("fields"); String method = options.getString("method"); ArrayList<ReadableMap> fileList = new ArrayList<>(); UploadParams params = new UploadParams(); for(int i =0;i<files.size();i++){ fileList.add(files.getMap(i)); } params.src = url; params.files =fileList; params.headers = headers; params.method=method; params.fields=fields; params.onUploadComplete = new UploadParams.onUploadComplete() { public void onUploadComplete(UploadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putMap("headers",res.headers); infoMap.putString("body",res.body); promise.resolve(infoMap); } else { reject(promise, options.getString("toUrl"), res.exception); } } }; params.onUploadBegin = new UploadParams.onUploadBegin() { public void onUploadBegin() { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); sendEvent(getReactApplicationContext(), "UploadBegin-" + jobId, data); } }; params.onUploadProgress = new UploadParams.onUploadProgress() { public void onUploadProgress(int totalBytesExpectedToSend,int totalBytesSent) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("totalBytesExpectedToSend", totalBytesExpectedToSend); data.putInt("totalBytesSent", totalBytesSent); sendEvent(getReactApplicationContext(), "UploadProgress-" + jobId, data); } }; Uploader uploader = new Uploader(); uploader.execute(params); this.uploaders.put(jobId, uploader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, options.getString("toUrl"), ex); } } @ReactMethod public void stopUpload(int jobId) { Uploader uploader = this.uploaders.get(jobId); if (uploader != null) { uploader.stop(); } } @ReactMethod public void pathForBundle(String bundleNamed, Promise promise) { // TODO: Not sure what equivalent would be? } @ReactMethod public void pathForGroup(String bundleNamed, Promise promise) { // TODO: Not sure what equivalent would be? } @ReactMethod public void getFSInfo(Promise promise) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long totalSpace; long freeSpace; if (android.os.Build.VERSION.SDK_INT >= 18) { totalSpace = stat.getTotalBytes(); freeSpace = stat.getFreeBytes(); } else { long blockSize = stat.getBlockSize(); totalSpace = blockSize * stat.getBlockCount(); freeSpace = blockSize * stat.getAvailableBlocks(); } WritableMap info = Arguments.createMap(); info.putDouble("totalSpace", (double) totalSpace); // Int32 too small, must use Double info.putDouble("freeSpace", (double) freeSpace); promise.resolve(info); } @ReactMethod public void touch(String filepath, double mtime, double ctime, Promise promise) { try { File file = new File(filepath); promise.resolve(file.setLastModified((long) mtime)); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void getAllExternalFilesDirs(Promise promise){ File[] allExternalFilesDirs = this.getReactApplicationContext().getExternalFilesDirs(null); WritableArray fs = Arguments.createArray(); for (File f : allExternalFilesDirs) { fs.pushString(f.getAbsolutePath()); } promise.resolve(fs); } private void reject(Promise promise, String filepath, Exception ex) { if (ex instanceof FileNotFoundException) { rejectFileNotFound(promise, filepath); return; } if (ex instanceof IORejectionException) { IORejectionException ioRejectionException = (IORejectionException) ex; promise.reject(ioRejectionException.getCode(), ioRejectionException.getMessage()); return; } promise.reject(null, ex.getMessage()); } private void rejectFileNotFound(Promise promise, String filepath) { promise.reject("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } private void rejectFileIsDirectory(Promise promise) { promise.reject("EISDIR", "EISDIR: illegal operation on a directory, read"); } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(RNFSDocumentDirectory, 0); constants.put(RNFSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath()); constants.put(RNFSTemporaryDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(RNFSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); constants.put(RNFSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(RNFSFileTypeRegular, 0); constants.put(RNFSFileTypeDirectory, 1); File externalStorageDirectory = Environment.getExternalStorageDirectory(); if (externalStorageDirectory != null) { constants.put(RNFSExternalStorageDirectoryPath, externalStorageDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalStorageDirectoryPath, null); } File externalDirectory = this.getReactApplicationContext().getExternalFilesDir(null); if (externalDirectory != null) { constants.put(RNFSExternalDirectoryPath, externalDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalDirectoryPath, null); } File externalCachesDirectory = this.getReactApplicationContext().getExternalCacheDir(); if (externalCachesDirectory != null) { constants.put(RNFSExternalCachesDirectoryPath, externalCachesDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalCachesDirectoryPath, null); } return constants; } }
package org.jboss.xnio; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Collections; import java.util.IdentityHashMap; import java.io.Serializable; /** * An immutable map of options to option values. No {@code null} keys or values are permitted. */ public final class OptionMap implements Iterable<Option<?>>, Serializable { private static final long serialVersionUID = 3632842565346928132L; private final Map<Option<?>, Object> value; private OptionMap(final Map<Option<?>, Object> value) { this.value = value; } /** * Determine whether this option map contains the given option. * * @param option the option to check * @return {@code true} if the option is present in the option map */ public boolean contains(Option<?> option) { return value.containsKey(option); } /** * Get the value of an option from this option map. * * @param option the option to get * @param <T> the type of the option * @return the option value, or {@code null} if it is not present */ public <T> T get(Option<T> option) { return option.cast(value.get(option)); } /** * Get a boolean value from this option map, with a specified default if the value is missing. * * @param option the option to get * @param defaultValue the default value if the option is not present * @return the result */ public boolean get(Option<Boolean> option, boolean defaultValue) { final Object o = value.get(option); return o == null ? defaultValue : option.cast(o).booleanValue(); } /** * Get a int value from this option map, with a specified default if the value is missing. * * @param option the option to get * @param defaultValue the default value if the option is not present * @return the result */ public int get(Option<Integer> option, int defaultValue) { final Object o = value.get(option); return o == null ? defaultValue : option.cast(o).intValue(); } /** * Iterate over the options in this map. * * @return an iterator over the options */ public Iterator<Option<?>> iterator() { return Collections.unmodifiableCollection(value.keySet()).iterator(); } /** * Get the number of options stored in this map. * * @return the number of options */ public int size() { return value.size(); } /** * The empty option map. */ public static final OptionMap EMPTY = new OptionMap(Collections.<Option<?>, Object>emptyMap()); /** * Create a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * A builder for immutable option maps. Create an instance with the {@link OptionMap#builder()} method. */ public static final class Builder { private Builder() { } private static class OVPair<T> { Option<T> option; T value; private OVPair(final Option<T> option, final T value) { this.option = option; this.value = value; } } private List<OVPair<?>> list = new ArrayList<OVPair<?>>(); /** * Add a key-value pair. * * @param key the key * @param value the value * @param <T> the option type * @return this builder */ public <T> Builder add(Option<T> key, T value) { if (value == null) { throw new NullPointerException("value is null"); } list.add(new OVPair<T>(key, value)); return this; } /** * Add an int value to an Integer key. * * @param key the option * @param value the value * @return this builder */ public Builder add(Option<Integer> key, int value) { list.add(new OVPair<Integer>(key, Integer.valueOf(value))); return this; } /** * Add int values to an Integer sequence key. * * @param key the key * @param values the values * @return this builder */ public Builder addSequence(Option<Sequence<Integer>> key, int... values) { Integer[] a = new Integer[values.length]; for (int i = 0; i < values.length; i++) { a[i] = Integer.valueOf(values[i]); } list.add(new OVPair<Sequence<Integer>>(key, Sequence.of(a))); return this; } /** * Add a long value to a Long key. * * @param key the option * @param value the value * @return this builder */ public Builder add(Option<Long> key, long value) { list.add(new OVPair<Long>(key, Long.valueOf(value))); return this; } /** * Add long values to an Long sequence key. * * @param key the key * @param values the values * @return this builder */ public Builder addSequence(Option<Sequence<Long>> key, long... values) { Long[] a = new Long[values.length]; for (int i = 0; i < values.length; i++) { a[i] = Long.valueOf(values[i]); } list.add(new OVPair<Sequence<Long>>(key, Sequence.of(a))); return this; } /** * Add a boolean value to a Boolean key. * * @param key the option * @param value the value * @return this builder */ public Builder add(Option<Boolean> key, boolean value) { list.add(new OVPair<Boolean>(key, Boolean.valueOf(value))); return this; } /** * Add boolean values to an Boolean sequence key. * * @param key the key * @param values the values * @return this builder */ public Builder addSequence(Option<Sequence<Boolean>> key, boolean... values) { Boolean[] a = new Boolean[values.length]; for (int i = 0; i < values.length; i++) { a[i] = Boolean.valueOf(values[i]); } list.add(new OVPair<Sequence<Boolean>>(key, Sequence.of(a))); return this; } /** * Add a key-value pair, where the value is a sequence type. * * @param key the key * @param values the values * @param <T> the option type * @return this builder */ public <T> Builder addSequence(Option<Sequence<T>> key, T... values) { list.add(new OVPair<Sequence<T>>(key, Sequence.of(values))); return this; } /** * Add a key-value pair, where the value is a flag type. * * @param key the key * @param values the values * @param <T> the option type * @return this builder */ public <T extends Enum<T>> Builder addFlags(Option<FlagSet<T>> key, T... values) { list.add(new OVPair<FlagSet<T>>(key, FlagSet.of(values))); return this; } private <T> void copy(Map<?, ?> map, Option<T> option) { add(option, option.cast(map.get(option))); } /** * Add all the entries of a map. Any keys of the map which are not valid {@link Option}s, or whose * values are not valid arguments for the given {@code Option}, will cause an exception to be thrown. * * @param map the map * @return this builder * @throws ClassCastException if any entries of the map are not valid option-value pairs */ public Builder add(Map<?, ?> map) throws ClassCastException { for (Object key : map.keySet()) { final Option<?> option = Option.class.cast(key); copy(map, option); } return this; } private <T> void copy(OptionMap optionMap, Option<T> option) { add(option, optionMap.get(option)); } /** * Add all entries from an existing option map to the one being built. * * @param optionMap the original option map * @return this builder */ public Builder addAll(OptionMap optionMap) { for (Option<?> option : optionMap) { copy(optionMap, option); } return this; } /** * Build a map that reflects the current state of this builder. * * @return the new immutable option map */ public OptionMap getMap() { final List<OVPair<?>> list = this.list; if (list.size() == 0) { return EMPTY; } else if (list.size() == 1) { final OVPair<?> pair = list.get(0); return new OptionMap(Collections.<Option<?>, Object>singletonMap(pair.option, pair.value)); } else { final Map<Option<?>, Object> map = new IdentityHashMap<Option<?>, Object>(); for (OVPair<?> ovPair : list) { map.put(ovPair.option, ovPair.value); } return new OptionMap(map); } } } }