lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
error: pathspec 'sources/scala/tools/scalatest/Console.java' did not match any file(s) known to git
04e430874f95a708019d654f5eb6799f5a1498c1
1
scala/scala,martijnhoekstra/scala,shimib/scala,martijnhoekstra/scala,jvican/scala,jvican/scala,shimib/scala,shimib/scala,shimib/scala,jvican/scala,jvican/scala,jvican/scala,shimib/scala,slothspot/scala,felixmulder/scala,felixmulder/scala,felixmulder/scala,slothspot/scala,scala/scala,shimib/scala,felixmulder/scala,martijnhoekstra/scala,slothspot/scala,slothspot/scala,lrytz/scala,lrytz/scala,jvican/scala,lrytz/scala,lrytz/scala,felixmulder/scala,slothspot/scala,slothspot/scala,felixmulder/scala,scala/scala,martijnhoekstra/scala,martijnhoekstra/scala,scala/scala,scala/scala,slothspot/scala,scala/scala,lrytz/scala,felixmulder/scala,jvican/scala,martijnhoekstra/scala,lrytz/scala
/* ___ ____ ___ __ ___ _____ ** / _// __// _ | / / / _ |/_ _/ Scala test ** __\ \/ /__/ __ |/ /__/ __ | / / (c) 2003, LAMP/EPFL ** /____/\___/_/ |_/____/_/ |_//_/ ** ** $Id$ */ package scala.tools.scalatest; import java.io.*; import java.text.*; class Console { // ANSI colors foreground public final static String BLACK = "\033[30m"; public final static String RED = "\033[31m"; public final static String GREEN = "\033[32m"; public final static String YELLOW = "\033[33m"; public final static String BLUE = "\033[34m"; public final static String MAGENTA = "\033[35m"; public final static String CYAN = "\033[36m"; public final static String WHITE = "\033[37m"; public final static String COLOR38 = "\033[38m"; public final static String COLOR39 = "\033[39m"; // ANSI colors background public final static String BLACK_B = "\033[40m"; public final static String RED_B = "\033[41m"; public final static String GREEN_B = "\033[42m"; public final static String YELLOW_B = "\033[43m"; public final static String BLUE_B = "\033[44m"; public final static String MAGENTA_B = "\033[45m"; public final static String CYAN_B = "\033[46m"; public final static String WHITE_B = "\033[47m"; // ANSI styles public final static String RESET = "\033[0m"; public final static String BOLD = "\033[1m"; public final static String UNDERLINED = "\033[4m"; public final static String BLINK = "\033[5m"; public final static String REVERSED = "\033[7m"; public final static String INVISIBLE = "\033[8m"; private PrintStream out = System.out; private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); /** Set the default output stream. * * @param out the new output stream. */ public void setOut(PrintStream out) { this.out = out; } /** Set the default input stream. * * @param in the new input stream. */ public void setIn(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } /** Set the default input stream. * * @param reader specifies the new input stream. */ public void setIn(Reader reader) { this.in = new BufferedReader(reader); } /** Print an object on the terminal. * * @param obj the object to print. */ public void print(Object obj) { out.print((obj == null) ? "null" : obj.toString()); } /** Flush the output stream. This function is required when partial * output (i.e. output not terminated by a new line character) has * to be made visible on the terminal. */ public void flush() { out.flush(); } /** Print a new line character on the terminal. */ public void println() { out.println(); } /** Print out an object followed by a new line character. * * @param x the object to print. */ public void println(Object x) { out.println(x); } /** Format and print out some text (in a fashion similar to printf in C). * The format of the text to print is specified by the parameter * <code>text</code>. The arguments that are inserted into specific * locations in <code>text</code> are provided with parameter * <code>args</code>. See class <code>java.text.MessageFormat</code> * for a full specification of the format syntax. * * @param text the format of the text to print out. * @param args the parameters used to instantiate the format. */ public void printf(String text, Object[] args) { if (text == null) out.print("null"); else out.print(MessageFormat.format(text, args)); } /** Read a full line from the terminal. * * @return the string read from the terminal. */ public String readLine() throws IOException { return in.readLine(); } /** Read a boolean value from the terminal. * * @return the boolean value read from the terminal. */ public boolean readBoolean() throws IOException { String value = in.readLine().toLowerCase(); return "true".equals(value) || "t".equals(value) || "yes".equals(value) || "y".equals(value); } /** Read a byte value from the terminal. */ public byte readByte() throws IOException { return java.lang.Byte.decode(in.readLine()).byteValue(); } /** Read a short value from the terminal. */ public short readShort() throws IOException { return java.lang.Short.decode(in.readLine()).shortValue(); } /** Read a char value from the terminal. */ public char readChar() throws IOException { return in.readLine().charAt(0); } /** Read an int value from the terminal. */ public int readInt() throws IOException { return java.lang.Integer.decode(in.readLine()).intValue(); } /** Read a float value from the terminal. */ public float readFloat() throws IOException { return java.lang.Float.parseFloat(in.readLine()); } /** Read a double value from the terminal. */ public double readDouble() throws IOException { return java.lang.Double.parseDouble(in.readLine()); } }
sources/scala/tools/scalatest/Console.java
- same class as scala/Console.scala, but in Jav... - same class as scala/Console.scala, but in Java (for now)
sources/scala/tools/scalatest/Console.java
- same class as scala/Console.scala, but in Jav...
Java
apache-2.0
error: pathspec 'core/java/src/net/i2p/stat/StatLogSplitter.java' did not match any file(s) known to git
0526d5b53abbeb10b9bf682712189dd3f7c352a6
1
i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie
package net.i2p.stat; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Simple CLI to splot the stat logs into per-stat files containing * #seconds since beginning and the value (ready for loading into your * favorite plotting tool) */ public class StatLogSplitter { private static final String DATE_FORMAT = "yyyyMMdd hh:mm:ss.SSS"; private static SimpleDateFormat _fmt = new SimpleDateFormat(DATE_FORMAT); public static void main(String args[]) { if (args.length != 1) { System.err.println("Usage: StatLogSplitter filename"); return; } splitLog(args[0]); } private static void splitLog(String filename) { Map outputFiles = new HashMap(4); try { BufferedReader in = new BufferedReader(new FileReader(filename)); String line; long first = 0; while ( (line = in.readLine()) != null) { String date = line.substring(0, DATE_FORMAT.length()).trim(); int endGroup = line.indexOf(' ', DATE_FORMAT.length()+1); int endStat = line.indexOf(' ', endGroup+1); int endValue = line.indexOf(' ', endStat+1); String group = line.substring(DATE_FORMAT.length()+1, endGroup).trim(); String stat = line.substring(endGroup, endStat).trim(); String value = line.substring(endStat, endValue).trim(); String duration = line.substring(endValue).trim(); //System.out.println(date + " " + group + " " + stat + " " + value + " " + duration); try { Date when = _fmt.parse(date); if (first <= 0) first = when.getTime(); long val = Long.parseLong(value); long time = Long.parseLong(duration); if (!outputFiles.containsKey(stat)) { outputFiles.put(stat, new FileWriter(stat + ".dat")); System.out.println("Including data to " + stat + ".dat"); } FileWriter out = (FileWriter)outputFiles.get(stat); double s = (when.getTime()-first)/1000.0; out.write(s + " " + val + "\n"); out.flush(); } catch (ParseException pe) { continue; } catch (NumberFormatException nfe){ continue; } } } catch (IOException ioe) { ioe.printStackTrace(); } for (Iterator iter = outputFiles.values().iterator(); iter.hasNext(); ) { FileWriter out = (FileWriter)iter.next(); try { out.close(); } catch (IOException ioe) {} } } }
core/java/src/net/i2p/stat/StatLogSplitter.java
cli to splot the stat log
core/java/src/net/i2p/stat/StatLogSplitter.java
cli to splot the stat log
Java
apache-2.0
error: pathspec 'main/src/com/pathtomani/entities/item/ItemConfig.java' did not match any file(s) known to git
1d2e4d2cde252cc137898c7459c8443d3de4435b
1
BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani,BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,TheNightForum/Path-to-Mani
/* * Copyright 2016 BurntGameProductions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pathtomani.entities.item; import java.util.List; public class ItemConfig { public final List<ManiItem> examples; public final int amt; public final float chance; public ItemConfig(List<ManiItem> examples, int amt, float chance) { this.examples = examples; this.amt = amt; this.chance = chance; } }
main/src/com/pathtomani/entities/item/ItemConfig.java
Moving files to Entites.
main/src/com/pathtomani/entities/item/ItemConfig.java
Moving files to Entites.
Java
apache-2.0
error: pathspec 'mvp/src/main/java/by/vshkl/model/ResponseWrapper.java' did not match any file(s) known to git
1c9cf05196e8017e51eae13228dbb65a88424835
1
vshkl/BashQ
package by.vshkl.model; public class ResponseWrapper<T> { public T body; }
mvp/src/main/java/by/vshkl/model/ResponseWrapper.java
ResponceWrapper class added
mvp/src/main/java/by/vshkl/model/ResponseWrapper.java
ResponceWrapper class added
Java
apache-2.0
error: pathspec 'servers/src/main/java/tachyon/worker/ClientRWLock.java' did not match any file(s) known to git
37b68e0eac26193d01315fa31e1831eb02229017
1
Reidddddd/mo-alluxio,riversand963/alluxio,wwjiang007/alluxio,riversand963/alluxio,jswudi/alluxio,Alluxio/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,calvinjia/tachyon,uronce-cc/alluxio,Reidddddd/alluxio,uronce-cc/alluxio,madanadit/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,madanadit/alluxio,aaudiber/alluxio,aaudiber/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,uronce-cc/alluxio,calvinjia/tachyon,jswudi/alluxio,aaudiber/alluxio,apc999/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,madanadit/alluxio,yuluo-ding/alluxio,bf8086/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,bf8086/alluxio,PasaLab/tachyon,uronce-cc/alluxio,madanadit/alluxio,bf8086/alluxio,maboelhassan/alluxio,apc999/alluxio,riversand963/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,PasaLab/tachyon,ShailShah/alluxio,maobaolong/alluxio,bf8086/alluxio,ChangerYoung/alluxio,madanadit/alluxio,wwjiang007/alluxio,Alluxio/alluxio,ShailShah/alluxio,Reidddddd/alluxio,jswudi/alluxio,apc999/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,calvinjia/tachyon,jsimsa/alluxio,madanadit/alluxio,ChangerYoung/alluxio,PasaLab/tachyon,ChangerYoung/alluxio,bf8086/alluxio,bf8086/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,Alluxio/alluxio,apc999/alluxio,maobaolong/alluxio,maboelhassan/alluxio,jsimsa/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,ShailShah/alluxio,jsimsa/alluxio,wwjiang007/alluxio,jsimsa/alluxio,riversand963/alluxio,Reidddddd/alluxio,calvinjia/tachyon,riversand963/alluxio,PasaLab/tachyon,wwjiang007/alluxio,Reidddddd/alluxio,maobaolong/alluxio,riversand963/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,calvinjia/tachyon,madanadit/alluxio,aaudiber/alluxio,calvinjia/tachyon,WilliamZapata/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,maobaolong/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,aaudiber/alluxio,WilliamZapata/alluxio,yuluo-ding/alluxio,Reidddddd/mo-alluxio,apc999/alluxio,maobaolong/alluxio,maboelhassan/alluxio,maobaolong/alluxio,ChangerYoung/alluxio,jswudi/alluxio,jsimsa/alluxio,apc999/alluxio,maobaolong/alluxio,PasaLab/tachyon,madanadit/alluxio,ShailShah/alluxio,wwjiang007/alluxio,apc999/alluxio,maobaolong/alluxio,calvinjia/tachyon,maboelhassan/alluxio,Reidddddd/alluxio,Alluxio/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,jswudi/alluxio,Alluxio/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,Alluxio/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,WilliamZapata/alluxio
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.worker; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; /** * Read/write lock associated with clients rather than threads. Either its read lock or write lock * can be released by a thread different from the thread acquiring them. */ public class ClientRWLock implements ReadWriteLock { private static final int MAX_AVAILABLE = 100; private final Semaphore mAvailable = new Semaphore(MAX_AVAILABLE, true); @Override public Lock readLock() { return new UserLock(mAvailable, 1); } @Override public Lock writeLock() { return new UserLock(mAvailable, MAX_AVAILABLE); } private class UserLock implements Lock { private final int mPermits; private Semaphore mSemaphore; private UserLock(Semaphore semaphore, int permits) { mSemaphore = semaphore; mPermits = permits; } @Override public void lock() { mSemaphore.acquireUninterruptibly(mPermits); } @Override public void lockInterruptibly() throws InterruptedException { mSemaphore.acquire(mPermits); } @Override public boolean tryLock() { return mSemaphore.tryAcquire(mPermits); } @Override public boolean tryLock(long time, TimeUnit unit) { try { return mSemaphore.tryAcquire(mPermits, time, unit); } catch (InterruptedException e) { return false; } } @Override public void unlock() { mSemaphore.release(mPermits); } @Override public Condition newCondition() { // Not supported return null; } } }
servers/src/main/java/tachyon/worker/ClientRWLock.java
Add a ReadWrite lock implementation based on Semaphore. The reason to have this lock is to ensure we can release previously acquired locks from different threads
servers/src/main/java/tachyon/worker/ClientRWLock.java
Add a ReadWrite lock implementation based on Semaphore. The reason to have this lock is to ensure we can release previously acquired locks from different threads
Java
apache-2.0
error: pathspec 'src/main/java/io/schinzel/basicutils/file/REMOVE_ME.java' did not match any file(s) known to git
28e20f84e2aac287f081a559c6f68c68ad169d80
1
Schinzel/basic-utils
package io.schinzel.basicutils.file; /** * Purpose of this class is ... * <p> * Created by Schinzel on 2018-01-10 */ public class REMOVE_ME { public static void main(String[] args) { // FileRW.readAsString("myfile.txt"); FileRW.write("myfile.txt", "my content"); // FileReader.create("myfile.txt").readAsString(); FileWriter.create("myfile.txt").write("my content"); // FileReader2.readAsString("myfile.txt"); FileWriter2.write("myfile.txt", "my content"); } }
src/main/java/io/schinzel/basicutils/file/REMOVE_ME.java
Examples
src/main/java/io/schinzel/basicutils/file/REMOVE_ME.java
Examples
Java
apache-2.0
error: pathspec 'src/main/java/com/jaamsim/resourceObjects/ResourceUnit.java' did not match any file(s) known to git
62b8f5fff09cdcdfdf2c4a10b19c91995c19e2f5
1
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2018 JaamSim Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.resourceObjects; import com.jaamsim.BasicObjects.DowntimeEntity; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.ProcessFlow.StateUserEntity; public class ResourceUnit extends StateUserEntity implements Seizable { public ResourceUnit() {} @Override public ResourcePool getResourcePool() { // TODO Auto-generated method stub return null; } @Override public boolean canSeize(DisplayEntity ent) { // TODO Auto-generated method stub return false; } @Override public void seize(DisplayEntity ent) { // TODO Auto-generated method stub } @Override public void release() { // TODO Auto-generated method stub } @Override public DisplayEntity getAssignment() { // TODO Auto-generated method stub return null; } @Override public void thresholdChanged() { // TODO Auto-generated method stub } @Override public boolean canStartDowntime(DowntimeEntity down) { // TODO Auto-generated method stub return false; } @Override public void prepareForDowntime(DowntimeEntity down) { // TODO Auto-generated method stub } @Override public void startDowntime(DowntimeEntity down) { // TODO Auto-generated method stub } @Override public void endDowntime(DowntimeEntity down) { // TODO Auto-generated method stub } }
src/main/java/com/jaamsim/resourceObjects/ResourceUnit.java
JS: add ResourceUnit class Signed-off-by: Harry King <409587b9e6671aa0763646191d292852dc49a658@gmail.com>
src/main/java/com/jaamsim/resourceObjects/ResourceUnit.java
JS: add ResourceUnit class
Java
apache-2.0
error: pathspec 'java/server/test/org/openqa/grid/e2e/selenium/NodeRecoveryTest.java' did not match any file(s) known to git
ada9e5c8c0f80ac9696a384e8eb1099719d62a4d
1
akiellor/selenium,akiellor/selenium,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,akiellor/selenium,akiellor/selenium,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,akiellor/selenium,akiellor/selenium,winhamwr/selenium,akiellor/selenium,akiellor/selenium,virajs/selenium-1
package org.openqa.grid.e2e.selenium; import org.openqa.grid.e2e.utils.GridConfigurationMock; import org.openqa.grid.internal.Registry; import org.openqa.grid.internal.RemoteProxy; import org.openqa.grid.selenium.SelfRegisteringRemote; import org.openqa.grid.selenium.utils.GridConfiguration; import org.openqa.grid.web.Hub; import org.openqa.selenium.net.PortProber; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.thoughtworks.selenium.DefaultSelenium; import com.thoughtworks.selenium.Selenium; public class NodeRecoveryTest { private Hub hub; GridConfiguration proxy; SelfRegisteringRemote node; int originalTimeout =3000; int newtimeout = 20000; @BeforeClass(alwaysRun = true) public void setup() throws Exception { hub = Hub.getNewInstanceForTest(PortProber.findFreePort(), Registry.getNewInstanceForTestOnly()); hub.start(); proxy = GridConfigurationMock.seleniumConfig(hub.getRegistrationURL()); node = SelfRegisteringRemote.create(proxy); // register a selenium 1 with a timeout of 3 sec node.addFirefoxSupport(); node.setTimeout(originalTimeout, 1000); node.launchRemoteServer(); node.registerToHub(); } @Test(enabled=false) public void test() throws Exception { Assert.assertEquals(hub.getRegistry().getAllProxies().size(), 1); for (RemoteProxy p : hub.getRegistry().getAllProxies()) { Assert.assertEquals(p.getTimeOut(), originalTimeout); } String url = "http://" + hub.getHost() + ":" + hub.getPort() + "/grid/console"; Selenium selenium = new DefaultSelenium(hub.getHost(), hub.getPort(), "*firefox", url); selenium.start(); // kill the node node.stopRemoteServer(); // change its config. node.setTimeout(newtimeout, 1000); System.out.println(node.getRegistrationRequest().toJSON()); // restart it node.launchRemoteServer(); node.registerToHub(); // wait for 5 sec : the timeout of the original node should be reached, and the session freed Thread.sleep(5000); Assert.assertEquals(hub.getRegistry().getActiveSessions().size(), 0); Assert.assertEquals(hub.getRegistry().getAllProxies().size(), 1); for (RemoteProxy p : hub.getRegistry().getAllProxies()) { System.out.println(p); Assert.assertEquals(p.getTimeOut(), newtimeout); } } }
java/server/test/org/openqa/grid/e2e/selenium/NodeRecoveryTest.java
FrancoisReynaud: adding. a test to debug timeout and re-registration of nodes.file left out of commit 12073 git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@12078 07704840-8298-11de-bf8c-fd130f914ac9
java/server/test/org/openqa/grid/e2e/selenium/NodeRecoveryTest.java
FrancoisReynaud: adding. a test to debug timeout and re-registration of nodes.file left out of commit 12073
Java
apache-2.0
error: pathspec 'src/impl/edu/columbia/gemma/common/auditAndSecurity/PersonImpl.java' did not match any file(s) known to git
b435bef96ffc401c2333f888be7c1355c04992a4
1
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
/* * The Gemma project. * * Copyright (c) 2005 Columbia University * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package edu.columbia.gemma.common.auditAndSecurity; /** * <hr> * <p> * Copyright (c) 2004-2005 Columbia University * * @author pavlidis * @version $Id$ */ public class PersonImpl extends edu.columbia.gemma.common.auditAndSecurity.Person implements java.io.Serializable { /** The serial version UID of this class. Needed for serialization. */ private static final long serialVersionUID = -3335182453066930211L; /** * @see edu.columbia.gemma.common.auditAndSecurity.Person#getFullName() */ public java.lang.String getFullName() { return this.getFirstName() + " " + this.getLastName(); } }
src/impl/edu/columbia/gemma/common/auditAndSecurity/PersonImpl.java
getFullName method.
src/impl/edu/columbia/gemma/common/auditAndSecurity/PersonImpl.java
getFullName method.
Java
apache-2.0
error: pathspec 'src/test/java/org/semanticweb/drew/rl/sparql/SparqlCompilerTest.java' did not match any file(s) known to git
3d5b1a95974a9f0c05ba9e73f01da5586eb9cf22
1
ghxiao/drew,ghxiao/drew,ghxiao/drew,ghxiao/drew
package org.semanticweb.drew.rl.sparql; import static org.junit.Assert.*; import org.junit.Test; import org.semanticweb.drew.dlprogram.format.DLProgramStorer; import org.semanticweb.drew.dlprogram.format.DLProgramStorerImpl; import org.semanticweb.drew.dlprogram.format.RLProgramStorerImpl; import org.semanticweb.drew.dlprogram.model.Clause; import org.semanticweb.drew.el.reasoner.DReWELManager; import org.semanticweb.drew.el.reasoner.NamingStrategy; import org.semanticweb.drew.ldlp.reasoner.LDLPQueryCompiler; import org.semanticweb.drew.rl.sparql.SparqlCompiler; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.Syntax; public class SparqlCompilerTest { @Test public void test() { String prefixRDF = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "; String queryText = prefixRDF + "PREFIX : <#>" + "SELECT ?X ?Y " + "WHERE {" + "?X rdf:type :preOnt1____ORDERS_LineItemQuantity ." + "?X :preOnt1____hasValue ?Y " + "}"; Query query = QueryFactory.create(queryText, Syntax.syntaxARQ); SparqlCompiler sparqlCompiler = new SparqlCompiler(); Clause drewQuery = sparqlCompiler.compileQuery(query); LDLPQueryCompiler queryCompiler = new LDLPQueryCompiler(); Clause drewRLQuery = queryCompiler.compileQuery(drewQuery); DLProgramStorer storer = new RLProgramStorerImpl(); storer.store(drewQuery, System.out); storer.store(drewRLQuery, System.out); } }
src/test/java/org/semanticweb/drew/rl/sparql/SparqlCompilerTest.java
add a sparql compiler test
src/test/java/org/semanticweb/drew/rl/sparql/SparqlCompilerTest.java
add a sparql compiler test
Java
apache-2.0
error: pathspec 'objector-ots/src/main/java/org/chenmin/open/objector/BooleanIntrospector.java' did not match any file(s) known to git
8663a73d70dfa1efa3deaa4748eada1f1cc105ba
1
chenmins/objector
package org.chenmin.open.objector; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import org.apache.commons.beanutils.BeanIntrospector; import org.apache.commons.beanutils.IntrospectionContext; import org.apache.commons.lang.WordUtils; public class BooleanIntrospector implements BeanIntrospector{ @Override public void introspect(IntrospectionContext icontext) throws IntrospectionException { for (Method m : icontext.getTargetClass().getMethods()) { if (m.getName().startsWith("is") && Boolean.class.equals(m.getReturnType())) { String propertyName = getPropertyName(m); PropertyDescriptor pd = icontext.getPropertyDescriptor(propertyName); if (pd == null) icontext.addPropertyDescriptor(new PropertyDescriptor(propertyName, m, getWriteMethod(icontext.getTargetClass(), propertyName))); else if (pd.getReadMethod() == null) pd.setReadMethod(m); } } } private String getPropertyName(Method m){ return WordUtils.uncapitalize(m.getName().substring(2, m.getName().length())); } private Method getWriteMethod(Class<?> clazz, String propertyName){ try { return clazz.getMethod("get" + WordUtils.capitalize(propertyName)); } catch (NoSuchMethodException e) { return null; } } }
objector-ots/src/main/java/org/chenmin/open/objector/BooleanIntrospector.java
boolean 类型的 Boolean isBoolean() 特殊处理类
objector-ots/src/main/java/org/chenmin/open/objector/BooleanIntrospector.java
boolean 类型的 Boolean isBoolean() 特殊处理类
Java
apache-2.0
error: pathspec 'ph-commons/src/test/java/com/helger/commons/supplementary/test/MainFileOnWindows.java' did not match any file(s) known to git
11f7f99b0692f244610065c04202d67220ea9ecf
1
phax/ph-commons
/** * Copyright (C) 2014-2019 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.commons.supplementary.test; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class MainFileOnWindows { private static final Logger LOGGER = LoggerFactory.getLogger (MainFileOnWindows.class); private MainFileOnWindows () {} public static void main (final String [] args) { final File fBase = new File ("f:\\test\\bla.txt"); File f = fBase; while (f != null) { LOGGER.info ("'" + f.getName () + "'"); LOGGER.info (" '" + f.getPath () + "'"); f = f.getParentFile (); } } }
ph-commons/src/test/java/com/helger/commons/supplementary/test/MainFileOnWindows.java
Small test file
ph-commons/src/test/java/com/helger/commons/supplementary/test/MainFileOnWindows.java
Small test file
Java
apache-2.0
error: pathspec 'openrest-filters/src/main/java/pl/openrest/filters/query/registry/JoinInformation.java' did not match any file(s) known to git
873632fc0a7ca3a4d6753de701cf537b63a68f0c
1
konik32/openrest
package pl.openrest.filters.query.registry; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import com.mysema.query.types.Path; @Getter @ToString @EqualsAndHashCode public class JoinInformation { private final Path<?> path; private final boolean collection; private final boolean fetch; private final Class<?> type; public JoinInformation(Path<?> path, boolean collection, boolean fetch, Class<?> type) { this.path = path; this.collection = collection; this.fetch = fetch; this.type = type; } }
openrest-filters/src/main/java/pl/openrest/filters/query/registry/JoinInformation.java
Create JoinInformation
openrest-filters/src/main/java/pl/openrest/filters/query/registry/JoinInformation.java
Create JoinInformation
Java
apache-2.0
error: pathspec 'src/test/java/com/feilong/core/lang/classloaderitiltest/ClassLoaderUtilGetResourceInAllClassLoaderTest.java' did not match any file(s) known to git
55366d5e0930e61e7cb809ddcc82eaac7929cc09
1
venusdrogon/feilong-core,venusdrogon/feilong-core
/* * Copyright (C) 2008 feilong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.feilong.core.lang.classloaderitiltest; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.feilong.core.lang.ClassLoaderUtil; /** * The Class ClassLoaderUtilGetResourceInAllClassLoaderTest. * * @author <a href="http://feitianbenyue.iteye.com/">feilong</a> */ public class ClassLoaderUtilGetResourceInAllClassLoaderTest{ /** * Test get resource not found. */ @Test public void testGetResourceNotFound(){ assertEquals(null, ClassLoaderUtil.getResourceInAllClassLoader("slf4j-log4j12-1.7.21", this.getClass())); assertEquals(null, ClassLoaderUtil.getResourceInAllClassLoader("slf4j-log4j12-1.7.21.jar", this.getClass())); } /** * Test get resource null resource name. */ @Test(expected = NullPointerException.class) public void testGetResourceNullResourceName(){ ClassLoaderUtil.getResourceInAllClassLoader(null, this.getClass()); } //************************************************************************************* /** * Test get resource null calling class. */ @Test public void testGetResourceNullCallingClass(){ String path = "file:/E:/Workspaces/feilong/feilong-core/target/classes/com/feilong/core/lang/ArrayUtil.class"; String resourceName = "com/feilong/core/lang/ArrayUtil.class"; assertEquals(path, ClassLoaderUtil.getResourceInAllClassLoader(resourceName, null).toString()); } /** * Test get resource 232. */ @Test public void testGetResource232(){ String path = "file:/E:/Workspaces/feilong/feilong-core/target/classes/com/feilong/core/lang/ArrayUtil.class"; String resourceName = "com/feilong/core/lang/ArrayUtil.class"; assertEquals(path, ClassLoaderUtil.getResourceInAllClassLoader(resourceName, this.getClass()).toString()); } /** * Test get resource slan. */ @Test public void testGetResourceSlan(){ String path = "file:/E:/Workspaces/feilong/feilong-core/target/classes/com/feilong/core/lang/ArrayUtil.class"; String resourceName = "com/feilong/core/lang/ArrayUtil.class"; assertEquals(path, ClassLoaderUtil.getResourceInAllClassLoader("/" + resourceName, this.getClass()).toString()); } }
src/test/java/com/feilong/core/lang/classloaderitiltest/ClassLoaderUtilGetResourceInAllClassLoaderTest.java
add ClassLoaderUtilGetResourceInAllClassLoaderTest fix #475
src/test/java/com/feilong/core/lang/classloaderitiltest/ClassLoaderUtilGetResourceInAllClassLoaderTest.java
add ClassLoaderUtilGetResourceInAllClassLoaderTest fix #475
Java
bsd-2-clause
error: pathspec 'lava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolCompletionStatusHandler.java' did not match any file(s) known to git
ca5cf5579e1ce7f55501f3e6ec3880fc333f94a1
1
UCSFMemoryAndAging/lava,UCSFMemoryAndAging/lava,UCSFMemoryAndAging/lava
package edu.ucsf.lava.crms.protocol.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.execution.RequestContext; import edu.ucsf.lava.core.action.ActionUtils; import edu.ucsf.lava.core.dao.LavaDaoFilter; import edu.ucsf.lava.core.model.EntityBase; import edu.ucsf.lava.crms.controller.CrmsEntityComponentHandler; import edu.ucsf.lava.crms.people.model.Patient; import edu.ucsf.lava.crms.protocol.model.Protocol; import edu.ucsf.lava.crms.protocol.model.ProtocolTracking; import edu.ucsf.lava.crms.session.CrmsSessionUtils; /** * This is a "view" mode of the Protocol, with a tree that shows completion statuses. The properties * are not editable. It is intended for drilling down from a list of Protocols showing overall * Protocol completion status (currStatus), to view the statuses of individual components of the * Protocol. * * @author ctoohey * */ public class ProtocolCompletionStatusHandler extends CrmsEntityComponentHandler { public ProtocolCompletionStatusHandler() { super(); setHandledEntity("protocolCompletionStatus", edu.ucsf.lava.crms.protocol.model.Protocol.class); } public Map getBackingObjects(RequestContext context, Map components) { HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest(); String flowMode = ActionUtils.getFlowMode(context.getActiveFlow().getId()); Map backingObjects = super.getBackingObjects(context, components); // retrieve the entire patientProtocol hierarchy tree for display in patientProtocol View mode Protocol protocol = (Protocol) backingObjects.get(getDefaultObjectName()); LavaDaoFilter filter = EntityBase.newFilterInstance(getCurrentUser(request)); filter.addDaoParam(filter.daoNamedParam("protocolId", protocol.getId())); ProtocolTracking protocolTree = (ProtocolTracking) EntityBase.MANAGER.findOneByNamedQuery("protocol.protocolTree", filter); backingObjects.put("protocolTree", protocolTree); return backingObjects; } protected Object initializeNewCommandInstance(RequestContext context, Object command){ // do not init project to current project; the protocol that is selected will determine the project HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest(); Protocol protocol = (Protocol) command; Patient p = CrmsSessionUtils.getCurrentPatient(sessionManager,request); if (p != null){ protocol.setPatient(p); } return command; } }
lava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolCompletionStatusHandler.java
initial revision
lava-crms/src/edu/ucsf/lava/crms/protocol/controller/ProtocolCompletionStatusHandler.java
initial revision
Java
bsd-3-clause
46bfab5efbfa7043c52fd1f853e9185c37279250
0
mdiggory/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo
/* * DSIndexer.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.search; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; import java.util.TimeZone; import java.text.SimpleDateFormat; import java.text.ParseException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.DateTools; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.dao.ItemDAO; import org.dspace.content.dao.ItemDAOFactory; import org.dspace.uri.ObjectIdentifier; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.Email; import org.dspace.core.LogManager; import org.dspace.sort.SortOption; import org.dspace.sort.OrderFormat; /** * DSIndexer contains the methods that index Items and their metadata, * collections, communities, etc. It is meant to either be invoked from the * command line (see dspace/bin/index-all) or via the indexContent() methods * within DSpace. * * As of 1.4.2 this class has new incremental update of index functionality * and better detection of locked state thanks to Lucene 2.1 moving write.lock. * It will attempt to attain a lock on the index in the event that an update * is requested and will wait a maximum of 30 seconds (a worst case scenario) * to attain the lock before giving up and logging the failure to log4j and * to the DSpace administrator email account. * * The Administrator can choose to run DSIndexer in a cron that * repeats regularly, a failed attempt to index from the UI will be "caught" up * on in that cron. * * @author Mark Diggory * @author Graham Triggs */ public class DSIndexer { private static final Logger log = Logger.getLogger(DSIndexer.class); private static final String LAST_INDEXED_FIELD = "DSIndexer.lastIndexed"; private static final long WRITE_LOCK_TIMEOUT = 30000 /* 30 sec */; private static ItemDAO itemDAO; // Class to hold the index configuration (one instance per config line) private static class IndexConfig { String indexName; String schema; String element; String qualifier = null; String type = "text"; IndexConfig() { } IndexConfig(String indexName, String schema, String element, String qualifier, String type) { this.indexName = indexName; this.schema = schema; this.element = element; this.qualifier = qualifier; this.type = type; } } private static String index_directory = ConfigurationManager.getProperty("search.dir"); private static int maxfieldlength = -1; // TODO: Support for analyzers per language, or multiple indices /** The analyzer for this DSpace instance */ private static Analyzer analyzer = null; /** Static initialisation of index configuration */ /** Includes backwards compatible default configuration */ private static IndexConfig[] indexConfigArr = new IndexConfig[] { new IndexConfig("author", "dc", "contributor", Item.ANY, "text") , new IndexConfig("author", "dc", "creator", Item.ANY, "text"), new IndexConfig("author", "dc", "description", "statementofresponsibility", "text"), new IndexConfig("title", "dc", "title", Item.ANY, "text"), new IndexConfig("keyword", "dc", "subject", Item.ANY, "text"), new IndexConfig("abstract", "dc", "description", "abstract", "text"), new IndexConfig("abstract", "dc", "description", "tableofcontents", "text"), new IndexConfig("series", "dc", "relation", "ispartofseries", "text"), new IndexConfig("mimetype", "dc", "format", "mimetype", "text"), new IndexConfig("sponsor", "dc", "description", "sponsorship", "text"), new IndexConfig("identifier", "dc", "identifier", Item.ANY, "text") }; static { // calculate maxfieldlength if (ConfigurationManager.getProperty("search.maxfieldlength") != null) { maxfieldlength = ConfigurationManager.getIntProperty("search.maxfieldlength"); } // read in indexes from the config ArrayList<String> indexConfigList = new ArrayList<String>(); // read in search.index.1, search.index.2.... for (int i = 1; ConfigurationManager.getProperty("search.index." + i) != null; i++) { indexConfigList.add(ConfigurationManager.getProperty("search.index." + i)); } if (indexConfigList.size() > 0) { indexConfigArr = new IndexConfig[indexConfigList.size()]; for (int i = 0; i < indexConfigList.size(); i++) { indexConfigArr[i] = new IndexConfig(); String index = indexConfigList.get(i); String[] configLine = index.split(":"); indexConfigArr[i].indexName = configLine[0]; // Get the schema, element and qualifier for the index // TODO: Should check valid schema, element, qualifier? String[] parts = configLine[1].split("\\."); switch (parts.length) { case 3: indexConfigArr[i].qualifier = parts[2]; case 2: indexConfigArr[i].schema = parts[0]; indexConfigArr[i].element = parts[1]; break; default: log.warn("Malformed configuration line: search.index." + i); // FIXME: Can't proceed here, no suitable exception to throw throw new RuntimeException( "Malformed configuration line: search.index." + i); } if (configLine.length > 2) { indexConfigArr[i].type = configLine[2]; } } } /* * Increase the default write lock so that Indexing can be interupted. */ IndexWriter.setDefaultWriteLockTimeout(WRITE_LOCK_TIMEOUT); /* * Create the index directory if it doesn't already exist. */ if(!IndexReader.indexExists(index_directory)) { try { new File(index_directory).mkdirs(); openIndex(null,true).close(); } catch (IOException e) { throw new RuntimeException( "Could not create search index: " + e.getMessage(),e); } } } /** * If a persistent identifier for the "dso" already exists in the index, * and the "dso" has a lastModified timestamp that is newer than the * document in the index then it is updated, otherwise a new document is * added. * * @param context Users Context * @param dso DSpace Object (Item, Collection or Community * @throws IOException */ public static void indexContent(Context context, DSpaceObject dso) throws IOException { indexContent(context, dso, false); } /** * If a persistent identifier for the "dso" already exists in the index, * and the "dso" has a lastModified timestamp that is newer than the * document in the index then it is updated, otherwise a new document is * added. * * @param context Users Context * @param dso DSpace Object (Item, Collection or Community * @param force Force update even if not stale. * @throws IOException */ public static void indexContent(Context context, DSpaceObject dso, boolean force) throws IOException { String uri = dso.getIdentifier().getCanonicalForm(); Term t = new Term("uri", uri); // String handle = dso.getHandle(); // // if(handle == null) // { // handle = HandleManager.findHandle(context, dso); // } // // Term t = new Term("handle", handle); IndexWriter writer = null; try { switch (dso.getType()) { case Constants.ITEM : Item item = (Item)dso; if (item.isArchived() && !item.isWithdrawn()) { if (requiresIndexing(uri, ((Item)dso).getLastModified()) || force) { Document doc = buildDocument(context, (Item) dso); /* open inside stale block, after building doc * to limit the total time spent in a lock. */ writer = openIndex(context, false); writer.updateDocument(t, doc); log.info("Wrote Item: " + uri + " to Index"); } } break; case Constants.COLLECTION : writer = openIndex(context, false); writer.updateDocument(t, buildDocument(context, (Collection) dso)); log.info("Wrote Collection: " + uri + " to Index"); break; case Constants.COMMUNITY : writer = openIndex(context, false); writer.updateDocument(t, buildDocument(context, (Community) dso)); log.info("Wrote Community: " + uri + " to Index"); break; default : log.error("Only Items, Collections and Communities can be Indexed"); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { /* drop the lock */ if(writer != null) writer.close(); } } /** * unIndex removes an Item, Collection, or Community only works if the * DSpaceObject has a persistent identifier (uses a persistent identifier * for its unique ID) * * @param context * @param dso DSpace Object, can be Community, Item, or Collection * @throws IOException */ public static void unIndexContent(Context context, DSpaceObject dso) throws IOException { try { unIndexContent(context, dso.getIdentifier().getCanonicalForm()); } catch(Exception exception) { log.error(exception.getMessage(),exception); emailException(exception); } } /** * Unindex a Docment in the Lucene Index. * * @param context * @param uri * @throws IOException */ public static void unIndexContent(Context context, String uri) throws IOException { IndexWriter writer = openIndex(context, false); try { if (uri != null) { // we have a persistent identifier (our unique ID, so remove) Term t = new Term("uri", uri); writer.deleteDocuments(t); } else { log.warn("unindex of content with null uri attempted"); } } finally { writer.close(); } } /** * reIndexContent removes something from the index, then re-indexes it * * @param context context object * @param dso object to re-index */ public static void reIndexContent(Context context, DSpaceObject dso) throws IOException { try { indexContent(context, dso); } catch(Exception exception) { log.error(exception.getMessage(),exception); emailException(exception); } } /** * create full index - wiping old index * * @param c context to use */ public static void createIndex(Context c) throws IOException { itemDAO = ItemDAOFactory.getInstance(c); /* Create a new index, blowing away the old. */ openIndex(c, true).close(); /* Reindex all content preemptively. */ DSIndexer.updateIndex(c, true); } /** * Optimize the existing index. Iimportant to do regularly to reduce * filehandle usage and keep performance fast! * * @param c Users Context * @throws IOException */ public static void optimizeIndex(Context c) throws IOException { IndexWriter writer = openIndex(c, false); try { writer.optimize(); } finally { writer.close(); } } /** * When invoked as a command-line tool, creates, updates, removes * content from the whole index * * @param args * the command-line arguments, none used * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, SQLException { Context context = new Context(); context.setIgnoreAuthorization(true); String usage = "org.dspace.search.DSIndexer [-cbhouf[d <item uri>]] or nothing to update/clean an existing index."; Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; options.addOption(OptionBuilder .withArgName("item uri") .hasArg(true) .withDescription( "delete an Item, Collection or Community from index based on its uri") .create("d")); options.addOption(OptionBuilder.isRequired(false).withDescription( "optimize existing index").create("o")); options.addOption(OptionBuilder .isRequired(false) .withDescription( "clean existing index removing any documents that no longer exist in the db") .create("c")); options.addOption(OptionBuilder.isRequired(false).withDescription( "(re)build index, wiping out current one if it exists").create( "b")); options.addOption(OptionBuilder .isRequired(false) .withDescription( "if updating existing index, force each document to be reindexed even if uptodate") .create("f")); options.addOption(OptionBuilder.isRequired(false).withDescription( "print this help message").create("h")); try { line = new PosixParser().parse(options, args); } catch (Exception e) { // automatically generate the help statement formatter.printHelp(usage, e.getMessage(), options, ""); System.exit(1); } if (line.hasOption("h")) { // automatically generate the help statement formatter.printHelp(usage, options); System.exit(1); } if (line.hasOption("r")) { log.info("Removing " + line.getOptionValue("r") + " from Index"); unIndexContent(context, line.getOptionValue("r")); } else if (line.hasOption("o")) { log.info("Optimizing Index"); optimizeIndex(context); } else if (line.hasOption("c")) { log.info("Cleaning Index"); cleanIndex(context); } else if (line.hasOption("u")) { log.info("Updating Index"); updateIndex(context, line.hasOption("f")); } else if (line.hasOption("b")) { log.info("(Re)building index from scratch."); createIndex(context); } else { log.info("Updating and Cleaning Index"); cleanIndex(context); updateIndex(context, line.hasOption("f")); } log.info("Done with indexing"); } /** * Iterates over all Items, Collections and Communities. And updates * them in the index. Uses decaching to control memory footprint. * Uses indexContent and isStale ot check state of item in index. * * @param context */ public static void updateIndex(Context context) { updateIndex(context,false); } /** * Iterates over all Items, Collections and Communities. And updates * them in the index. Uses decaching to control memory footprint. * Uses indexContent and isStale ot check state of item in index. * * At first it may appear counterintuitive to have an IndexWriter/Reader * opened and closed on each DSO. But this allows the UI processes * to step in and attain a lock and write to the index even if other * processes/jvms are running a reindex. * * @param context * @param force */ public static void updateIndex(Context context, boolean force) { try { for (Item item : itemDAO.getItems()) { indexContent(context,item,force); item.decache(); } Collection[] collections = Collection.findAll(context); for (int i = 0; i < collections.length; i++) { indexContent(context,collections[i],force); context.removeCached(collections[i], collections[i].getID()); } Community[] communities = Community.findAll(context); for (int i = 0; i < communities.length; i++) { indexContent(context,communities[i],force); context.removeCached(communities[i], communities[i].getID()); } optimizeIndex(context); } catch(Exception e) { log.error(e.getMessage(), e); } } /** * Iterates over all documents in the Lucene index and verifies they * are in database, if not, they are removed. * * @param context * @throws IOException */ public static void cleanIndex(Context context) throws IOException { ObjectIdentifier oi = null; IndexReader reader = DSQuery.getIndexReader(); for(int i = 0 ; i < reader.numDocs(); i++) { if(!reader.isDeleted(i)) { Document doc = reader.document(i); String uri = doc.get("uri"); oi = ObjectIdentifier.parseCanonicalForm(uri); DSpaceObject o = oi.getObject(context); if (o == null) { log.info("Deleting: " + uri); /* Use IndexWriter to delete, its easier to manage write.lock */ DSIndexer.unIndexContent(context, uri); } else { context.removeCached(o, o.getID()); log.debug("Keeping: " + uri); } } else { log.debug("Encountered deleted doc: " + i); } } } /** * Get the Lucene analyzer to use according to current configuration (or * default). TODO: Should have multiple analyzers (and maybe indices?) for * multi-lingual DSpaces. * * @return <code>Analyzer</code> to use * @throws IllegalStateException * if the configured analyzer can't be instantiated */ static Analyzer getAnalyzer() throws IllegalStateException { if (analyzer == null) { // We need to find the analyzer class from the configuration String analyzerClassName = ConfigurationManager.getProperty("search.analyzer"); if (analyzerClassName == null) { // Use default analyzerClassName = "org.dspace.search.DSAnalyzer"; } try { Class analyzerClass = Class.forName(analyzerClassName); analyzer = (Analyzer) analyzerClass.newInstance(); } catch (Exception e) { log.fatal(LogManager.getHeader(null, "no_search_analyzer", "search.analyzer=" + analyzerClassName), e); throw new IllegalStateException(e.toString()); } } return analyzer; } //////////////////////////////////// // Private //////////////////////////////////// private static void emailException(Exception exception) { // Also email an alert, system admin may need to check for stale lock try { String recipient = ConfigurationManager .getProperty("alert.recipient"); if (recipient != null) { Email email = ConfigurationManager.getEmail("internal_error"); email.addRecipient(recipient); email.addArgument(ConfigurationManager .getProperty("dspace.url")); email.addArgument(new Date()); String stackTrace; if (exception != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); pw.flush(); stackTrace = sw.toString(); } else { stackTrace = "No exception"; } email.addArgument(stackTrace); email.send(); } } catch (Exception e) { // Not much we can do here! log.warn("Unable to send email alert", e); } } /** * Is stale checks the lastModified time stamp in the database and the index * to determine if the index is stale. * * @param uri * @param lastModified * @return * @throws IOException */ private static boolean requiresIndexing(String uri, Date lastModified) throws IOException { boolean reindexItem = false; boolean inIndex = false; IndexReader ir = DSQuery.getIndexReader(); Term t = new Term("uri", uri); TermDocs docs = ir.termDocs(t); while(docs.next()) { inIndex = true; int id = docs.doc(); Document doc = ir.document(id); Field lastIndexed = doc.getField(LAST_INDEXED_FIELD); if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) < lastModified.getTime()) { reindexItem = true; } } return reindexItem || !inIndex; } /** * prepare index, opening writer, and wiping out existing index if necessary */ private static IndexWriter openIndex(Context c, boolean wipe_existing) throws IOException { IndexWriter writer = new IndexWriter(index_directory, getAnalyzer(), wipe_existing); /* Set maximum number of terms to index if present in dspace.cfg */ if (maxfieldlength == -1) { writer.setMaxFieldLength(Integer.MAX_VALUE); } else { writer.setMaxFieldLength(maxfieldlength); } return writer; } /** * * @param c * @param myitem * @return */ private static String buildItemLocationString(Context c, Item myitem) { // build list of community ids Community[] communities = myitem.getCommunities(); // build list of collection ids Collection[] collections = myitem.getCollections(); // now put those into strings String location = ""; int i = 0; for (i = 0; i < communities.length; i++) location = location + " m" + communities[i].getID(); for (i = 0; i < collections.length; i++) location = location + " l" + collections[i].getID(); return location; } private static String buildCollectionLocationString(Context c, Collection target) { // build list of community ids Community[] communities = target.getCommunities(); // now put those into strings String location = ""; int i = 0; for (i = 0; i < communities.length; i++) location = location + " m" + communities[i].getID(); return location; } /** * Build a Lucene document for a DSpace Community. * * @param context Users Context * @param community Community to be indexed * @return * @throws IOException */ private static Document buildDocument(Context context, Community community) throws IOException { // Create Lucene Document String uri = community.getIdentifier().getCanonicalForm(); Document doc = buildDocument(Constants.COMMUNITY, community.getID(), uri, null); // and populate it String name = community.getMetadata("name"); if (name != null) { doc.add(new Field("name", name, Field.Store.NO, Field.Index.TOKENIZED)); doc.add(new Field("default", name, Field.Store.NO, Field.Index.TOKENIZED)); } return doc; } /** * Build a Lucene document for a DSpace Collection. * * @param context Users Context * @param collection Collection to be indexed * @return * @throws IOException */ private static Document buildDocument(Context context, Collection collection) throws IOException { String location_text = buildCollectionLocationString(context, collection); // Create Lucene Document String uri = collection.getIdentifier().getCanonicalForm(); Document doc = buildDocument(Constants.COLLECTION, collection.getID(), uri, location_text); // and populate it String name = collection.getMetadata("name"); if(name != null) { doc.add(new Field("name", name, Field.Store.NO, Field.Index.TOKENIZED)); doc.add(new Field("default", name, Field.Store.NO, Field.Index.TOKENIZED)); } return doc; } /** * Build a Lucene document for a DSpace Item. * * @param context Users Context * @param item The DSpace Item to be indexed * @return * @throws IOException */ private static Document buildDocument(Context context, Item item) throws IOException { // get the location string (for searching by collection & community) String location = buildItemLocationString(context, item); // FIXME: Need to check to make sure the Item has a persistent // identifier? String uri = item.getIdentifier().getCanonicalForm(); Document doc = buildDocument(Constants.ITEM, item.getID(), uri, location); log.debug("Building Item: " + uri); int j; int k = 0; if (indexConfigArr.length > 0) { ArrayList fields = new ArrayList(); ArrayList content = new ArrayList(); DCValue[] mydc; for (int i = 0; i < indexConfigArr.length; i++) { // extract metadata (ANY is wildcard from Item class) if (indexConfigArr[i].qualifier!= null && indexConfigArr[i].qualifier.equals("*")) { mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, Item.ANY, Item.ANY); } else { mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, indexConfigArr[i].qualifier, Item.ANY); } for (j = 0; j < mydc.length; j++) { if (!StringUtils.isEmpty(mydc[j].value)) { if ("timestamp".equalsIgnoreCase(indexConfigArr[i].type)) { Date d = toDate(mydc[j].value); if (d != null) { doc.add( new Field(indexConfigArr[i].indexName, DateTools.dateToString(d, DateTools.Resolution.SECOND), Field.Store.NO, Field.Index.TOKENIZED)); doc.add( new Field(indexConfigArr[i].indexName + ".year", DateTools.dateToString(d, DateTools.Resolution.YEAR), Field.Store.NO, Field.Index.TOKENIZED)); } } else if ("date".equalsIgnoreCase(indexConfigArr[i].type)) { Date d = toDate(mydc[j].value); if (d != null) { doc.add( new Field(indexConfigArr[i].indexName, DateTools.dateToString(d, DateTools.Resolution.DAY), Field.Store.NO, Field.Index.TOKENIZED)); doc.add( new Field(indexConfigArr[i].indexName + ".year", DateTools.dateToString(d, DateTools.Resolution.YEAR), Field.Store.NO, Field.Index.TOKENIZED)); } } else { // TODO: use a delegate to allow custom 'types' to be used to reformat the field doc.add( new Field(indexConfigArr[i].indexName, mydc[j].value, Field.Store.NO, Field.Index.TOKENIZED)); } doc.add( new Field("default", mydc[j].value, Field.Store.NO, Field.Index.TOKENIZED)); } } } } log.debug(" Added Metadata"); try { // Now get the configured sort options, and add those as untokenized fields // Note that we will use the sort order delegates to normalise the values written for (SortOption so : SortOption.getSortOptions()) { String[] somd = so.getMdBits(); DCValue[] dcv = item.getMetadata(somd[0], somd[1], somd[2], Item.ANY); if (dcv.length > 0) { String value = OrderFormat.makeSortString(dcv[0].value, dcv[0].language, so.getType()); doc.add( new Field("sort_" + so.getName(), value, Field.Store.NO, Field.Index.UN_TOKENIZED) ); } } } catch (Exception e) { log.error(e.getMessage(),e); } log.debug(" Added Sorting"); try { // now get full text of any bitstreams in the TEXT bundle // trundle through the bundles Bundle[] myBundles = item.getBundles(); for (int i = 0; i < myBundles.length; i++) { if ((myBundles[i].getName() != null) && myBundles[i].getName().equals("TEXT")) { // a-ha! grab the text out of the bitstreams Bitstream[] myBitstreams = myBundles[i].getBitstreams(); for (j = 0; j < myBitstreams.length; j++) { try { InputStreamReader is = new InputStreamReader( myBitstreams[j].retrieve()); // get input // Add each InputStream to the Indexed Document (Acts like an Append) doc.add(new Field("default", is)); log.debug(" Added BitStream: " + myBitstreams[j].getStoreNumber() + " " + myBitstreams[j].getSequenceID() + " " + myBitstreams[j].getName()); } catch (Exception e) { // this will never happen, but compiler is now happy. log.error(e.getMessage(),e); } } } } } catch(Exception e) { log.error(e.getMessage(),e); } return doc; } /** * Create Lucene document with all the shared fields initialized. * * @param type Type of DSpace Object * @param id * @param uri * @param location * @return */ private static Document buildDocument(int type, int id, String uri, String location) { Document doc = new Document(); // want to be able to check when last updated // (not tokenized, but it is indexed) doc.add(new Field(LAST_INDEXED_FIELD, Long.toString(System.currentTimeMillis()), Field.Store.YES, Field.Index.UN_TOKENIZED)); // KEPT FOR BACKWARDS COMPATIBILITY // do location, type, uri first doc.add(new Field("type", Integer.toString(type), Field.Store.YES, Field.Index.NO)); // New fields to weaken the dependence on handles, and allow for faster list display doc.add(new Field("search.resourcetype", Integer.toString(type), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field("search.resourceid", Integer.toString(id), Field.Store.YES, Field.Index.NO)); // want to be able to search for uri, so use keyword // (not tokenized, but it is indexed) if (uri != null) { // FIXME: Figure out wtf is going on here. // ??? not sure what the "handletext" field is but it was there in writeItemIndex ??? doc.add(new Field("handletext", uri, Field.Store.YES, Field.Index.TOKENIZED)); // want to be able to search for uri, so use keyword // (not tokenized, but it is indexed) doc.add(new Field("uri", uri, Field.Store.YES, Field.Index.UN_TOKENIZED)); // add to full text index doc.add(new Field("default", uri, Field.Store.NO, Field.Index.TOKENIZED)); } if(location != null) { doc.add(new Field("location", location, Field.Store.NO, Field.Index.TOKENIZED)); doc.add(new Field("default", location, Field.Store.NO, Field.Index.TOKENIZED)); } return doc; } /** * Helper function to retrieve a date using a best guess of the potential date encodings on a field * * @param t * @return */ private static Date toDate(String t) { SimpleDateFormat[] dfArr; // Choose the likely date formats based on string length switch (t.length()) { case 4: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy") }; break; case 6: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMM") }; break; case 7: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM") }; break; case 8: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMMdd"), new SimpleDateFormat("yyyy MMM") }; break; case 10: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd") }; break; case 11: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy MMM dd") }; break; case 20: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") }; break; default: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") }; break; } for (SimpleDateFormat df : dfArr) { try { // Parse the date df.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); return df.parse(t); } catch (ParseException pe) { log.error("Unable to parse date format", pe); } } return null; } }
dspace-api/src/main/java/org/dspace/search/DSIndexer.java
/* * DSIndexer.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.search; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; import java.util.TimeZone; import java.text.SimpleDateFormat; import java.text.ParseException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.DateTools; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.dao.ItemDAO; import org.dspace.content.dao.ItemDAOFactory; import org.dspace.uri.ObjectIdentifier; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.Email; import org.dspace.core.LogManager; import org.dspace.sort.SortOption; import org.dspace.sort.OrderFormat; /** * DSIndexer contains the methods that index Items and their metadata, * collections, communities, etc. It is meant to either be invoked from the * command line (see dspace/bin/index-all) or via the indexContent() methods * within DSpace. * * As of 1.4.2 this class has new incremental update of index functionality * and better detection of locked state thanks to Lucene 2.1 moving write.lock. * It will attempt to attain a lock on the index in the event that an update * is requested and will wait a maximum of 30 seconds (a worst case scenario) * to attain the lock before giving up and logging the failure to log4j and * to the DSpace administrator email account. * * The Administrator can choose to run DSIndexer in a cron that * repeats regularly, a failed attempt to index from the UI will be "caught" up * on in that cron. * * @author Mark Diggory * @author Graham Triggs */ public class DSIndexer { private static final Logger log = Logger.getLogger(DSIndexer.class); private static final String LAST_INDEXED_FIELD = "DSIndexer.lastIndexed"; private static final long WRITE_LOCK_TIMEOUT = 30000 /* 30 sec */; private static ItemDAO itemDAO; // Class to hold the index configuration (one instance per config line) private static class IndexConfig { String indexName; String schema; String element; String qualifier = null; String type = "text"; IndexConfig() { } IndexConfig(String indexName, String schema, String element, String qualifier, String type) { this.indexName = indexName; this.schema = schema; this.element = element; this.qualifier = qualifier; this.type = type; } } private static String index_directory = ConfigurationManager.getProperty("search.dir"); private static int maxfieldlength = -1; // TODO: Support for analyzers per language, or multiple indices /** The analyzer for this DSpace instance */ private static Analyzer analyzer = null; /** Static initialisation of index configuration */ /** Includes backwards compatible default configuration */ private static IndexConfig[] indexConfigArr = new IndexConfig[] { new IndexConfig("author", "dc", "contributor", Item.ANY, "text") , new IndexConfig("author", "dc", "creator", Item.ANY, "text"), new IndexConfig("author", "dc", "description", "statementofresponsibility", "text"), new IndexConfig("title", "dc", "title", Item.ANY, "text"), new IndexConfig("keyword", "dc", "subject", Item.ANY, "text"), new IndexConfig("abstract", "dc", "description", "abstract", "text"), new IndexConfig("abstract", "dc", "description", "tableofcontents", "text"), new IndexConfig("series", "dc", "relation", "ispartofseries", "text"), new IndexConfig("mimetype", "dc", "format", "mimetype", "text"), new IndexConfig("sponsor", "dc", "description", "sponsorship", "text"), new IndexConfig("identifier", "dc", "identifier", Item.ANY, "text") }; static { // calculate maxfieldlength if (ConfigurationManager.getProperty("search.maxfieldlength") != null) { maxfieldlength = ConfigurationManager.getIntProperty("search.maxfieldlength"); } // read in indexes from the config ArrayList<String> indexConfigList = new ArrayList<String>(); // read in search.index.1, search.index.2.... for (int i = 1; ConfigurationManager.getProperty("search.index." + i) != null; i++) { indexConfigList.add(ConfigurationManager.getProperty("search.index." + i)); } if (indexConfigList.size() > 0) { indexConfigArr = new IndexConfig[indexConfigList.size()]; for (int i = 0; i < indexConfigList.size(); i++) { indexConfigArr[i] = new IndexConfig(); String index = indexConfigList.get(i); String[] configLine = index.split(":"); indexConfigArr[i].indexName = configLine[0]; // Get the schema, element and qualifier for the index // TODO: Should check valid schema, element, qualifier? String[] parts = configLine[1].split("\\."); switch (parts.length) { case 3: indexConfigArr[i].qualifier = parts[2]; case 2: indexConfigArr[i].schema = parts[0]; indexConfigArr[i].element = parts[1]; break; default: log.warn("Malformed configuration line: search.index." + i); // FIXME: Can't proceed here, no suitable exception to throw throw new RuntimeException( "Malformed configuration line: search.index." + i); } if (configLine.length > 2) { indexConfigArr[i].type = configLine[2]; } } } /* * Increase the default write lock so that Indexing can be interupted. */ IndexWriter.setDefaultWriteLockTimeout(WRITE_LOCK_TIMEOUT); /* * Create the index directory if it doesn't already exist. */ if(!IndexReader.indexExists(index_directory)) { try { new File(index_directory).mkdirs(); openIndex(null,true).close(); } catch (IOException e) { throw new RuntimeException( "Could not create search index: " + e.getMessage(),e); } } } /** * If a persistent identifier for the "dso" already exists in the index, * and the "dso" has a lastModified timestamp that is newer than the * document in the index then it is updated, otherwise a new document is * added. * * @param context Users Context * @param dso DSpace Object (Item, Collection or Community * @throws IOException */ public static void indexContent(Context context, DSpaceObject dso) throws IOException { indexContent(context, dso, false); } /** * If a persistent identifier for the "dso" already exists in the index, * and the "dso" has a lastModified timestamp that is newer than the * document in the index then it is updated, otherwise a new document is * added. * * @param context Users Context * @param dso DSpace Object (Item, Collection or Community * @param force Force update even if not stale. * @throws IOException */ public static void indexContent(Context context, DSpaceObject dso, boolean force) throws IOException { String uri = dso.getIdentifier().getCanonicalForm(); Term t = new Term("uri", uri); // String handle = dso.getHandle(); // // if(handle == null) // { // handle = HandleManager.findHandle(context, dso); // } // // Term t = new Term("handle", handle); IndexWriter writer = null; try { switch (dso.getType()) { case Constants.ITEM : Item item = (Item)dso; if (item.isArchived() && !item.isWithdrawn()) { if (requiresIndexing(uri, ((Item)dso).getLastModified()) || force) { Document doc = buildDocument(context, (Item) dso); /* open inside stale block, after building doc * to limit the total time spent in a lock. */ writer = openIndex(context, false); writer.updateDocument(t, doc); log.info("Wrote Item: " + uri + " to Index"); } } break; case Constants.COLLECTION : writer = openIndex(context, false); writer.updateDocument(t, buildDocument(context, (Collection) dso)); log.info("Wrote Collection: " + uri + " to Index"); break; case Constants.COMMUNITY : writer = openIndex(context, false); writer.updateDocument(t, buildDocument(context, (Community) dso)); log.info("Wrote Community: " + uri + " to Index"); break; default : log.error("Only Items, Collections and Communities can be Indexed"); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { /* drop the lock */ if(writer != null) writer.close(); } } /** * unIndex removes an Item, Collection, or Community only works if the * DSpaceObject has a persistent identifier (uses a persistent identifier * for its unique ID) * * @param context * @param dso DSpace Object, can be Community, Item, or Collection * @throws IOException */ public static void unIndexContent(Context context, DSpaceObject dso) throws IOException { try { unIndexContent(context, dso.getIdentifier().getCanonicalForm()); } catch(Exception exception) { log.error(exception.getMessage(),exception); emailException(exception); } } /** * Unindex a Docment in the Lucene Index. * * @param context * @param uri * @throws IOException */ public static void unIndexContent(Context context, String uri) throws IOException { IndexWriter writer = openIndex(context, false); try { if (uri != null) { // we have a persistent identifier (our unique ID, so remove) Term t = new Term("uri", uri); writer.deleteDocuments(t); } else { log.warn("unindex of content with null uri attempted"); } } finally { writer.close(); } } /** * reIndexContent removes something from the index, then re-indexes it * * @param context context object * @param dso object to re-index */ public static void reIndexContent(Context context, DSpaceObject dso) throws IOException { try { indexContent(context, dso); } catch(Exception exception) { log.error(exception.getMessage(),exception); emailException(exception); } } /** * create full index - wiping old index * * @param c context to use */ public static void createIndex(Context c) throws IOException { itemDAO = ItemDAOFactory.getInstance(c); /* Create a new index, blowing away the old. */ openIndex(c, true).close(); /* Reindex all content preemptively. */ DSIndexer.updateIndex(c, true); } /** * Optimize the existing index. Iimportant to do regularly to reduce * filehandle usage and keep performance fast! * * @param c Users Context * @throws IOException */ public static void optimizeIndex(Context c) throws IOException { IndexWriter writer = openIndex(c, false); try { writer.optimize(); } finally { writer.close(); } } /** * When invoked as a command-line tool, creates, updates, removes * content from the whole index * * @param args * the command-line arguments, none used * @throws IOException * @throws SQLException */ public static void main(String[] args) throws IOException, SQLException { Context context = new Context(); context.setIgnoreAuthorization(true); String usage = "org.dspace.search.DSIndexer [-cbhouf[d <item uri>]] or nothing to update/clean an existing index."; Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; options.addOption(OptionBuilder .withArgName("item uri") .hasArg(true) .withDescription( "delete an Item, Collection or Community from index based on its uri") .create("d")); options.addOption(OptionBuilder.isRequired(false).withDescription( "optimize existing index").create("o")); options.addOption(OptionBuilder .isRequired(false) .withDescription( "clean existing index removing any documents that no longer exist in the db") .create("c")); options.addOption(OptionBuilder.isRequired(false).withDescription( "(re)build index, wiping out current one if it exists").create( "b")); options.addOption(OptionBuilder .isRequired(false) .withDescription( "if updating existing index, force each document to be reindexed even if uptodate") .create("f")); options.addOption(OptionBuilder.isRequired(false).withDescription( "print this help message").create("h")); try { line = new PosixParser().parse(options, args); } catch (Exception e) { // automatically generate the help statement formatter.printHelp(usage, e.getMessage(), options, ""); System.exit(1); } if (line.hasOption("h")) { // automatically generate the help statement formatter.printHelp(usage, options); System.exit(1); } if (line.hasOption("r")) { log.info("Removing " + line.getOptionValue("r") + " from Index"); unIndexContent(context, line.getOptionValue("r")); } else if (line.hasOption("o")) { log.info("Optimizing Index"); optimizeIndex(context); } else if (line.hasOption("c")) { log.info("Cleaning Index"); cleanIndex(context); } else if (line.hasOption("u")) { log.info("Updating Index"); updateIndex(context, line.hasOption("f")); } else if (line.hasOption("b")) { log.info("(Re)building index from scratch."); createIndex(context); } else { log.info("Updating and Cleaning Index"); cleanIndex(context); updateIndex(context, line.hasOption("f")); } log.info("Done with indexing"); } /** * Iterates over all Items, Collections and Communities. And updates * them in the index. Uses decaching to control memory footprint. * Uses indexContent and isStale ot check state of item in index. * * @param context */ public static void updateIndex(Context context) { updateIndex(context,false); } /** * Iterates over all Items, Collections and Communities. And updates * them in the index. Uses decaching to control memory footprint. * Uses indexContent and isStale ot check state of item in index. * * At first it may appear counterintuitive to have an IndexWriter/Reader * opened and closed on each DSO. But this allows the UI processes * to step in and attain a lock and write to the index even if other * processes/jvms are running a reindex. * * @param context * @param force */ public static void updateIndex(Context context, boolean force) { try { for (Item item : itemDAO.getItems()) { indexContent(context,item,force); item.decache(); } Collection[] collections = Collection.findAll(context); for (int i = 0; i < collections.length; i++) { indexContent(context,collections[i],force); context.removeCached(collections[i], collections[i].getID()); } Community[] communities = Community.findAll(context); for (int i = 0; i < communities.length; i++) { indexContent(context,communities[i],force); context.removeCached(communities[i], communities[i].getID()); } optimizeIndex(context); } catch(Exception e) { log.error(e.getMessage(), e); } } /** * Iterates over all documents in the Lucene index and verifies they * are in database, if not, they are removed. * * @param context * @throws IOException */ public static void cleanIndex(Context context) throws IOException { ObjectIdentifier oi = null; IndexReader reader = DSQuery.getIndexReader(); for(int i = 0 ; i < reader.numDocs(); i++) { if(!reader.isDeleted(i)) { Document doc = reader.document(i); String uri = doc.get("uri"); oi = ObjectIdentifier.parseCanonicalForm(uri); DSpaceObject o = oi.getObject(context); if (o == null) { log.info("Deleting: " + uri); /* Use IndexWriter to delete, its easier to manage write.lock */ DSIndexer.unIndexContent(context, uri); } else { context.removeCached(o, o.getID()); log.debug("Keeping: " + uri); } } else { log.debug("Encountered deleted doc: " + i); } } } /** * Get the Lucene analyzer to use according to current configuration (or * default). TODO: Should have multiple analyzers (and maybe indices?) for * multi-lingual DSpaces. * * @return <code>Analyzer</code> to use * @throws IllegalStateException * if the configured analyzer can't be instantiated */ static Analyzer getAnalyzer() throws IllegalStateException { if (analyzer == null) { // We need to find the analyzer class from the configuration String analyzerClassName = ConfigurationManager.getProperty("search.analyzer"); if (analyzerClassName == null) { // Use default analyzerClassName = "org.dspace.search.DSAnalyzer"; } try { Class analyzerClass = Class.forName(analyzerClassName); analyzer = (Analyzer) analyzerClass.newInstance(); } catch (Exception e) { log.fatal(LogManager.getHeader(null, "no_search_analyzer", "search.analyzer=" + analyzerClassName), e); throw new IllegalStateException(e.toString()); } } return analyzer; } //////////////////////////////////// // Private //////////////////////////////////// private static void emailException(Exception exception) { // Also email an alert, system admin may need to check for stale lock try { String recipient = ConfigurationManager .getProperty("alert.recipient"); if (recipient != null) { Email email = ConfigurationManager.getEmail("internal_error"); email.addRecipient(recipient); email.addArgument(ConfigurationManager .getProperty("dspace.url")); email.addArgument(new Date()); String stackTrace; if (exception != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); pw.flush(); stackTrace = sw.toString(); } else { stackTrace = "No exception"; } email.addArgument(stackTrace); email.send(); } } catch (Exception e) { // Not much we can do here! log.warn("Unable to send email alert", e); } } /** * Is stale checks the lastModified time stamp in the database and the index * to determine if the index is stale. * * @param uri * @param lastModified * @return * @throws IOException */ private static boolean requiresIndexing(String uri, Date lastModified) throws IOException { boolean reindexItem = false; boolean inIndex = false; IndexReader ir = DSQuery.getIndexReader(); Term t = new Term("uri", uri); TermDocs docs = ir.termDocs(t); while(docs.next()) { inIndex = true; int id = docs.doc(); Document doc = ir.document(id); Field lastIndexed = doc.getField(LAST_INDEXED_FIELD); if (lastIndexed == null || Long.parseLong(lastIndexed.stringValue()) < lastModified.getTime()) { reindexItem = true; } } return reindexItem || !inIndex; } /** * prepare index, opening writer, and wiping out existing index if necessary */ private static IndexWriter openIndex(Context c, boolean wipe_existing) throws IOException { IndexWriter writer = new IndexWriter(index_directory, getAnalyzer(), wipe_existing); /* Set maximum number of terms to index if present in dspace.cfg */ if (maxfieldlength == -1) { writer.setMaxFieldLength(Integer.MAX_VALUE); } else { writer.setMaxFieldLength(maxfieldlength); } return writer; } /** * * @param c * @param myitem * @return */ private static String buildItemLocationString(Context c, Item myitem) { // build list of community ids Community[] communities = myitem.getCommunities(); // build list of collection ids Collection[] collections = myitem.getCollections(); // now put those into strings String location = ""; int i = 0; for (i = 0; i < communities.length; i++) location = location + " m" + communities[i].getID(); for (i = 0; i < collections.length; i++) location = location + " l" + collections[i].getID(); return location; } private static String buildCollectionLocationString(Context c, Collection target) { // build list of community ids Community[] communities = target.getCommunities(); // now put those into strings String location = ""; int i = 0; for (i = 0; i < communities.length; i++) location = location + " m" + communities[i].getID(); return location; } /** * Build a Lucene document for a DSpace Community. * * @param context Users Context * @param community Community to be indexed * @return * @throws IOException */ private static Document buildDocument(Context context, Community community) throws IOException { // Create Lucene Document String uri = community.getIdentifier().getCanonicalForm(); Document doc = buildDocument(Constants.COMMUNITY, community.getID(), uri, null); // and populate it String name = community.getMetadata("name"); if (name != null) { doc.add(new Field("name", name, Field.Store.NO, Field.Index.TOKENIZED)); doc.add(new Field("default", name, Field.Store.NO, Field.Index.TOKENIZED)); } return doc; } /** * Build a Lucene document for a DSpace Collection. * * @param context Users Context * @param collection Collection to be indexed * @return * @throws IOException */ private static Document buildDocument(Context context, Collection collection) throws IOException { String location_text = buildCollectionLocationString(context, collection); // Create Lucene Document String uri = collection.getIdentifier().getCanonicalForm(); Document doc = buildDocument(Constants.COLLECTION, collection.getID(), uri, location_text); // and populate it String name = collection.getMetadata("name"); if(name != null) { doc.add(new Field("name", name, Field.Store.NO, Field.Index.TOKENIZED)); doc.add(new Field("default", name, Field.Store.NO, Field.Index.TOKENIZED)); } return doc; } /** * Build a Lucene document for a DSpace Item. * * @param context Users Context * @param item The DSpace Item to be indexed * @return * @throws IOException */ private static Document buildDocument(Context context, Item item) throws IOException { // get the location string (for searching by collection & community) String location = buildItemLocationString(context, item); // FIXME: Need to check to make sure the Item has a persistent // identifier? String uri = item.getIdentifier().getCanonicalForm(); Document doc = buildDocument(Constants.ITEM, item.getID(), uri, location); log.debug("Building Item: " + uri); int j; int k = 0; if (indexConfigArr.length > 0) { ArrayList fields = new ArrayList(); ArrayList content = new ArrayList(); DCValue[] mydc; for (int i = 0; i < indexConfigArr.length; i++) { // extract metadata (ANY is wildcard from Item class) if (indexConfigArr[i].qualifier!= null && indexConfigArr[i].qualifier.equals("*")) { mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, Item.ANY, Item.ANY); } else { mydc = item.getMetadata(indexConfigArr[i].schema, indexConfigArr[i].element, indexConfigArr[i].qualifier, Item.ANY); } for (j = 0; j < mydc.length; j++) { if (!StringUtils.isEmpty(mydc[j].value)) { if ("timestamp".equalsIgnoreCase(indexConfigArr[i].type)) { Date d = toDate(mydc[j].value); if (d != null) { doc.add( new Field(indexConfigArr[i].indexName, DateTools.dateToString(d, DateTools.Resolution.SECOND), Field.Store.NO, Field.Index.TOKENIZED)); } } else if ("date".equalsIgnoreCase(indexConfigArr[i].type)) { Date d = toDate(mydc[j].value); if (d != null) { doc.add( new Field(indexConfigArr[i].indexName, DateTools.dateToString(d, DateTools.Resolution.DAY), Field.Store.NO, Field.Index.TOKENIZED)); } } else { // TODO: use a delegate to allow custom 'types' to be used to reformat the field doc.add( new Field(indexConfigArr[i].indexName, mydc[j].value, Field.Store.NO, Field.Index.TOKENIZED)); } doc.add( new Field("default", mydc[j].value, Field.Store.NO, Field.Index.TOKENIZED)); } } } } log.debug(" Added Metadata"); try { // Now get the configured sort options, and add those as untokenized fields // Note that we will use the sort order delegates to normalise the values written for (SortOption so : SortOption.getSortOptions()) { String[] somd = so.getMdBits(); DCValue[] dcv = item.getMetadata(somd[0], somd[1], somd[2], Item.ANY); if (dcv.length > 0) { String value = OrderFormat.makeSortString(dcv[0].value, dcv[0].language, so.getType()); doc.add( new Field("sort_" + so.getName(), value, Field.Store.NO, Field.Index.UN_TOKENIZED) ); } } } catch (Exception e) { log.error(e.getMessage(),e); } log.debug(" Added Sorting"); try { // now get full text of any bitstreams in the TEXT bundle // trundle through the bundles Bundle[] myBundles = item.getBundles(); for (int i = 0; i < myBundles.length; i++) { if ((myBundles[i].getName() != null) && myBundles[i].getName().equals("TEXT")) { // a-ha! grab the text out of the bitstreams Bitstream[] myBitstreams = myBundles[i].getBitstreams(); for (j = 0; j < myBitstreams.length; j++) { try { InputStreamReader is = new InputStreamReader( myBitstreams[j].retrieve()); // get input // Add each InputStream to the Indexed Document (Acts like an Append) doc.add(new Field("default", is)); log.debug(" Added BitStream: " + myBitstreams[j].getStoreNumber() + " " + myBitstreams[j].getSequenceID() + " " + myBitstreams[j].getName()); } catch (Exception e) { // this will never happen, but compiler is now happy. log.error(e.getMessage(),e); } } } } } catch(Exception e) { log.error(e.getMessage(),e); } return doc; } /** * Create Lucene document with all the shared fields initialized. * * @param type Type of DSpace Object * @param id * @param uri * @param location * @return */ private static Document buildDocument(int type, int id, String uri, String location) { Document doc = new Document(); // want to be able to check when last updated // (not tokenized, but it is indexed) doc.add(new Field(LAST_INDEXED_FIELD, Long.toString(System.currentTimeMillis()), Field.Store.YES, Field.Index.UN_TOKENIZED)); // KEPT FOR BACKWARDS COMPATIBILITY // do location, type, uri first doc.add(new Field("type", Integer.toString(type), Field.Store.YES, Field.Index.NO)); // New fields to weaken the dependence on handles, and allow for faster list display doc.add(new Field("search.resourcetype", Integer.toString(type), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add(new Field("search.resourceid", Integer.toString(id), Field.Store.YES, Field.Index.NO)); // want to be able to search for uri, so use keyword // (not tokenized, but it is indexed) if (uri != null) { // FIXME: Figure out wtf is going on here. // ??? not sure what the "handletext" field is but it was there in writeItemIndex ??? doc.add(new Field("handletext", uri, Field.Store.YES, Field.Index.TOKENIZED)); // want to be able to search for uri, so use keyword // (not tokenized, but it is indexed) doc.add(new Field("uri", uri, Field.Store.YES, Field.Index.UN_TOKENIZED)); // add to full text index doc.add(new Field("default", uri, Field.Store.NO, Field.Index.TOKENIZED)); } if(location != null) { doc.add(new Field("location", location, Field.Store.NO, Field.Index.TOKENIZED)); doc.add(new Field("default", location, Field.Store.NO, Field.Index.TOKENIZED)); } return doc; } /** * Helper function to retrieve a date using a best guess of the potential date encodings on a field * * @param t * @return */ private static Date toDate(String t) { SimpleDateFormat[] dfArr; // Choose the likely date formats based on string length switch (t.length()) { case 4: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy") }; break; case 6: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMM") }; break; case 7: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM") }; break; case 8: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMMdd"), new SimpleDateFormat("yyyy MMM") }; break; case 10: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd") }; break; case 11: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy MMM dd") }; break; case 20: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") }; break; default: dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") }; break; } for (SimpleDateFormat df : dfArr) { try { // Parse the date df.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); return df.parse(t); } catch (ParseException pe) { log.error("Unable to parse date format", pe); } } return null; } }
Added distinct year indexing for dates git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@2550 9c30dcfa-912a-0410-8fc2-9e0234be79fd
dspace-api/src/main/java/org/dspace/search/DSIndexer.java
Added distinct year indexing for dates
Java
bsd-3-clause
16b4494d684de458fa750d20a4c92f0991491c67
0
Lucky-Dhakad/semanticvectors,sabitaacharya/semanticvectors,anhth12/semanticvectors,anhth12/semanticvectors,sabitaacharya/semanticvectors,sabitaacharya/semanticvectors,anhth12/semanticvectors,Lucky-Dhakad/semanticvectors,Lucky-Dhakad/semanticvectors,sabitaacharya/semanticvectors,anhth12/semanticvectors,Lucky-Dhakad/semanticvectors
/** Copyright (c) 2007, University of Pittsburgh All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package pitt.search.semanticvectors; import java.io.IOException; import java.util.Arrays; /** * Command line utility for creating semantic vector indexes. */ public class BuildIndex { /* These can be modified with command line arguments */ static int seedLength = 20; static int minFreq = 10; static int nonAlphabet = 0; static int trainingCycles = 1; static boolean docsIncremental = false; /** * Prints the following usage message: * <code> * <br> BuildIndex class in package pitt.search.semanticvectors * <br> Usage: java pitt.search.semanticvectors.BuildIndex PATH_TO_LUCENE_INDEX * <br> BuildIndex creates termvectors and docvectors files in local directory. * <br> Other parameters that can be changed include vector length, * <br> (number of dimensions), seed length (number of non-zero * <br> entries in basic vectors), minimum term frequency, * <br> and number of iterative training cycles. * <br> To change these use the following command line arguments: * <br> -dimension [number of dimensions] * <br> -seedlength [seed length] * <br> -minfrequency [minimum term frequency] * <br> -maxnonalphabetchars [number non-alphabet characters (-1 for any number)] * <br> -trainingcycles [training cycles] * <br> -docindexing [incremental|inmemory] Switch between building doc vectors incrementally" * <br> (requires positional index) or all in memory (default case). * </code> */ public static void usage() { String usageMessage = "\nBuildIndex class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.BuildIndex PATH_TO_LUCENE_INDEX" + "\nBuildIndex creates termvectors and docvectors files in local directory." + "\nOther parameters that can be changed include vector length," + "\n (number of dimensions), seed length (number of non-zero" + "\n entries in basic vectors), minimum term frequency," + "\n and number of iterative training cycles." + "\nTo change these use the command line arguments " + "\n -dimension [number of dimensions]" + "\n -seedlength [seed length]" + "\n -minfrequency [minimum term frequency]" + "\n -maxnonalphabetchars [number non-alphabet characters (-1 for any number)]" + "\n -trainingcycles [training cycles]" + "\n -docindexing [incremental|inmemory|none] Switch between building doc vectors incrementally" + "\n (requires positional index), all in memory (default case), or not at all"; System.out.println(usageMessage); } /** * Builds term vector and document vector stores from a Lucene index. * @param args * @see BuildIndex#usage */ public static void main (String[] args) throws IllegalArgumentException { try { args = Flags.parseCommandLineFlags(args); } catch (IllegalArgumentException e) { usage(); throw e; } // Only one argument should remain, the path to the Lucene index. if (args.length != 1) { usage(); throw (new IllegalArgumentException("After parsing command line flags, there were " + args.length + " arguments, instead of the expected 1.")); } String luceneIndex = args[0]; System.err.println("Seedlength = " + Flags.seedlength); System.err.println("Dimension = " + Flags.dimension); System.err.println("Minimum frequency = " + Flags.minfrequency); System.err.println("Maximum frequency = " + Flags.maxfrequency); System.err.println("Number non-alphabet characters = " + Flags.maxnonalphabetchars); String termFile = "termvectors.bin"; String docFile = "docvectors.bin"; VectorStoreRAM initialdocvectors = null; System.err.println("Contents fields are: " + Arrays.toString(Flags.contentsfields)); try{ TermVectorsFromLucene vecStore; if (Flags.initialtermvectors.length() > 0) { // If Flags.initialtermvectors="random" create elemental (random index) // term vectors. Recommended to iterate at least once (i.e. -trainingcycles = 2) to // obtain semantic term vectors. // Otherwise attempt to load pre-existing semantic term vectors. System.err.println("Creating term vectors ..."); vecStore = new TermVectorsFromLucene(luceneIndex, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, Flags.initialtermvectors, Flags.contentsfields); } else { System.err.println("Creating elemental document vectors ..."); vecStore = new TermVectorsFromLucene(luceneIndex, Flags.dimension, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, null, Flags.contentsfields); } // Create doc vectors and write vectors to disk. VectorStoreWriter vecWriter = new VectorStoreWriter(); if (Flags.docindexing.equals("incremental")) { System.err.println("Writing term vectors to " + termFile); vecWriter.WriteVectors(termFile, vecStore); IncrementalDocVectors idocVectors = new IncrementalDocVectors( vecStore, luceneIndex, Flags.contentsfields, "incremental_"+docFile); IncrementalTermVectors itermVectors = null; for (int i = 1; i < Flags.trainingcycles; ++i) { itermVectors = new IncrementalTermVectors(luceneIndex, Flags.dimension, Flags.contentsfields, "incremental_"+docFile); new VectorStoreWriter().WriteVectors( "incremental_termvectors"+Flags.trainingcycles+".bin", itermVectors); // Write over previous cycle's docvectors until final // iteration, then rename according to number cycles if (i == Flags.trainingcycles-1) docFile = "docvectors"+Flags.trainingcycles+".bin"; idocVectors = new IncrementalDocVectors( itermVectors, luceneIndex, Flags.contentsfields, "incremental_"+docFile); } } else if (Flags.docindexing.equals("inmemory")) { DocVectors docVectors = new DocVectors(vecStore); for (int i = 1; i < Flags.trainingcycles; ++i) { System.err.println("\nRetraining with learned document vectors ..."); vecStore = new TermVectorsFromLucene(luceneIndex, Flags.dimension, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, docVectors, Flags.contentsfields); docVectors = new DocVectors(vecStore); } // At end of training, convert document vectors from ID keys to pathname keys. VectorStore writeableDocVectors = docVectors.makeWriteableVectorStore(); if (Flags.trainingcycles > 1) { termFile = "termvectors" + Flags.trainingcycles + ".bin"; docFile = "docvectors" + Flags.trainingcycles + ".bin"; } System.err.println("Writing term vectors to " + termFile); vecWriter.WriteVectors(termFile, vecStore); System.err.println("Writing doc vectors to " + docFile); vecWriter.WriteVectors(docFile, writeableDocVectors); } else { // Write term vectors to disk even if there are no docvectors to output. System.err.println("Writing term vectors to " + termFile); vecWriter.WriteVectors(termFile, vecStore); } } catch (IOException e) { e.printStackTrace(); } } }
src/pitt/search/semanticvectors/BuildIndex.java
/** Copyright (c) 2007, University of Pittsburgh All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package pitt.search.semanticvectors; import java.io.IOException; import java.util.Arrays; /** * Command line utility for creating semantic vector indexes. */ public class BuildIndex { /* These can be modified with command line arguments */ static int seedLength = 20; static int minFreq = 10; static int nonAlphabet = 0; static int trainingCycles = 1; static boolean docsIncremental = false; /** * Prints the following usage message: * <code> * <br> BuildIndex class in package pitt.search.semanticvectors * <br> Usage: java pitt.search.semanticvectors.BuildIndex PATH_TO_LUCENE_INDEX * <br> BuildIndex creates termvectors and docvectors files in local directory. * <br> Other parameters that can be changed include vector length, * <br> (number of dimensions), seed length (number of non-zero * <br> entries in basic vectors), minimum term frequency, * <br> and number of iterative training cycles. * <br> To change these use the following command line arguments: * <br> -dimension [number of dimensions] * <br> -seedlength [seed length] * <br> -minfrequency [minimum term frequency] * <br> -maxnonalphabetchars [number non-alphabet characters (-1 for any number)] * <br> -trainingcycles [training cycles] * <br> -docindexing [incremental|inmemory] Switch between building doc vectors incrementally" * <br> (requires positional index) or all in memory (default case). * </code> */ public static void usage() { String usageMessage = "\nBuildIndex class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.BuildIndex PATH_TO_LUCENE_INDEX" + "\nBuildIndex creates termvectors and docvectors files in local directory." + "\nOther parameters that can be changed include vector length," + "\n (number of dimensions), seed length (number of non-zero" + "\n entries in basic vectors), minimum term frequency," + "\n and number of iterative training cycles." + "\nTo change these use the command line arguments " + "\n -dimension [number of dimensions]" + "\n -seedlength [seed length]" + "\n -minfrequency [minimum term frequency]" + "\n -maxnonalphabetchars [number non-alphabet characters (-1 for any number)]" + "\n -trainingcycles [training cycles]" + "\n -docindexing [incremental|inmemory|none] Switch between building doc vectors incrementally" + "\n (requires positional index), all in memory (default case), or not at all"; System.out.println(usageMessage); } /** * Builds term vector and document vector stores from a Lucene index. * @param args * @see BuildIndex#usage */ public static void main (String[] args) throws IllegalArgumentException { try { args = Flags.parseCommandLineFlags(args); } catch (IllegalArgumentException e) { usage(); throw e; } // Only one argument should remain, the path to the Lucene index. if (args.length != 1) { usage(); throw (new IllegalArgumentException("After parsing command line flags, there were " + args.length + " arguments, instead of the expected 1.")); } String luceneIndex = args[0]; System.err.println("Seedlength = " + Flags.seedlength); System.err.println("Dimension = " + Flags.dimension); System.err.println("Minimum frequency = " + Flags.minfrequency); System.err.println("Maximum frequency = " + Flags.maxfrequency); System.err.println("Number non-alphabet characters = " + Flags.maxnonalphabetchars); String termFile = "termvectors.bin"; String docFile = "docvectors.bin"; VectorStoreRAM initialdocvectors = null; System.err.println("Contents fields are: " + Arrays.toString(Flags.contentsfields)); try{ TermVectorsFromLucene vecStore; if (Flags.initialtermvectors.length() > 0) { // If Flags.initialtermvectors="random" create elemental (random index) // term vectors. Recommended to iterate at least once (i.e. -trainingcycles = 2) to // obtain semantic term vectors. // Otherwise attempt to load pre-existing semantic term vectors. System.err.println("Creating term vectors ..."); vecStore = new TermVectorsFromLucene(luceneIndex, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, Flags.initialtermvectors, Flags.contentsfields); } else { System.err.println("Creating elemental document vectors ..."); vecStore = new TermVectorsFromLucene(luceneIndex, Flags.dimension, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, null, Flags.contentsfields); } // Create doc vectors and write vectors to disk. VectorStoreWriter vecWriter = new VectorStoreWriter(); if (Flags.docindexing.equals("incremental")) { System.err.println("Writing term vectors to " + termFile); vecWriter.WriteVectors(termFile, vecStore); IncrementalDocVectors idocVectors = new IncrementalDocVectors(vecStore, luceneIndex, Flags.contentsfields, "incremental_"+docFile); IncrementalTermVectors itermVectors = null; for (int i = 1; i < Flags.trainingcycles; ++i) { itermVectors = new IncrementalTermVectors(luceneIndex, Flags.dimension, Flags.contentsfields, "incremental_"+docFile); new VectorStoreWriter().WriteVectors("incremental_termvectors"+Flags.trainingcycles+".bin", itermVectors); //Write over previous cycle's docvectors until final iteration, then rename according to number cycles if (i == Flags.trainingcycles-1) docFile = "docvectors"+Flags.trainingcycles+".bin"; idocVectors = new IncrementalDocVectors(itermVectors, luceneIndex, Flags.contentsfields, "incremental_"+docFile); } } else if (Flags.docindexing.equals("inmemory")) { DocVectors docVectors = new DocVectors(vecStore); for (int i = 1; i < Flags.trainingcycles; ++i) { System.err.println("\nRetraining with learned document vectors ..."); vecStore = new TermVectorsFromLucene(luceneIndex, Flags.dimension, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, docVectors, Flags.contentsfields); docVectors = new DocVectors(vecStore); } // At end of training, convert document vectors from ID keys to pathname keys. VectorStore writeableDocVectors = docVectors.makeWriteableVectorStore(); if (Flags.trainingcycles > 1) { termFile = "termvectors" + Flags.trainingcycles + ".bin"; docFile = "docvectors" + Flags.trainingcycles + ".bin"; } System.err.println("Writing term vectors to " + termFile); vecWriter.WriteVectors(termFile, vecStore); System.err.println("Writing doc vectors to " + docFile); vecWriter.WriteVectors(docFile, writeableDocVectors); } else { // Write term vectors to disk even if there are no docvectors to output. System.err.println("Writing term vectors to " + termFile); vecWriter.WriteVectors(termFile, vecStore); } } catch (IOException e) { e.printStackTrace(); } } }
Trivial whitespace cleanup.
src/pitt/search/semanticvectors/BuildIndex.java
Trivial whitespace cleanup.
Java
bsd-3-clause
error: pathspec 'src/us/crast/mondochest/DirectionalStrings.java' did not match any file(s) known to git
18693292b859e0facaed4301bbb70d4f0ba85cbc
1
crast/MondoChest,crast/MondoChest
package us.crast.mondochest; import java.util.HashMap; import java.util.Map; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; public class DirectionalStrings { private static Map<String, BlockFace> dirs = new HashMap<String, BlockFace>(); public static Block parseDirectional(Block context, String directioninfo) throws MondoMessage { String[] directional = directioninfo.split(" "); if ((directional.length % 2) != 0) { throw new MondoMessage("Directional info specification is invalid"); } for (int i = 0; i < directional.length; i+=2) { BlockFace desired_face = dirs.get(directional[i].toUpperCase()); if (desired_face == null) { throw new MondoMessage(String.format("Direction must be one of up/down/north/south/east/west, got '{0}'", directional[i])); } int distance = Integer.parseInt(directional[i+1]); if (distance < 0) { distance = -distance; desired_face = desired_face.getOppositeFace(); } context = context.getRelative(desired_face, distance); } return context; } static { dirs.put("UP", BlockFace.UP); dirs.put("DOWN", BlockFace.DOWN); dirs.put("EAST", BlockFace.EAST); dirs.put("WEST", BlockFace.WEST); dirs.put("NORTH", BlockFace.NORTH); dirs.put("SOUTH", BlockFace.SOUTH); } }
src/us/crast/mondochest/DirectionalStrings.java
Add in support for parsing directional strings like 'up 7 east 12'
src/us/crast/mondochest/DirectionalStrings.java
Add in support for parsing directional strings like 'up 7 east 12'
Java
mit
052e08556733f1ca1aad57be199eb99829576128
0
Pankiev/Distributed-Processing-Gdansk-University-of-Technology-project
package pl.gda.pg.student.project.server; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.Server; import pl.gda.pg.student.project.kryonetcommon.ConnectionSettings; import pl.gda.pg.student.project.kryonetcommon.IdSupplier; import pl.gda.pg.student.project.kryonetcommon.PacketsRegisterer; import pl.gda.pg.student.project.libgdxcommon.Assets; import pl.gda.pg.student.project.libgdxcommon.StateManager; import pl.gda.pg.student.project.libgdxcommon.exception.GameException; import pl.gda.pg.student.project.libgdxcommon.objects.GameObject; import pl.gda.pg.student.project.libgdxcommon.objects.MovableGameObject; import pl.gda.pg.student.project.packets.CreateObjectPacket; import pl.gda.pg.student.project.packets.DisconnectPacket; import pl.gda.pg.student.project.packets.PlayerPutBombPacket; import pl.gda.pg.student.project.packets.RemoveObjectInfo; import pl.gda.pg.student.project.packets.movement.*; import pl.gda.pg.student.project.server.helpers.PlayerPositioner; import pl.gda.pg.student.project.server.objects.Bomb; import pl.gda.pg.student.project.server.objects.ObjectsIdentifier; import pl.gda.pg.student.project.server.objects.ServerPlayer; import pl.gda.pg.student.project.server.states.ServerPlayState; import java.io.IOException; import java.util.Map; public class GameServer extends ApplicationAdapter { private PlayerPositioner positioner; private SpriteBatch batch; public static Assets assets; private StateManager states; private Server server; private ServerPlayState gameState; @Override public void create() { positioner = new PlayerPositioner(); server = initializeServer(); assets = new Assets(); batch = new SpriteBatch(); states = new StateManager(); gameState = new ServerPlayState(); states.push(gameState); } private Server initializeServer() { Server server = new Server(); Kryo serverKryo = server.getKryo(); serverKryo = PacketsRegisterer.registerAllAnnotated(serverKryo); serverKryo = PacketsRegisterer.registerDefaults(serverKryo); server.addListener(new ServerListener()); server.start(); tryBindingServer(server, ConnectionSettings.TCP_PORT, ConnectionSettings.UDP_PORT); return server; } private void tryBindingServer(Server server, int tcpPort, int udpPort) { try { server.bind(tcpPort, udpPort); } catch (IOException e) { throw new CannotBindServerException(e.getMessage()); } } @Override public void render() { update(); Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); states.render(batch); batch.end(); } private void update() { states.update(); } @Override public void dispose() { assets.dispose(); } private void userConnected(int clientId) { sendGameStateInfo(clientId); Vector2 playerPosition = positioner.getPosition(); addPlayerObjectOnServer(clientId, playerPosition); informOthersAboutNewPlayer(clientId, playerPosition); sendPositionUpdateInfoToNewClient(clientId, playerPosition); } private void sendGameStateInfo(int clientId) { Map<Long, GameObject> gameObjects = gameState.getGameObjects(); for(GameObject object : gameObjects.values()) sendObjectCreationInfo(object, clientId); } private void sendObjectCreationInfo(GameObject object, int targetClientId) { CreateObjectPacket createObjectPacket = new CreateObjectPacket(); createObjectPacket.id = object.getId(); createObjectPacket.xPosition = object.getX(); createObjectPacket.yPosition = object.getY(); createObjectPacket.objectType = ObjectsIdentifier.getObjectIdentifier(object.getClass()); server.sendToTCP(targetClientId, createObjectPacket); } private void addPlayerObjectOnServer(int clientId, Vector2 playerPosition) { ServerPlayer newPlayer = new ServerPlayer(gameState); newPlayer.setId(clientId); newPlayer.setPosition(playerPosition.x, playerPosition.y); gameState.add(newPlayer); } private void informOthersAboutNewPlayer(int id, Vector2 playerPosition) { CreateObjectPacket createNewPlayer = new CreateObjectPacket(); createNewPlayer.id = id; createNewPlayer.objectType = ObjectsIdentifier.getObjectIdentifier(ServerPlayer.class); createNewPlayer.xPosition = playerPosition.x; createNewPlayer.yPosition = playerPosition.y; server.sendToAllExceptTCP(id, createNewPlayer); } private void sendPositionUpdateInfoToNewClient(int clientId, Vector2 playerPosition) { ObjectSetPositionPacket setPositionPacket = new ObjectSetPositionPacket(); setPositionPacket.id = clientId; setPositionPacket.x = playerPosition.x; setPositionPacket.y = playerPosition.y; server.sendToTCP(clientId, setPositionPacket); } private void userDisconnected(long id) { RemoveObjectInfo removeObjectInfo = new RemoveObjectInfo(); removeObjectInfo.id = id; server.sendToAllTCP(removeObjectInfo); gameState.remove(id); } private static class CannotBindServerException extends GameException { public CannotBindServerException(String message) { super(message); } } private Vector2 countBombLegalPosition(Vector2 playerPosition){ Vector2 bombPosition = new Vector2(); int playerPositionX = (int)playerPosition.x; int playerPositionY = (int)playerPosition.y; int fazeX = playerPositionX%27; int fazeY = playerPositionY%27; int noOfTileX = playerPositionX/27; int noOfTileY = playerPositionY/27; if(fazeX > 27/2) noOfTileX++; if(fazeY > 27/2) noOfTileY++; float bombPositionX = noOfTileX*27; float bombPositionY = noOfTileY*27; bombPosition.set(bombPositionX, bombPositionY); System.out.println(bombPosition); return bombPosition; } private class ServerListener extends Listener { @Override public void connected(Connection connection) { userConnected(connection.getID()); System.out.println("Client connected server side, id: " + connection.getID()); } @Override public void disconnected(Connection connection) { userDisconnected(connection.getID()); System.out.println("Client connected server side, id: " + connection.getID()); } @Override public void received(Connection connection, Object object) { if(object instanceof ObjectSetPositionPacket) { ObjectSetPositionPacket setPositionPacket = (ObjectSetPositionPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(setPositionPacket.id); operationTarget.setPosition(setPositionPacket.x, setPositionPacket.y); server.sendToAllTCP(setPositionPacket); } else if(object instanceof ObjectMoveLeftPacket) { ObjectMoveLeftPacket moveLeftPacket = (ObjectMoveLeftPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveLeftPacket.id); operationTarget.moveLeft(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof ObjectMoveRightPacket) { ObjectMoveRightPacket moveRightPacket = (ObjectMoveRightPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveRight(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if (object instanceof ObjectMoveUpPacket) { ObjectMoveUpPacket moveRightPacket = (ObjectMoveUpPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveUp(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof ObjectMoveDownPacket) { ObjectMoveDownPacket moveRightPacket = (ObjectMoveDownPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveDown(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof DisconnectPacket) connection.close(); else if (object instanceof PlayerPutBombPacket) { PlayerPutBombPacket putBombPacket = (PlayerPutBombPacket) object; ServerPlayer player = (ServerPlayer) gameState.getObject(putBombPacket.id); if(player.canPlaceBomb()){ Vector2 bombPosition = countBombLegalPosition(new Vector2(player.getX(), player.getY())); Bomb bomb = new Bomb(gameState, bombPosition, player); long id = IdSupplier.getId(); bomb.setId(id); gameState.add(bomb); CreateObjectPacket createObjectPacket = new CreateObjectPacket(); createObjectPacket.xPosition = bombPosition.x; createObjectPacket.yPosition = bombPosition.y; createObjectPacket.id = id; createObjectPacket.objectType = "Bomb"; server.sendToAllTCP(createObjectPacket); } } System.out.println("Server side: object reveived from client id: " + connection.getID() + " " + object); } private ObjectSetPositionPacket createSetPositionPacketByObject(GameObject object) { ObjectSetPositionPacket packet = new ObjectSetPositionPacket(); packet.id = object.getId(); packet.x = object.getX(); packet.y = object.getY(); return packet; } } }
core/src/pl/gda/pg/student/project/server/GameServer.java
package pl.gda.pg.student.project.server; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.Server; import pl.gda.pg.student.project.kryonetcommon.ConnectionSettings; import pl.gda.pg.student.project.kryonetcommon.IdSupplier; import pl.gda.pg.student.project.kryonetcommon.PacketsRegisterer; import pl.gda.pg.student.project.libgdxcommon.Assets; import pl.gda.pg.student.project.libgdxcommon.StateManager; import pl.gda.pg.student.project.libgdxcommon.exception.GameException; import pl.gda.pg.student.project.libgdxcommon.objects.GameObject; import pl.gda.pg.student.project.libgdxcommon.objects.MovableGameObject; import pl.gda.pg.student.project.packets.CreateObjectPacket; import pl.gda.pg.student.project.packets.DisconnectPacket; import pl.gda.pg.student.project.packets.PlayerPutBombPacket; import pl.gda.pg.student.project.packets.RemoveObjectInfo; import pl.gda.pg.student.project.packets.movement.*; import pl.gda.pg.student.project.server.helpers.PlayerPositioner; import pl.gda.pg.student.project.server.objects.Bomb; import pl.gda.pg.student.project.server.objects.ObjectsIdentifier; import pl.gda.pg.student.project.server.objects.ServerPlayer; import pl.gda.pg.student.project.server.states.ServerPlayState; import java.io.IOException; import java.util.Map; public class GameServer extends ApplicationAdapter { private PlayerPositioner positioner; private SpriteBatch batch; public static Assets assets; private StateManager states; private Server server; private ServerPlayState gameState; @Override public void create() { positioner = new PlayerPositioner(); server = initializeServer(); assets = new Assets(); batch = new SpriteBatch(); states = new StateManager(); gameState = new ServerPlayState(); states.push(gameState); } private Server initializeServer() { Server server = new Server(); Kryo serverKryo = server.getKryo(); serverKryo = PacketsRegisterer.registerAllAnnotated(serverKryo); serverKryo = PacketsRegisterer.registerDefaults(serverKryo); server.addListener(new ServerListener()); server.start(); tryBindingServer(server, ConnectionSettings.TCP_PORT, ConnectionSettings.UDP_PORT); return server; } private void tryBindingServer(Server server, int tcpPort, int udpPort) { try { server.bind(tcpPort, udpPort); } catch (IOException e) { throw new CannotBindServerException(e.getMessage()); } } @Override public void render() { update(); Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); states.render(batch); batch.end(); } private void update() { states.update(); } @Override public void dispose() { assets.dispose(); } private void userConnected(int clientId) { sendGameStateInfo(clientId); Vector2 playerPosition = positioner.getPosition(); addPlayerObjectOnServer(clientId, playerPosition); informOthersAboutNewPlayer(clientId, playerPosition); sendPositionUpdateInfoToNewClient(clientId, playerPosition); } private void sendGameStateInfo(int clientId) { Map<Long, GameObject> gameObjects = gameState.getGameObjects(); for(GameObject object : gameObjects.values()) sendObjectCreationInfo(object, clientId); } private void sendObjectCreationInfo(GameObject object, int targetClientId) { CreateObjectPacket createObjectPacket = new CreateObjectPacket(); createObjectPacket.id = object.getId(); createObjectPacket.xPosition = object.getX(); createObjectPacket.yPosition = object.getY(); createObjectPacket.objectType = ObjectsIdentifier.getObjectIdentifier(object.getClass()); server.sendToTCP(targetClientId, createObjectPacket); } private void addPlayerObjectOnServer(int clientId, Vector2 playerPosition) { ServerPlayer newPlayer = new ServerPlayer(gameState); newPlayer.setId(clientId); newPlayer.setPosition(playerPosition.x, playerPosition.y); gameState.add(newPlayer); } private void informOthersAboutNewPlayer(int id, Vector2 playerPosition) { CreateObjectPacket createNewPlayer = new CreateObjectPacket(); createNewPlayer.id = id; createNewPlayer.objectType = ObjectsIdentifier.getObjectIdentifier(ServerPlayer.class); createNewPlayer.xPosition = playerPosition.x; createNewPlayer.yPosition = playerPosition.y; server.sendToAllExceptTCP(id, createNewPlayer); } private void sendPositionUpdateInfoToNewClient(int clientId, Vector2 playerPosition) { ObjectSetPositionPacket setPositionPacket = new ObjectSetPositionPacket(); setPositionPacket.id = clientId; setPositionPacket.x = playerPosition.x; setPositionPacket.y = playerPosition.y; server.sendToTCP(clientId, setPositionPacket); } private void userDisconnected(long id) { RemoveObjectInfo removeObjectInfo = new RemoveObjectInfo(); removeObjectInfo.id = id; server.sendToAllTCP(removeObjectInfo); gameState.remove(id); } private static class CannotBindServerException extends GameException { public CannotBindServerException(String message) { super(message); } } private Vector2 countBombLegalPosition(Vector2 playerPosition){ Vector2 bombPosition = new Vector2(); int xFaze = (int)playerPosition.x%27; int yFaze = (int)playerPosition.y%27; if(xFaze > 27/2) xFaze *= -1; if(yFaze > 27/2) yFaze *= -1; float bombPositionX = (int)playerPosition.x - xFaze; float bombPositionY = (int)playerPosition.y - yFaze; bombPosition.set(bombPositionX, bombPositionY); return bombPosition; } private class ServerListener extends Listener { @Override public void connected(Connection connection) { userConnected(connection.getID()); System.out.println("Client connected server side, id: " + connection.getID()); } @Override public void disconnected(Connection connection) { userDisconnected(connection.getID()); System.out.println("Client connected server side, id: " + connection.getID()); } @Override public void received(Connection connection, Object object) { if(object instanceof ObjectSetPositionPacket) { ObjectSetPositionPacket setPositionPacket = (ObjectSetPositionPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(setPositionPacket.id); operationTarget.setPosition(setPositionPacket.x, setPositionPacket.y); server.sendToAllTCP(setPositionPacket); } else if(object instanceof ObjectMoveLeftPacket) { ObjectMoveLeftPacket moveLeftPacket = (ObjectMoveLeftPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveLeftPacket.id); operationTarget.moveLeft(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof ObjectMoveRightPacket) { ObjectMoveRightPacket moveRightPacket = (ObjectMoveRightPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveRight(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if (object instanceof ObjectMoveUpPacket) { ObjectMoveUpPacket moveRightPacket = (ObjectMoveUpPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveUp(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof ObjectMoveDownPacket) { ObjectMoveDownPacket moveRightPacket = (ObjectMoveDownPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveDown(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof DisconnectPacket) connection.close(); else if (object instanceof PlayerPutBombPacket) { PlayerPutBombPacket putBombPacket = (PlayerPutBombPacket) object; ServerPlayer player = (ServerPlayer) gameState.getObject(putBombPacket.id); if(player.canPlaceBomb()){ Vector2 bombPosition = countBombLegalPosition(new Vector2(player.getX(), player.getY())); Bomb bomb = new Bomb(gameState, bombPosition, player); long id = IdSupplier.getId(); bomb.setId(id); gameState.add(bomb); CreateObjectPacket createObjectPacket = new CreateObjectPacket(); createObjectPacket.xPosition = bombPosition.x; createObjectPacket.yPosition = bombPosition.y; createObjectPacket.id = id; createObjectPacket.objectType = "Bomb"; server.sendToAllTCP(createObjectPacket); } } System.out.println("Server side: object reveived from client id: " + connection.getID() + " " + object); } private ObjectSetPositionPacket createSetPositionPacketByObject(GameObject object) { ObjectSetPositionPacket packet = new ObjectSetPositionPacket(); packet.id = object.getId(); packet.x = object.getX(); packet.y = object.getY(); return packet; } } }
bomb position
core/src/pl/gda/pg/student/project/server/GameServer.java
bomb position
Java
mit
ea080d9ffc2595bb677f4c8c1b62e51416e9203f
0
KyoriPowered/text,KyoriPowered/text
/* * This file is part of adventure, licensed under the MIT License. * * Copyright (c) 2017-2020 KyoriPowered * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.kyori.adventure.bossbar; import java.util.Set; import net.kyori.adventure.text.Component; import net.kyori.adventure.util.NameMap; import org.checkerframework.checker.nullness.qual.NonNull; /** * A bossbar. */ public interface BossBar { /** * Creates a new bossbar. * * @param name the name * @param percent the percent, between 0 and 1 * @param color the color * @param overlay the overlay * @return a bossbar */ static @NonNull BossBar of(final @NonNull Component name, final float percent, final @NonNull Color color, final @NonNull Overlay overlay) { BossBarImpl.checkPercent(percent); return new BossBarImpl(name, percent, color, overlay); } /** * Creates a new bossbar. * * @param name the name * @param percent the percent, between 0 and 1 * @param color the color * @param overlay the overlay * @param flags the flags * @return a bossbar */ static @NonNull BossBar of(final @NonNull Component name, final float percent, final @NonNull Color color, final @NonNull Overlay overlay, final @NonNull Set<Flag> flags) { BossBarImpl.checkPercent(percent); return new BossBarImpl(name, percent, color, overlay, flags); } /** * Gets the name. * * @return the name */ @NonNull Component name(); /** * Sets the name. * * @param name the name * @return the bossbar */ @NonNull BossBar name(final @NonNull Component name); /** * Gets the percent. * * <p>The percent is a value between 0 and 1.</p> * * @return the percent */ float percent(); /** * Sets the percent. * * <p>The percent is a value between 0 and 1.</p> * * @param percent the percent * @return the bossbar */ @NonNull BossBar percent(final float percent); /** * Gets the color. * * @return the color */ @NonNull Color color(); /** * Sets the color. * * @param color the color * @return the bossbar */ @NonNull BossBar color(final @NonNull Color color); /** * Gets the overlay. * * @return the overlay */ @NonNull Overlay overlay(); /** * Sets the overlay. * * @param overlay the overlay * @return the bossbar */ @NonNull BossBar overlay(final @NonNull Overlay overlay); /** * Gets the flags. * * @return the flags */ @NonNull Set<Flag> flags(); /** * Sets the flags. * * @param flags the flags * @return the bossbar */ @NonNull BossBar flags(final @NonNull Set<Flag> flags); /** * Sets the flags. * * @param flags the flags * @return the bossbar */ @NonNull BossBar addFlags(final @NonNull Flag@NonNull... flags); /** * Sets the flags. * * @param flags the flags * @return the bossbar */ @NonNull BossBar removeFlags(final @NonNull Flag@NonNull... flags); /** * Adds a listener. * * @param listener a listener * @return the bossbar */ @NonNull BossBar addListener(final @NonNull Listener listener); /** * Removes a listener. * * @param listener a listener * @return the bossbar */ @NonNull BossBar removeListener(final @NonNull Listener listener); /** * A listener. */ @FunctionalInterface interface Listener { void bossBarChanged(final @NonNull BossBar bar, final @NonNull Change change); /** * The type of change. */ enum Change { NAME, PERCENT, COLOR, OVERLAY, FLAGS; } } enum Color { PINK("pink"), BLUE("blue"), RED("red"), GREEN("green"), YELLOW("yellow"), PURPLE("purple"), WHITE("white"); public static final NameMap<Color> NAMES = NameMap.create(Color.class, color -> color.name); private final String name; Color(final String name) { this.name = name; } } enum Flag { /** * If the screen should be darkened. */ DARKEN_SCREEN, /** * If boss music should be played. */ PLAY_BOSS_MUSIC, /** * If world fog should be created. */ CREATE_WORLD_FOG; } enum Overlay { PROGRESS("progress"), NOTCHED_6("notched_6"), NOTCHED_10("notched_10"), NOTCHED_12("notched_12"), NOTCHED_20("notched_20"); public static final NameMap<Overlay> NAMES = NameMap.create(Overlay.class, overlay -> overlay.name); private final String name; Overlay(final String name) { this.name = name; } } }
api/src/main/java/net/kyori/adventure/bossbar/BossBar.java
/* * This file is part of adventure, licensed under the MIT License. * * Copyright (c) 2017-2020 KyoriPowered * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.kyori.adventure.bossbar; import java.util.Set; import net.kyori.adventure.text.Component; import net.kyori.adventure.util.NameMap; import org.checkerframework.checker.nullness.qual.NonNull; /** * A bossbar. */ public interface BossBar { /** * Creates a new bossbar. * * @param name the name * @param percent the percent, between 0 and 1 * @param color the color * @param overlay the overlay * @return a bossbar */ static @NonNull BossBar of(final @NonNull Component name, final float percent, final @NonNull Color color, final @NonNull Overlay overlay) { BossBarImpl.checkPercent(percent); return new BossBarImpl(name, percent, color, overlay); } /** * Creates a new bossbar. * * @param name the name * @param percent the percent, between 0 and 1 * @param color the color * @param overlay the overlay * @param flags the flags * @return a bossbar */ static @NonNull BossBar of(final @NonNull Component name, final float percent, final @NonNull Color color, final @NonNull Overlay overlay, final @NonNull Set<Flag> flags) { BossBarImpl.checkPercent(percent); return new BossBarImpl(name, percent, color, overlay, flags); } /** * Gets the name. * * @return the name */ @NonNull Component name(); /** * Sets the name. * * @param name the name * @return the bossbar */ @NonNull BossBar name(final @NonNull Component name); /** * Gets the percent. * * <p>The percent is a value between 0 and 1.</p> * * @return the percent */ float percent(); /** * Sets the percent. * * <p>The percent is a value between 0 and 1.</p> * * @param percent the percent * @return the bossbar */ @NonNull BossBar percent(final float percent); /** * Gets the color. * * @return the color */ @NonNull Color color(); /** * Sets the color. * * @param color the color * @return the bossbar */ @NonNull BossBar color(final @NonNull Color color); /** * Gets the overlay. * * @return the overlay */ @NonNull Overlay overlay(); /** * Sets the overlay. * * @param overlay the overlay * @return the bossbar */ @NonNull BossBar overlay(final @NonNull Overlay overlay); /** * Gets the flags. * * @return the flags */ @NonNull Set<Flag> flags(); /** * Sets the flags. * * @param flags the flags * @return the bossbar */ @NonNull BossBar flags(final @NonNull Set<Flag> flags); /** * Sets the flags. * * @param flags the flags * @return the bossbar */ @NonNull BossBar addFlags(final @NonNull Flag@NonNull... flags); /** * Sets the flags. * * @param flags the flags * @return the bossbar */ @NonNull BossBar removeFlags(final @NonNull Flag@NonNull... flags); @NonNull BossBar addListener(final @NonNull Listener listener); @NonNull BossBar removeListener(final @NonNull Listener listener); @FunctionalInterface interface Listener { void bossBarChanged(final @NonNull BossBar bar, final @NonNull Change change); /** * The type of change. */ enum Change { NAME, PERCENT, COLOR, OVERLAY, FLAGS; } } enum Color { PINK("pink"), BLUE("blue"), RED("red"), GREEN("green"), YELLOW("yellow"), PURPLE("purple"), WHITE("white"); public static final NameMap<Color> NAMES = NameMap.create(Color.class, color -> color.name); private final String name; Color(final String name) { this.name = name; } } enum Flag { /** * If the screen should be darkened. */ DARKEN_SCREEN, /** * If boss music should be played. */ PLAY_BOSS_MUSIC, /** * If world fog should be created. */ CREATE_WORLD_FOG; } enum Overlay { PROGRESS("progress"), NOTCHED_6("notched_6"), NOTCHED_10("notched_10"), NOTCHED_12("notched_12"), NOTCHED_20("notched_20"); public static final NameMap<Overlay> NAMES = NameMap.create(Overlay.class, overlay -> overlay.name); private final String name; Overlay(final String name) { this.name = name; } } }
bossbar listener changes
api/src/main/java/net/kyori/adventure/bossbar/BossBar.java
bossbar listener changes
Java
mit
735c73a1012451bbc183ea27c69764557289ab2d
0
andrewyang96/PokePebble
package seniorcheeseman.pokepebbleassistapp; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.URI; import java.net.URISyntaxException; import java.util.UUID; import PokemonParts.Party; import PokemonParts.Pokemon; public class MainActivity extends AppCompatActivity { private static final String TAG = "MyActivity"; private WebSocketClient mWebSocketClient; private boolean mGotPokemon; private Party mParty; private String mBattleRoom; private Button mGod, mForfeitButton; private View.OnClickListener mFindBattleListener, mForfeitListener; private PebbleKit.PebbleDataReceiver mReceiver; private static final int MOVE = 1,POS = 2,FORFEIT =3,SWITCH = 4; private PebbleDictionary data; private final static UUID PEBBLE_APP_UUID = UUID.fromString("46263b9e-6ecf-4454-8388-0638495af75f"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); connectWebSocket(); mGotPokemon = false; mGod = (Button) findViewById(R.id.testButton); mForfeitButton = (Button) findViewById(R.id.forfeitButton); mForfeitListener = new View.OnClickListener() { @Override public void onClick(View v) { forfeit(); } }; mFindBattleListener = new View.OnClickListener() { @Override public void onClick(View v) { findRandomBattle(); mGod.setOnClickListener(null); mForfeitButton.setOnClickListener(mForfeitListener); } }; mGod.setOnClickListener(mFindBattleListener); if (mReceiver == null) { mReceiver = new PebbleKit.PebbleDataReceiver(PEBBLE_APP_UUID) { @Override public void receiveData(Context context, int id, PebbleDictionary data) { // Always ACKnowledge the last message to prevent timeouts PebbleKit.sendAckToPebble(getApplicationContext(), id); if(data.contains(MOVE)) { long t = data.getInteger(POS); int pos =(int) t; makeMove(pos); } else if(data.contains(SWITCH)) { long t = data.getInteger(POS); int pos =(int) t; switchPokemon(pos); } else if(data.contains(FORFEIT)) { forfeit(); } Log.i("receiveData", "Got message from Pebble!"); // Get action and display // int state = data.getUnsignedIntegerAsLong().intValue(); } }; } // Register the receiver to get data PebbleKit.registerReceivedDataHandler(this, mReceiver); } private void forfeit() { String giveUp = mBattleRoom + "|/forfeit"; sendMessage(giveUp); mForfeitButton.setOnClickListener(null);//todo make it invisible mGod.setOnClickListener(mFindBattleListener); } private void findRandomBattle() { sendMessage("|/cancelsearch"); sendMessage("|/search randombattle"); } private void makeMove(int move) { String in = Integer.toString(move + 1); sendMessage(mBattleRoom + "|/move " + in); } private void switchPokemon(int pos) { String in = Integer.toString(pos + 1); mParty.switchPokemon(0, pos); sendMessage(mBattleRoom + "|/switch " + in); } @Override protected void onDestroy() { super.onDestroy(); mWebSocketClient.close(); } @Override protected void onResume() { super.onResume(); boolean isConnected = PebbleKit.isWatchConnected(this); Toast.makeText(this, "Pebble " + (isConnected ? "is" : "is not") + " connected!", Toast.LENGTH_LONG).show(); boolean appMessageSupported = PebbleKit.areAppMessagesSupported(this); Log.d("PebbleMessages", (appMessageSupported) ? "true" : "false"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void connectWebSocket() { URI uri; try { uri = new URI("ws://159.203.89.223:8000/showdown/websocket"); } catch (URISyntaxException e) { e.printStackTrace(); return; } mWebSocketClient = new WebSocketClient(uri) { @Override public void onOpen(ServerHandshake serverHandshake) { Log.i("Websocket", "Opened"); mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL); } @Override public void onMessage(String s) { final String message = s; data = new PebbleDictionary(); if (s.contains("request")) { if (!mGotPokemon) { String[] parts = message.split("request"); JSONObject part; try { data.addString(0,"CreateParty"); part = getParty(parts[1].substring(1));//hard coded mGotPokemon = true; JSONObject temp = part.getJSONObject("side"); JSONArray pokes = temp.getJSONArray("pokemon"); Pokemon[] pokemons = new Pokemon[6]; for (int x = 0; x < pokes.length(); x++) { int[] pp = {12, 12, 12, 12}; for(int y=0;y<4;y++) { data.addInt32(11*x+6+y+2,pp[y]); } String[] moves = new String[4]; JSONObject poke = (JSONObject) pokes.get(0); JSONArray pokeMoves = (JSONArray) poke.get("moves"); for (int y = 0; y < 4; y++) { moves[y] = (String) pokeMoves.get(y); data.addString(11*x+y+2,moves[y]); } String name = ((JSONObject) (pokes.get(x))).getString("ident").split(":")[1]; int pokekeyname = 11*x+1; data.addString(pokekeyname, name); int hp = Integer.parseInt(((JSONObject) (pokes.get(x))).getString("condition").split("/")[1]); data.addInt32(11*x+6,hp);data.addInt32(11*x+7,hp); pokemons[x] = new Pokemon(name, moves, pp, hp); PebbleKit.sendDataToPebble(getApplicationContext(),PEBBLE_APP_UUID,data); } mParty = new Party(pokemons); } catch (JSONException e) { e.printStackTrace(); } } else if (message.contains("active")) { data.addString(0,"UpdateMoves"); String[] parts = message.split("request"); JSONObject part; try { part = getParty(parts[1].substring(1)); JSONArray temp = part.getJSONArray("active"); JSONObject first = (JSONObject) temp.get(0); temp = first.getJSONArray("moves"); for (int x = 0; x < first.length(); x++) { JSONObject moves = (JSONObject) temp.get(x); if (!moves.getBoolean("disabled")) mParty.getPokemon(0).changeCurrentPP(x, moves.getInt("pp")); else mParty.getPokemon(0).changeCurrentPP(x, 0); mParty.getPokemon(0).changeTotalPP(x, moves.getInt("maxpp")); data.addInt32(x + 1, (moves.getInt("pp"))); data.addInt32(x+1+4,(moves.getInt("maxpp"))); Log.d("PPChanges", Integer.toString(moves.getInt("pp"))); Log.d("PPChanges", Integer.toString(moves.getInt("maxpp"))); } PebbleKit.sendDataToPebble(getApplicationContext(),PEBBLE_APP_UUID,data); } catch (JSONException e) { e.printStackTrace(); } } } else if (message.contains("battle-randombattle") && mBattleRoom == null) { String[] notBattleRoom = message.split("\\|"); mBattleRoom = notBattleRoom[0].substring(1); mBattleRoom = mBattleRoom.replaceAll("\n", ""); Log.d("BattleRoom", mBattleRoom); } else if ((message.contains("-damage") || message.contains("-heal")) && mParty != null) { data.addString(0,"ChangeHp"); String pokemonName = mParty.getPokemon(0).getName(); if (message.contains(pokemonName)) { if (message.contains("fnt")) { mParty.getPokemon(0).setFainted(); mParty.getPokemon(0).changeHp(0); data.addInt32(1,0); } else { String[] part = message.split("\\|"); String hps = part[2]; String[] healths = hps.split("/"); mParty.getPokemon(0).changeHp(Integer.parseInt(healths[0])); data.addInt32(1,Integer.parseInt((healths[0]))); } PebbleKit.sendDataToPebble(getApplicationContext(),PEBBLE_APP_UUID,data); Log.d("Hploss", Integer.toString(mParty.getPokemon(0).getHp())); } } Log.d(TAG, message); } @Override public void onClose(int i, String s, boolean b) { Log.i("Websocket", "Closed " + s); } @Override public void onError(Exception e) { Log.i("Websocket", "Error " + e.getMessage()); } }; mWebSocketClient.connect(); } public void sendMessage(String message) { mWebSocketClient.send(message); Log.d("WebsocketMessages", message); Toast.makeText(this, message + ": has been sent", Toast.LENGTH_LONG).show(); } /** * Parses the websocket input to get jsonarray of the pokemon * * @param input * @return JSONObject of pokemon */ public JSONObject getParty(String input) throws JSONException { JSONObject party = new JSONObject(input); return party; } }
Android/PokePebbleAssistApp/app/src/main/java/seniorcheeseman/pokepebbleassistapp/MainActivity.java
package seniorcheeseman.pokepebbleassistapp; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.URI; import java.net.URISyntaxException; import java.util.UUID; import PokemonParts.Party; import PokemonParts.Pokemon; public class MainActivity extends AppCompatActivity { private static final String TAG = "MyActivity"; private WebSocketClient mWebSocketClient; private boolean mGotPokemon; private Party mParty; private String mBattleRoom; private Button mGod, mForfeitButton; private View.OnClickListener mFindBattleListener, mForfeitListener; private PebbleKit.PebbleDataReceiver mReceiver; private final static UUID PEBBLE_APP_UUID = UUID.fromString("46263b9e-6ecf-4454-8388-0638495af75f"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); connectWebSocket(); mGotPokemon = false; mGod = (Button) findViewById(R.id.testButton); mForfeitButton = (Button) findViewById(R.id.forfeitButton); mForfeitListener = new View.OnClickListener() { @Override public void onClick(View v) { forfeit(); } }; mFindBattleListener = new View.OnClickListener() { @Override public void onClick(View v) { findRandomBattle(); mGod.setOnClickListener(null); mForfeitButton.setOnClickListener(mForfeitListener); } }; mGod.setOnClickListener(mFindBattleListener); if (mReceiver == null) { mReceiver = new PebbleKit.PebbleDataReceiver(PEBBLE_APP_UUID) { @Override public void receiveData(Context context, int id, PebbleDictionary data) { // Always ACKnowledge the last message to prevent timeouts PebbleKit.sendAckToPebble(getApplicationContext(), id); Log.i("receiveData", "Got message from Pebble!"); // Get action and display // int state = data.getUnsignedIntegerAsLong().intValue(); } }; } // Register the receiver to get data PebbleKit.registerReceivedDataHandler(this, mReceiver); } private void forfeit() { String giveUp = mBattleRoom + "|/forfeit"; sendMessage(giveUp); mForfeitButton.setOnClickListener(null);//todo make it invisible mGod.setOnClickListener(mFindBattleListener); } private void findRandomBattle() { sendMessage("|/cancelsearch"); sendMessage("|/search randombattle"); } private void makeMove(int move) { String in = Integer.toString(move + 1); sendMessage(mBattleRoom + "|/move " + in); } private void switchPokemon(int pos) { String in = Integer.toString(pos + 1); mParty.switchPokemon(0, pos); sendMessage(mBattleRoom + "|/switch " + in); } @Override protected void onDestroy() { super.onDestroy(); mWebSocketClient.close(); } @Override protected void onResume() { super.onResume(); boolean isConnected = PebbleKit.isWatchConnected(this); Toast.makeText(this, "Pebble " + (isConnected ? "is" : "is not") + " connected!", Toast.LENGTH_LONG).show(); boolean appMessageSupported = PebbleKit.areAppMessagesSupported(this); Log.d("PebbleMessages", (appMessageSupported) ? "true" : "false"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void connectWebSocket() { URI uri; try { uri = new URI("ws://159.203.89.223:8000/showdown/websocket"); } catch (URISyntaxException e) { e.printStackTrace(); return; } mWebSocketClient = new WebSocketClient(uri) { @Override public void onOpen(ServerHandshake serverHandshake) { Log.i("Websocket", "Opened"); mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL); } @Override public void onMessage(String s) { final String message = s; if (s.contains("request")) { if (!mGotPokemon) { String[] parts = message.split("request"); JSONObject part; try { part = getParty(parts[1].substring(1));//hard coded mGotPokemon = true; JSONObject temp = part.getJSONObject("side"); JSONArray pokes = temp.getJSONArray("pokemon"); Pokemon[] pokemons = new Pokemon[6]; for (int x = 0; x < pokes.length(); x++) { int[] pp = {12, 12, 12, 12}; String[] moves = new String[4]; JSONObject poke = (JSONObject) pokes.get(0); JSONArray pokeMoves = (JSONArray) poke.get("moves"); for (int y = 0; y < 4; y++) { moves[y] = (String) pokeMoves.get(y); } String name = ((JSONObject) (pokes.get(x))).getString("ident").split(":")[1]; int hp = Integer.parseInt(((JSONObject) (pokes.get(x))).getString("condition").split("/")[1]); pokemons[x] = new Pokemon(name, moves, pp, hp); } mParty = new Party(pokemons); } catch (JSONException e) { e.printStackTrace(); } } else if (message.contains("active")) { String[] parts = message.split("request"); JSONObject part; try { part = getParty(parts[1].substring(1)); JSONArray temp = part.getJSONArray("active"); JSONObject first = (JSONObject) temp.get(0); temp = first.getJSONArray("moves"); for (int x = 0; x < first.length(); x++) { JSONObject moves = (JSONObject) temp.get(x); if (!moves.getBoolean("disabled")) mParty.getPokemon(0).changeCurrentPP(x, moves.getInt("pp")); else mParty.getPokemon(0).changeCurrentPP(x, 0); mParty.getPokemon(0).changeTotalPP(x, moves.getInt("maxpp")); Log.d("PPChanges", Integer.toString(moves.getInt("pp"))); Log.d("PPChanges", Integer.toString(moves.getInt("maxpp"))); } } catch (JSONException e) { e.printStackTrace(); } } } else if (message.contains("battle-randombattle") && mBattleRoom == null) { String[] notBattleRoom = message.split("\\|"); mBattleRoom = notBattleRoom[0].substring(1); mBattleRoom = mBattleRoom.replaceAll("\n", ""); Log.d("BattleRoom", mBattleRoom); } else if ((message.contains("-damage") || message.contains("-heal")) && mParty != null) { String pokemonName = mParty.getPokemon(0).getName(); if (message.contains(pokemonName)) { if (message.contains("fnt")) { mParty.getPokemon(0).setFainted(); mParty.getPokemon(0).changeHp(0); } else { String[] part = message.split("\\|"); String hps = part[2]; String[] healths = hps.split("/"); mParty.getPokemon(0).changeHp(Integer.parseInt(healths[0])); } Log.d("Hploss", Integer.toString(mParty.getPokemon(0).getHp())); } } Log.d(TAG, message); } @Override public void onClose(int i, String s, boolean b) { Log.i("Websocket", "Closed " + s); } @Override public void onError(Exception e) { Log.i("Websocket", "Error " + e.getMessage()); } }; mWebSocketClient.connect(); } public void sendMessage(String message) { mWebSocketClient.send(message); Log.d("WebsocketMessages", message); Toast.makeText(this, message + ": has been sent", Toast.LENGTH_LONG).show(); } /** * Parses the websocket input to get jsonarray of the pokemon * * @param input * @return JSONObject of pokemon */ public JSONObject getParty(String input) throws JSONException { JSONObject party = new JSONObject(input); return party; } }
untested android sending messages to pebble code
Android/PokePebbleAssistApp/app/src/main/java/seniorcheeseman/pokepebbleassistapp/MainActivity.java
untested android sending messages to pebble code
Java
mit
96f4582908c0eb938f8503498e3650068b495aee
0
hearsilent/TTU-WiFiAutoLogin,HackGen/TTU-WiFiAutoLogin,hearsilent/TTU-WiFiAutoLogin,HackGen/TTU-WiFiAutoLogin
package tw.edu.ttu.wifiautoconnect; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.app.Activity; import android.content.SharedPreferences; public class WifiAutoConnect extends Activity { public static final String PREF = "ACCOUNT_PREF"; public static final String PREF_USERNAME = "USERNAME"; public static final String PREF_PWD = "PASSWORD"; private EditText usernameEditText; private EditText passwordEditText; private CheckBox showPasswordCheckBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi_auto_connect); usernameEditText = (EditText) findViewById(R.id.et_username); passwordEditText = (EditText) findViewById(R.id.et_password); showPasswordCheckBox = (CheckBox) findViewById(R.id.cb_showpwd); restorePrefs(); } public void showPasswordCheckBoxOnclick(View view) { if (showPasswordCheckBox.isChecked()) { passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } public void loginBthOnclick(View view) { } private void restorePrefs() { SharedPreferences setting = getSharedPreferences(PREF, 0); String username = setting.getString(PREF_USERNAME, ""); String password = setting.getString(PREF_PWD, ""); usernameEditText.setText(username); passwordEditText.setText(password); } private void savePrefs() { SharedPreferences setting = getSharedPreferences(PREF, 0); setting.edit() .putString(PREF_USERNAME, usernameEditText.getText().toString()) .putString(PREF_PWD, passwordEditText.getText().toString()) .commit(); } @Override protected void onPause() { super.onPause(); savePrefs(); } }
android/src/tw/edu/ttu/wifiautoconnect/WifiAutoConnect.java
package tw.edu.ttu.wifiautoconnect; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.app.Activity; import android.content.SharedPreferences; public class WifiAutoConnect extends Activity { public static final String PREF = "ACCOUNT_PREF"; public static final String PREF_USERNAME = "USERNAME"; public static final String PREF_PWD = "PASSWORD"; EditText usernameEditText; EditText passwordEditText; CheckBox showPasswordCheckBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi_auto_connect); usernameEditText = (EditText) findViewById(R.id.et_username); passwordEditText = (EditText) findViewById(R.id.et_password); showPasswordCheckBox = (CheckBox) findViewById(R.id.cb_showpwd); restorePrefs(); } public void showPasswordCheckBoxOnclick(View view) { if (showPasswordCheckBox.isChecked()) { passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } public void loginBthOnclick(View view) { } private void restorePrefs() { SharedPreferences setting = getSharedPreferences(PREF, 0); String username = setting.getString(PREF_USERNAME, ""); String password = setting.getString(PREF_PWD, ""); usernameEditText.setText(username); passwordEditText.setText(password); } private void savePrefs() { SharedPreferences setting = getSharedPreferences(PREF, 0); setting.edit() .putString(PREF_USERNAME, usernameEditText.getText().toString()) .putString(PREF_PWD, passwordEditText.getText().toString()) .commit(); } @Override protected void onPause() { super.onPause(); savePrefs(); } }
private UI object
android/src/tw/edu/ttu/wifiautoconnect/WifiAutoConnect.java
private UI object
Java
epl-1.0
0c9ba914cea89cc427132dfb3237cad4efa64f22
0
amolenaar/fitnesse,amolenaar/fitnesse,amolenaar/fitnesse
package fitnesse.components; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * Gets a class loader which extends the class path with jars found in "plugins" directory. */ public class PluginsClassLoader { public static ClassLoader getClassLoader(String rootPath) throws IOException { ClassLoader result = ClassLoader.getSystemClassLoader(); File pluginsDirectory = new File(rootPath, "plugins"); List<String> plugins = pluginJars(pluginsDirectory); if (!plugins.isEmpty()) { URL[] urls = urlsForPlugins(plugins); result = new URLClassLoader(urls, result); appendPluginsToClassPathProperty(plugins); } return result; } private static List<String> pluginJars(File pluginsDirectory) throws IOException { List<String> result = new ArrayList<>(); if (pluginsDirectory.exists() && pluginsDirectory.isDirectory()) { for (File plugin : pluginsDirectory.listFiles()) { if (plugin.getName().endsWith("jar")) { result.add(plugin.getCanonicalPath()); } } } return result; } private static URL[] urlsForPlugins(List<String> plugins) throws MalformedURLException { URL[] urls = new URL[plugins.size()]; int i = 0; for (String plugin : plugins) { urls[i] = toUrl(plugin); i++; } return urls; } private static URL toUrl(String fileName) throws MalformedURLException { return new File(fileName).toURI().toURL(); } private static void appendPluginsToClassPathProperty(List<String> plugins) { String currentClassPath = System.getProperty("java.class.path"); StringBuilder classpathItems = new StringBuilder(); classpathItems.append(currentClassPath); for (String plugin : plugins) { classpathItems.append(File.pathSeparator); classpathItems.append(plugin); } System.setProperty("java.class.path", classpathItems.toString()); } }
src/fitnesse/components/PluginsClassLoader.java
package fitnesse.components; import java.io.File; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * Update the current thread class path with jars foundin a "plugins" directory. */ public class PluginsClassLoader { public static ClassLoader getClassLoader(String rootPath) throws Exception { ClassLoader result = ClassLoader.getSystemClassLoader(); File pluginsDirectory = new File(rootPath, "plugins"); URL[] urls = urlsForPlugins(pluginsDirectory); if (urls.length > 0) { result = new URLClassLoader(urls, result); } return result; } private static URL[] urlsForPlugins(File pluginsDirectory) throws Exception { List<URL> urls = new ArrayList<>(); if (pluginsDirectory.exists() && pluginsDirectory.isDirectory()) for (File plugin : pluginsDirectory.listFiles()) if (plugin.getName().endsWith("jar")) urls.addAll(toUrls(plugin.getCanonicalPath())); return urls.toArray(new URL[urls.size()]); } private static List<URL> toUrls(String classpathItems) throws Exception { final String separator = File.pathSeparator; String currentClassPath = System.getProperty("java.class.path"); System.setProperty("java.class.path", currentClassPath + separator + classpathItems); String[] items = classpathItems.split(separator); List<URL> urls = new ArrayList<>(items.length); for (String item : items) { urls.add(toUrl(item)); } return urls; } private static URL toUrl(String fileName) throws MalformedURLException { return new File(fileName).toURI().toURL(); } }
Restructure plugins class loader
src/fitnesse/components/PluginsClassLoader.java
Restructure plugins class loader
Java
agpl-3.0
1fa2a009267b3b18ff8c97135e0afb9ca32feb08
0
ozwillo/ozwillo-kernel,ozwillo/ozwillo-kernel,ozwillo/ozwillo-kernel
package oasis.web.authn; import java.net.URI; import java.security.PublicKey; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Objects; import javax.annotation.Nullable; import javax.inject.Inject; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.auth.openidconnect.IdToken; import com.google.api.client.json.JsonFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.template.soy.data.SoyListData; import com.google.template.soy.data.SoyMapData; import oasis.model.accounts.AccountRepository; import oasis.model.accounts.UserAccount; import oasis.model.applications.v2.AppInstance; import oasis.model.applications.v2.AppInstanceRepository; import oasis.model.applications.v2.Service; import oasis.model.applications.v2.ServiceRepository; import oasis.model.authn.SidToken; import oasis.model.authn.TokenRepository; import oasis.model.bootstrap.ClientIds; import oasis.auth.AuthModule; import oasis.auth.RedirectUri; import oasis.services.cookies.CookieFactory; import oasis.soy.SoyTemplate; import oasis.soy.templates.LogoutSoyInfo; import oasis.soy.templates.LogoutSoyInfo.LogoutSoyTemplateInfo; import oasis.urls.Urls; import oasis.web.resteasy.Resteasy1099; import oasis.web.security.StrictReferer; @User @Path("/a/logout") public class LogoutPage { private static final Logger logger = LoggerFactory.getLogger(LogoutPage.class); @Context SecurityContext securityContext; @Context UriInfo uriInfo; @Inject TokenRepository tokenRepository; @Inject AuthModule.Settings settings; @Inject Urls urls; @Inject JsonFactory jsonFactory; @Inject AppInstanceRepository appInstanceRepository; @Inject ServiceRepository serviceRepository; @Inject AccountRepository accountRepository; @GET @Produces(MediaType.TEXT_HTML) public Response get( @Nullable @QueryParam("id_token_hint") String id_token_hint, @Nullable @QueryParam("post_logout_redirect_uri") String post_logout_redirect_uri, @Nullable @QueryParam("state") String state) { final SidToken sidToken = (securityContext.getUserPrincipal() != null) ? ((UserSessionPrincipal) securityContext.getUserPrincipal()).getSidToken() : null; final IdToken.Payload idTokenHint = parseIdTokenHint(id_token_hint, sidToken); post_logout_redirect_uri = Strings.emptyToNull(post_logout_redirect_uri); final AppInstance appInstance; if (idTokenHint != null) { final String client_id = idTokenHint.getAudienceAsList().get(0); appInstance = appInstanceRepository.getAppInstance(client_id); if (appInstance == null) { logger.debug("No app instance for id_token_hint audience: {}", client_id); } } else { appInstance = null; } final Service service; if (appInstance != null && post_logout_redirect_uri != null) { service = serviceRepository.getServiceByPostLogoutRedirectUri(appInstance.getId(), post_logout_redirect_uri); if (service == null) { logger.debug("No service found for id_token_hint audience {} and post_logout_redirect_uri {}", appInstance.getId(), post_logout_redirect_uri); } if (service == null && !appInstance.isRedirect_uri_validation_disabled()) { // don't act as an open redirector! post_logout_redirect_uri = null; } } else { service = null; // don't act as an open redirector! post_logout_redirect_uri = null; } // Note: validate the URI even if it's in the whitelist, just in case. You can never be too careful. if (post_logout_redirect_uri != null && !RedirectUri.isValid(post_logout_redirect_uri)) { logger.debug("Invalid post_logout_redirect_uri {}", post_logout_redirect_uri); post_logout_redirect_uri = null; } if (post_logout_redirect_uri != null && !Strings.isNullOrEmpty(state)) { post_logout_redirect_uri = new RedirectUri(post_logout_redirect_uri) .setState(state) .toString(); } if (securityContext.getUserPrincipal() == null) { // Not authenticated (we'll assume the user already signed out but the app didn't caught it up) return redirectTo(post_logout_redirect_uri != null ? URI.create(post_logout_redirect_uri) : null); } UserAccount account = accountRepository.getUserAccountById(sidToken.getAccountId()); SoyMapData viewModel = new SoyMapData(); viewModel.put(LogoutSoyTemplateInfo.FORM_ACTION, UriBuilder.fromResource(LogoutPage.class).build().toString()); if (post_logout_redirect_uri != null) { viewModel.put(LogoutSoyTemplateInfo.CONTINUE, post_logout_redirect_uri); } if (appInstance != null) { viewModel.put(LogoutSoyTemplateInfo.APP_NAME, appInstance.getName().get(account.getLocale())); } // FIXME: services don't all have a service_uri for now so we need to workaround it. if (service != null && !Strings.isNullOrEmpty(service.getService_uri())) { viewModel.put(LogoutSoyTemplateInfo.SERVICE_URL, service.getService_uri()); } ArrayList<String> otherApps = new ArrayList<>(); for (AppInstance otherAppInstance : appInstanceRepository.getAppInstances(tokenRepository.getAllClientsForSession(sidToken.getId()))) { if (otherAppInstance == null) { // that shouldn't happen, but we don't want to break if that's the case continue; } otherApps.add(otherAppInstance.getName().get(account.getLocale())); } Collections.sort(otherApps, Collator.getInstance(account.getLocale())); viewModel.put(LogoutSoyTemplateInfo.OTHER_APPS, new SoyListData(otherApps)); viewModel.put(LogoutSoyTemplateInfo.IS_PORTAL, appInstance != null && appInstance.getId().equals(ClientIds.PORTAL)); // FIXME: this should probably be a different URL, make it configurable if (urls.landingPage().isPresent()) { viewModel.put(LogoutSoyTemplateInfo.PORTAL_URL, urls.landingPage().get().toString()); } return Response.ok(new SoyTemplate(LogoutSoyInfo.LOGOUT, account.getLocale(), viewModel)).build(); } private Response redirectTo(@Nullable URI continueUrl) { if (continueUrl == null) { continueUrl = LoginPage.defaultContinueUrl(urls.landingPage(), uriInfo); } return Response.seeOther(continueUrl).build(); } @VisibleForTesting @Nullable private IdToken.Payload parseIdTokenHint(@Nullable String idTokenHint, @Nullable SidToken sidToken) { return parseIdTokenHint(jsonFactory, settings.keyPair.getPublic(), Resteasy1099.getBaseUri(uriInfo).toString(), idTokenHint, sidToken); } @VisibleForTesting @Nullable static IdToken.Payload parseIdTokenHint(JsonFactory jsonFactory, PublicKey publicKey, String issuer, @Nullable String idTokenHint, @Nullable SidToken sidToken) { if (idTokenHint == null) { return null; } try { IdToken idToken = IdToken.parse(jsonFactory, idTokenHint); if (!idToken.verifySignature(publicKey)) { logger.debug("Bad signature for id_token_hint: {}", idTokenHint); return null; } if (!idToken.verifyIssuer(issuer)) { logger.debug("Bad issuer for id_token_hint (expected: {}, actual: {})", issuer, idToken.getPayload().getIssuer()); return null; } IdToken.Payload payload = idToken.getPayload(); if (payload.getAudience() == null) { logger.debug("Missing audience in id_token_hint: {}", idTokenHint); return null; } // there must be an audience assert payload.getAudienceAsList() != null && !payload.getAudienceAsList().isEmpty(); if (sidToken != null && !sidToken.getAccountId().equals(payload.getSubject())) { // The app asked to sign-out another session (we'll assume the user already signed out –and // signed in again– but the app didn't caught it up) logger.debug("Mismatching subject in id_token_hint (expected: {}, actual: {})", sidToken.getAccountId(), payload.getSubject()); return null; } return payload; } catch (Exception e) { logger.debug("Error parsing id_token_hint", e); return null; } } @POST @Authenticated @StrictReferer public Response post(@FormParam("continue") URI continueUrl) { if (continueUrl == null) { continueUrl = LoginPage.defaultContinueUrl(urls.landingPage(), uriInfo); } final SidToken sidToken = ((UserSessionPrincipal) securityContext.getUserPrincipal()).getSidToken(); boolean tokenRevoked = tokenRepository.revokeToken(sidToken.getId()); if (!tokenRevoked) { logger.error("No SidToken was found when trying to revoke it."); } return Response.seeOther(continueUrl) .cookie(CookieFactory.createExpiredCookie(UserFilter.COOKIE_NAME, securityContext.isSecure())) .build(); } }
oasis-webapp/src/main/java/oasis/web/authn/LogoutPage.java
package oasis.web.authn; import java.net.URI; import java.security.PublicKey; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Objects; import javax.annotation.Nullable; import javax.inject.Inject; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.auth.openidconnect.IdToken; import com.google.api.client.json.JsonFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.template.soy.data.SoyListData; import com.google.template.soy.data.SoyMapData; import oasis.model.accounts.AccountRepository; import oasis.model.accounts.UserAccount; import oasis.model.applications.v2.AppInstance; import oasis.model.applications.v2.AppInstanceRepository; import oasis.model.applications.v2.Service; import oasis.model.applications.v2.ServiceRepository; import oasis.model.authn.SidToken; import oasis.model.authn.TokenRepository; import oasis.model.bootstrap.ClientIds; import oasis.auth.AuthModule; import oasis.auth.RedirectUri; import oasis.services.cookies.CookieFactory; import oasis.soy.SoyTemplate; import oasis.soy.templates.LogoutSoyInfo; import oasis.soy.templates.LogoutSoyInfo.LogoutSoyTemplateInfo; import oasis.urls.Urls; import oasis.web.resteasy.Resteasy1099; import oasis.web.security.StrictReferer; @User @Path("/a/logout") public class LogoutPage { private static final Logger logger = LoggerFactory.getLogger(LogoutPage.class); @Context SecurityContext securityContext; @Context UriInfo uriInfo; @Inject TokenRepository tokenRepository; @Inject AuthModule.Settings settings; @Inject Urls urls; @Inject JsonFactory jsonFactory; @Inject AppInstanceRepository appInstanceRepository; @Inject ServiceRepository serviceRepository; @Inject AccountRepository accountRepository; @GET @Produces(MediaType.TEXT_HTML) public Response get( @Nullable @QueryParam("id_token_hint") String id_token_hint, @Nullable @QueryParam("post_logout_redirect_uri") String post_logout_redirect_uri, @Nullable @QueryParam("state") String state) { final SidToken sidToken = (securityContext.getUserPrincipal() != null) ? ((UserSessionPrincipal) securityContext.getUserPrincipal()).getSidToken() : null; final IdToken.Payload idTokenHint = parseIdTokenHint(id_token_hint, sidToken); post_logout_redirect_uri = Strings.emptyToNull(post_logout_redirect_uri); final AppInstance appInstance; if (idTokenHint != null) { final String client_id = idTokenHint.getAudienceAsList().get(0); appInstance = appInstanceRepository.getAppInstance(client_id); if (appInstance == null) { logger.debug("No app instance for id_token_hint audience: {}", client_id); } } else { appInstance = null; } final Service service; if (appInstance != null && post_logout_redirect_uri != null) { service = serviceRepository.getServiceByPostLogoutRedirectUri(appInstance.getId(), post_logout_redirect_uri); if (service == null) { logger.debug("No service found for id_token_hint audience {} and post_logout_redirect_uri {}", appInstance.getId(), post_logout_redirect_uri); } if (service == null && !appInstance.isRedirect_uri_validation_disabled()) { // don't act as an open redirector! post_logout_redirect_uri = null; } } else { service = null; // don't act as an open redirector! post_logout_redirect_uri = null; } // Note: validate the URI even if it's in the whitelist, just in case. You can never be too careful. if (post_logout_redirect_uri != null && !RedirectUri.isValid(post_logout_redirect_uri)) { logger.debug("Invalid post_logout_redirect_uri {}", post_logout_redirect_uri); post_logout_redirect_uri = null; } if (post_logout_redirect_uri != null && !Strings.isNullOrEmpty(state)) { post_logout_redirect_uri = new RedirectUri(post_logout_redirect_uri) .setState(state) .toString(); } if (securityContext.getUserPrincipal() == null) { // Not authenticated (we'll assume the user already signed out but the app didn't caught it up) return redirectTo(post_logout_redirect_uri != null ? URI.create(post_logout_redirect_uri) : null); } UserAccount account = accountRepository.getUserAccountById(sidToken.getAccountId()); SoyMapData viewModel = new SoyMapData(); viewModel.put(LogoutSoyTemplateInfo.FORM_ACTION, UriBuilder.fromResource(LogoutPage.class).build().toString()); if (post_logout_redirect_uri != null) { viewModel.put(LogoutSoyTemplateInfo.CONTINUE, post_logout_redirect_uri); } if (appInstance != null) { viewModel.put(LogoutSoyTemplateInfo.APP_NAME, appInstance.getName().get(account.getLocale())); } // FIXME: services don't all have a service_uri for now so we need to workaround it. if (service != null && !Strings.isNullOrEmpty(service.getService_uri())) { viewModel.put(LogoutSoyTemplateInfo.SERVICE_URL, service.getService_uri()); } ArrayList<String> otherApps = new ArrayList<>(); for (AppInstance otherAppInstance : appInstanceRepository.getAppInstances(tokenRepository.getAllClientsForSession(sidToken.getId()))) { if (otherAppInstance == null) { // that shouldn't happen, but we don't want to break if that's the case continue; } otherApps.add(otherAppInstance.getName().get(account.getLocale())); } Collections.sort(otherApps, Collator.getInstance(account.getLocale())); viewModel.put(LogoutSoyTemplateInfo.OTHER_APPS, new SoyListData(otherApps)); viewModel.put(LogoutSoyTemplateInfo.IS_PORTAL, appInstance != null && appInstance.getId().equals(ClientIds.PORTAL)); // FIXME: this should probably be a different URL, make it configurable viewModel.put(LogoutSoyTemplateInfo.PORTAL_URL, Objects.toString(urls.landingPage().orNull(), null)); return Response.ok(new SoyTemplate(LogoutSoyInfo.LOGOUT, account.getLocale(), viewModel)).build(); } private Response redirectTo(@Nullable URI continueUrl) { if (continueUrl == null) { continueUrl = LoginPage.defaultContinueUrl(urls.landingPage(), uriInfo); } return Response.seeOther(continueUrl).build(); } @VisibleForTesting @Nullable private IdToken.Payload parseIdTokenHint(@Nullable String idTokenHint, @Nullable SidToken sidToken) { return parseIdTokenHint(jsonFactory, settings.keyPair.getPublic(), Resteasy1099.getBaseUri(uriInfo).toString(), idTokenHint, sidToken); } @VisibleForTesting @Nullable static IdToken.Payload parseIdTokenHint(JsonFactory jsonFactory, PublicKey publicKey, String issuer, @Nullable String idTokenHint, @Nullable SidToken sidToken) { if (idTokenHint == null) { return null; } try { IdToken idToken = IdToken.parse(jsonFactory, idTokenHint); if (!idToken.verifySignature(publicKey)) { logger.debug("Bad signature for id_token_hint: {}", idTokenHint); return null; } if (!idToken.verifyIssuer(issuer)) { logger.debug("Bad issuer for id_token_hint (expected: {}, actual: {})", issuer, idToken.getPayload().getIssuer()); return null; } IdToken.Payload payload = idToken.getPayload(); if (payload.getAudience() == null) { logger.debug("Missing audience in id_token_hint: {}", idTokenHint); return null; } // there must be an audience assert payload.getAudienceAsList() != null && !payload.getAudienceAsList().isEmpty(); if (sidToken != null && !sidToken.getAccountId().equals(payload.getSubject())) { // The app asked to sign-out another session (we'll assume the user already signed out –and // signed in again– but the app didn't caught it up) logger.debug("Mismatching subject in id_token_hint (expected: {}, actual: {})", sidToken.getAccountId(), payload.getSubject()); return null; } return payload; } catch (Exception e) { logger.debug("Error parsing id_token_hint", e); return null; } } @POST @Authenticated @StrictReferer public Response post(@FormParam("continue") URI continueUrl) { if (continueUrl == null) { continueUrl = LoginPage.defaultContinueUrl(urls.landingPage(), uriInfo); } final SidToken sidToken = ((UserSessionPrincipal) securityContext.getUserPrincipal()).getSidToken(); boolean tokenRevoked = tokenRepository.revokeToken(sidToken.getId()); if (!tokenRevoked) { logger.error("No SidToken was found when trying to revoke it."); } return Response.seeOther(continueUrl) .cookie(CookieFactory.createExpiredCookie(UserFilter.COOKIE_NAME, securityContext.isSecure())) .build(); } }
Fix NPE when we don't have a landing-page configured. This should only happen in dev, or when the Kernel hasn't been configured. Change-Id: I6f0ad72fab4d02aa949bdedf489794ede8a067d9
oasis-webapp/src/main/java/oasis/web/authn/LogoutPage.java
Fix NPE when we don't have a landing-page configured.
Java
lgpl-2.1
cff2aead105d4ae77fa8f466bfe49a4ec76b8d43
0
SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.eventprocessing; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLException; import javax.media.opengl.awt.GLCanvas; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import net.sf.jaer.chip.AEChip; import net.sf.jaer.graphics.ChipCanvas; import net.sf.jaer.graphics.FrameAnnotater; /** * Adds a mouse adaptor to the basic EventFilter2D to let subclasses more easily * integrate mouse events into their functionality * * @author Tobi */ abstract public class EventFilter2DMouseAdaptor extends EventFilter2D implements MouseListener, MouseMotionListener, FrameAnnotater { protected GLCanvas glCanvas; protected ChipCanvas chipCanvas; private final float CURSOR_SIZE_CHIP_PIXELS = 7; protected GLU glu = new GLU(); protected GLUquadric quad = null; private boolean hasBlendChecked = false, hasBlend = false; public EventFilter2DMouseAdaptor(AEChip chip) { super(chip); if (chip.getCanvas() != null && chip.getCanvas().getCanvas() != null) { glCanvas = (GLCanvas) chip.getCanvas().getCanvas(); } } /** * Annotates the display with the current mouse position to indicate that * mouse is being used. Subclasses can override this functionality. * * @param drawable */ public void annotate(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); chipCanvas = chip.getCanvas(); if (chipCanvas == null) { return; } glCanvas = (GLCanvas) chipCanvas.getCanvas(); if (glCanvas == null) { return; } if (isSelected()) { Point mp = glCanvas.getMousePosition(); Point p = chipCanvas.getPixelFromPoint(mp); if (p == null) { return; } if (!hasBlendChecked) { hasBlendChecked = true; String glExt = gl.glGetString(GL.GL_EXTENSIONS); if (glExt.indexOf("GL_EXT_blend_color") != -1) { hasBlend = true; } } if (hasBlend) { try { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL.GL_FUNC_ADD); } catch (GLException e) { e.printStackTrace(); hasBlend = false; } } gl.glColor4f(1f, 1f, 1f, 1); gl.glLineWidth(3f); gl.glPushMatrix(); gl.glTranslatef(p.x, p.y, 0); gl.glBegin(GL2.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); gl.glTranslatef(.5f, -.5f, 0); gl.glColor4f(0, 0, 0, 1); gl.glBegin(GL2.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); // if (quad == null) { // quad = glu.gluNewQuadric(); // } // glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL); // glu.gluDisk(quad, 0, 3, 32, 1); gl.glPopMatrix(); } chip.getCanvas().checkGLError(gl, glu, "in annotate"); } /** * When this is selected in the FilterPanel GUI, the mouse listeners will be * added. When this is unselected, the listeners will be removed. * */ @Override public void setSelected(boolean yes) { super.setSelected(yes); chipCanvas = chip.getCanvas(); if (chipCanvas == null) { log.warning("null chip canvas, can't add mouse listeners"); return; } glCanvas = (GLCanvas) chipCanvas.getCanvas(); if (glCanvas == null) { log.warning("null chip canvas GL drawable, can't add mouse listeners"); return; } if (yes) { glCanvas.removeMouseListener(this); glCanvas.removeMouseMotionListener(this); glCanvas.addMouseListener(this); glCanvas.addMouseMotionListener(this); } else { glCanvas.removeMouseListener(this); glCanvas.removeMouseMotionListener(this); } } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } /** * Returns the chip pixel position from the MouseEvent. * Note that any calls that modify the GL model matrix (or viewport, etc) will make the location meaningless. * Make sure that your graphics rendering code wraps transforms inside pushMatrix and popMatrix calls. * * @param e the mouse event * @return the pixel position in the chip object, origin 0,0 in lower left * corner. */ protected Point getMousePixel(MouseEvent e) { if (chipCanvas == null) { return null; } Point p = chipCanvas.getPixelFromMouseEvent(e); if (chipCanvas.wasMousePixelInsideChipBounds()) { return p; } else { return null; } } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { chip.getCanvas().repaint(100); } }
src/net/sf/jaer/eventprocessing/EventFilter2DMouseAdaptor.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.eventprocessing; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLException; import javax.media.opengl.awt.GLCanvas; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import net.sf.jaer.chip.AEChip; import net.sf.jaer.graphics.ChipCanvas; import net.sf.jaer.graphics.FrameAnnotater; /** * Adds a mouse adaptor to the basic EventFilter2D to let subclasses more easily * integrate mouse events into their functionality * * @author Tobi */ abstract public class EventFilter2DMouseAdaptor extends EventFilter2D implements MouseListener, MouseMotionListener, FrameAnnotater { protected GLCanvas glCanvas; protected ChipCanvas chipCanvas; private final float CURSOR_SIZE_CHIP_PIXELS = 7; protected GLU glu = new GLU(); protected GLUquadric quad = null; private boolean hasBlendChecked = false, hasBlend = false; public EventFilter2DMouseAdaptor(AEChip chip) { super(chip); if (chip.getCanvas() != null && chip.getCanvas().getCanvas() != null) { glCanvas = (GLCanvas) chip.getCanvas().getCanvas(); } } /** * Annotates the display with the current mouse position to indicate that * mouse is being used. Subclasses can override this functionality. * * @param drawable */ public void annotate(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); chipCanvas = chip.getCanvas(); if (chipCanvas == null) { return; } glCanvas = (GLCanvas) chipCanvas.getCanvas(); if (glCanvas == null) { return; } if (isSelected()) { Point mp = glCanvas.getMousePosition(); Point p = chipCanvas.getPixelFromPoint(mp); if (p == null) { return; } if (!hasBlendChecked) { hasBlendChecked = true; String glExt = gl.glGetString(GL.GL_EXTENSIONS); if (glExt.indexOf("GL_EXT_blend_color") != -1) { hasBlend = true; } } if (hasBlend) { try { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL.GL_FUNC_ADD); } catch (GLException e) { e.printStackTrace(); hasBlend = false; } } gl.glColor4f(1f, 1f, 1f, 1); gl.glLineWidth(3f); gl.glPushMatrix(); gl.glTranslatef(p.x, p.y, 0); gl.glBegin(GL2.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); gl.glTranslatef(.5f, -.5f, 0); gl.glColor4f(0, 0, 0, 1); gl.glBegin(GL2.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); // if (quad == null) { // quad = glu.gluNewQuadric(); // } // glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL); // glu.gluDisk(quad, 0, 3, 32, 1); gl.glPopMatrix(); } chip.getCanvas().checkGLError(gl, glu, "in annotate"); } /** * When this is selected in the FilterPanel GUI, the mouse listeners will be * added. When this is unselected, the listeners will be removed. * */ @Override public void setSelected(boolean yes) { super.setSelected(yes); chipCanvas = chip.getCanvas(); if (chipCanvas == null) { log.warning("null chip canvas, can't add mouse listeners"); return; } glCanvas = (GLCanvas) chipCanvas.getCanvas(); if (glCanvas == null) { log.warning("null chip canvas GL drawable, can't add mouse listeners"); return; } if (yes) { glCanvas.removeMouseListener(this); glCanvas.removeMouseMotionListener(this); glCanvas.addMouseListener(this); glCanvas.addMouseMotionListener(this); } else { glCanvas.removeMouseListener(this); glCanvas.removeMouseMotionListener(this); } } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } /** * Returns the chip pixel position from the MouseEvent. * * @param e the mouse event * @return the pixel position in the chip object, origin 0,0 in lower left * corner. */ protected Point getMousePixel(MouseEvent e) { if (chipCanvas == null) { return null; } Point p = chipCanvas.getPixelFromMouseEvent(e); if (chipCanvas.wasMousePixelInsideChipBounds()) { return p; } else { return null; } } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { chip.getCanvas().repaint(100); } }
added note to javadoc to wrap transform calls inside push and pop to use getMousePixel to work properly. git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@5828 b7f4320f-462c-0410-a916-d9f35bb82d52
src/net/sf/jaer/eventprocessing/EventFilter2DMouseAdaptor.java
added note to javadoc to wrap transform calls inside push and pop to use getMousePixel to work properly.
Java
lgpl-2.1
3d30096beffc47d2cf2dc93b37e3d00cd796490a
0
jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.language; import org.languagetool.Language; import org.languagetool.LanguageMaintainedState; import org.languagetool.UserConfig; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.languagemodel.LuceneLanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.neuralnetwork.NeuralNetworkRuleCreator; import org.languagetool.rules.neuralnetwork.Word2VecModel; import org.languagetool.rules.pt.*; import org.languagetool.rules.spelling.hunspell.HunspellRule; import org.languagetool.synthesis.Synthesizer; import org.languagetool.synthesis.pt.PortugueseSynthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.pt.PortugueseHybridDisambiguator; import org.languagetool.tagging.pt.PortugueseTagger; import org.languagetool.tokenizers.SRXSentenceTokenizer; import org.languagetool.tokenizers.SentenceTokenizer; import org.languagetool.tokenizers.Tokenizer; import org.languagetool.tokenizers.pt.PortugueseWordTokenizer; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; /** * Post-spelling-reform Portuguese. */ public class Portuguese extends Language implements AutoCloseable { private static final Language PORTUGAL_PORTUGUESE = new PortugalPortuguese(); private Tagger tagger; private Disambiguator disambiguator; private Tokenizer wordTokenizer; private Synthesizer synthesizer; private SentenceTokenizer sentenceTokenizer; private LuceneLanguageModel languageModel; @Override public String getName() { return "Portuguese"; } @Override public String getShortCode() { return "pt"; } @Override public String[] getCountries() { return new String[]{"", "CV", "GW", "MO", "ST", "TL"}; } @Override public Language getDefaultLanguageVariant() { return PORTUGAL_PORTUGUESE; } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Marco A.G. Pinto", "http://www.marcoagpinto.com/"), new Contributor("Matheus Poletto", "https://github.com/MatheusPoletto"), new Contributor("Tiago F. Santos (3.6+)", "https://github.com/TiagoSantos81") }; } @Override public Tagger getTagger() { if (tagger == null) { tagger = new PortugueseTagger(); } return tagger; } /** * @since 3.6 */ @Override public Disambiguator getDisambiguator() { if (disambiguator == null) { disambiguator = new PortugueseHybridDisambiguator(); } return disambiguator; } /** * @since 3.6 */ @Override public Tokenizer getWordTokenizer() { if (wordTokenizer == null) { wordTokenizer = new PortugueseWordTokenizer(); } return wordTokenizer; } @Override public Synthesizer getSynthesizer() { if (synthesizer == null) { synthesizer = new PortugueseSynthesizer(); } return synthesizer; } @Override public SentenceTokenizer getSentenceTokenizer() { if (sentenceTokenizer == null) { sentenceTokenizer = new SRXSentenceTokenizer(this); } return sentenceTokenizer; } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Tomamos café<marker> ,</marker> queijo, bolachas e uvas."), Example.fixed("Tomamos café<marker>,</marker> queijo, bolachas e uvas.")), new GenericUnpairedBracketsRule(messages, Arrays.asList("[", "(", "{", "\"", "“" /*, "«", "'", "‘" */), Arrays.asList("]", ")", "}", "\"", "”" /*, "»", "'", "’" */)), new HunspellRule(messages, this, userConfig), new LongSentenceRule(messages, userConfig, -1, true), new LongParagraphRule(messages, userConfig), new UppercaseSentenceStartRule(messages, this, Example.wrong("Esta casa é velha. <marker>foi</marker> construida em 1950."), Example.fixed("Esta casa é velha. <marker>Foi</marker> construida em 1950.")), new MultipleWhitespaceRule(messages, this), new SentenceWhitespaceRule(messages), new WhiteSpaceBeforeParagraphEnd(messages), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages), new ParagraphRepeatBeginningRule(messages), new PunctuationMarkAtParagraphEnd(messages), //Specific to Portuguese: new PostReformPortugueseCompoundRule(messages), new PortugueseReplaceRule(messages), new PortugueseBarbarismsRule(messages), new PortugueseClicheRule(messages), new PortugueseFillerWordsRule(messages, userConfig), new PortugueseRedundancyRule(messages), new PortugueseWordinessRule(messages), new PortugueseWeaselWordsRule(messages), new PortugueseWikipediaRule(messages), new PortugueseWordRepeatRule(messages, this), new PortugueseWordRepeatBeginningRule(messages, this), new PortugueseAccentuationCheckRule(messages), new PortugueseWrongWordInContextRule(messages), new PortugueseWordCoherencyRule(messages) ); } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } /** @since 3.6 */ @Override public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException { if (languageModel == null) { languageModel = new LuceneLanguageModel(new File(indexDir, getShortCode())); } return languageModel; } /** @since 3.6 */ @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel) throws IOException { return Arrays.<Rule>asList( new PortugueseConfusionProbabilityRule(messages, languageModel, this) ); } /** @since 4.0 */ @Override public synchronized Word2VecModel getWord2VecModel(File indexDir) throws IOException { return new Word2VecModel(indexDir + File.separator + getShortCode()); } /** @since 4.0 */ @Override public List<Rule> getRelevantWord2VecModelRules(ResourceBundle messages, Word2VecModel word2vecModel) throws IOException { return NeuralNetworkRuleCreator.createRules(messages, this, word2vecModel); } /** @since 3.6 */ @Override public void close() throws Exception { if (languageModel != null) { languageModel.close(); } } @Override public int getPriorityForId(String id) { switch (id) { case "FRAGMENT_TWO_ARTICLES": return 50; case "DEGREE_MINUTES_SECONDS": return 30; case "INTERJECTIONS_PUNTUATION": return 20; case "CONFUSION_POR": return 10; case "HOMOPHONE_AS_CARD": return 5; case "TODOS_FOLLOWED_BY_NOUN_PLURAL": return 3; case "TODOS_FOLLOWED_BY_NOUN_SINGULAR": return 2; case "UNPAIRED_BRACKETS": return -5; case "PROFANITY": return -6; case "PT_BARBARISMS_REPLACE": return -10; case "PT_PT_SIMPLE_REPLACE": return -11; case "PT_REDUNDANCY_REPLACE": return -12; case "PT_WORDINESS_REPLACE": return -13; case "PT_CLICHE_REPLACE": return -17; case "CHILDISH_LANGUAGE": return -25; case "ARCHAISMS": return -26; case "INFORMALITIES": return -27; case "PUFFERY": return -30; case "BIASED_OPINION_WORDS": return -31; case "WEAK_WORDS": return -32; case "PT_AGREEMENT_REPLACE": return -35; case "HUNSPELL_RULE": return -50; case "NO_VERB": return -52; case "CRASE_CONFUSION": return -55; case "FINAL_STOPS": return -75; case "EU_NÓS_REMOVAL": return -90; case "T-V_DISTINCTION": return -100; case "T-V_DISTINCTION_ALL": return -101; case "REPEATED_WORDS": return -210; case "REPEATED_WORDS_3X": return -211; case "PT_WIKIPEDIA_COMMON_ERRORS":return -500; case "FILLER_WORDS_PT": return -990; case LongSentenceRule.RULE_ID: return -997; case LongParagraphRule.RULE_ID: return -998; case "CACOPHONY": return -1500; case "UNKNOWN_WORD": return -2000; } return 0; } }
languagetool-language-modules/pt/src/main/java/org/languagetool/language/Portuguese.java
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.language; import org.languagetool.Language; import org.languagetool.LanguageMaintainedState; import org.languagetool.UserConfig; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.languagemodel.LuceneLanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.neuralnetwork.NeuralNetworkRuleCreator; import org.languagetool.rules.neuralnetwork.Word2VecModel; import org.languagetool.rules.pt.*; import org.languagetool.rules.spelling.hunspell.HunspellRule; import org.languagetool.synthesis.Synthesizer; import org.languagetool.synthesis.pt.PortugueseSynthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.pt.PortugueseHybridDisambiguator; import org.languagetool.tagging.pt.PortugueseTagger; import org.languagetool.tokenizers.SRXSentenceTokenizer; import org.languagetool.tokenizers.SentenceTokenizer; import org.languagetool.tokenizers.Tokenizer; import org.languagetool.tokenizers.pt.PortugueseWordTokenizer; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; /** * Post-spelling-reform Portuguese. */ public class Portuguese extends Language implements AutoCloseable { private static final Language PORTUGAL_PORTUGUESE = new PortugalPortuguese(); private Tagger tagger; private Disambiguator disambiguator; private Tokenizer wordTokenizer; private Synthesizer synthesizer; private SentenceTokenizer sentenceTokenizer; private LuceneLanguageModel languageModel; @Override public String getName() { return "Portuguese"; } @Override public String getShortCode() { return "pt"; } @Override public String[] getCountries() { return new String[]{"", "CV", "GW", "MO", "ST", "TL"}; } @Override public Language getDefaultLanguageVariant() { return PORTUGAL_PORTUGUESE; } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Marco A.G. Pinto", "http://www.marcoagpinto.com/"), new Contributor("Matheus Poletto", "https://github.com/MatheusPoletto"), new Contributor("Tiago F. Santos (3.6+)", "https://github.com/TiagoSantos81") }; } @Override public Tagger getTagger() { if (tagger == null) { tagger = new PortugueseTagger(); } return tagger; } /** * @since 3.6 */ @Override public Disambiguator getDisambiguator() { if (disambiguator == null) { disambiguator = new PortugueseHybridDisambiguator(); } return disambiguator; } /** * @since 3.6 */ @Override public Tokenizer getWordTokenizer() { if (wordTokenizer == null) { wordTokenizer = new PortugueseWordTokenizer(); } return wordTokenizer; } @Override public Synthesizer getSynthesizer() { if (synthesizer == null) { synthesizer = new PortugueseSynthesizer(); } return synthesizer; } @Override public SentenceTokenizer getSentenceTokenizer() { if (sentenceTokenizer == null) { sentenceTokenizer = new SRXSentenceTokenizer(this); } return sentenceTokenizer; } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Tomamos café<marker> ,</marker> queijo, bolachas e uvas."), Example.fixed("Tomamos café<marker>,</marker> queijo, bolachas e uvas.")), new GenericUnpairedBracketsRule(messages, Arrays.asList("[", "(", "{", "\"", "“" /*, "«", "'", "‘" */), Arrays.asList("]", ")", "}", "\"", "”" /*, "»", "'", "’" */)), new HunspellRule(messages, this, userConfig), new LongSentenceRule(messages, userConfig, -1, true), new LongParagraphRule(messages, userConfig), new UppercaseSentenceStartRule(messages, this, Example.wrong("Esta casa é velha. <marker>foi</marker> construida em 1950."), Example.fixed("Esta casa é velha. <marker>Foi</marker> construida em 1950.")), new MultipleWhitespaceRule(messages, this), new SentenceWhitespaceRule(messages), new WhiteSpaceBeforeParagraphEnd(messages), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages), new ParagraphRepeatBeginningRule(messages), new PunctuationMarkAtParagraphEnd(messages), //Specific to Portuguese: new PostReformPortugueseCompoundRule(messages), new PortugueseReplaceRule(messages), new PortugueseBarbarismsRule(messages), new PortugueseClicheRule(messages), new PortugueseFillerWordsRule(messages, userConfig), new PortugueseRedundancyRule(messages), new PortugueseWordinessRule(messages), new PortugueseWeaselWordsRule(messages), new PortugueseWikipediaRule(messages), new PortugueseWordRepeatRule(messages, this), new PortugueseWordRepeatBeginningRule(messages, this), new PortugueseAccentuationCheckRule(messages), new PortugueseWrongWordInContextRule(messages), new PortugueseWordCoherencyRule(messages) ); } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } /** @since 3.6 */ @Override public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException { if (languageModel == null) { languageModel = new LuceneLanguageModel(new File(indexDir, getShortCode())); } return languageModel; } /** @since 3.6 */ @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel) throws IOException { return Arrays.<Rule>asList( new PortugueseConfusionProbabilityRule(messages, languageModel, this) ); } /** @since 4.0 */ @Override public synchronized Word2VecModel getWord2VecModel(File indexDir) throws IOException { return new Word2VecModel(indexDir + File.separator + getShortCode()); } /** @since 4.0 */ @Override public List<Rule> getRelevantWord2VecModelRules(ResourceBundle messages, Word2VecModel word2vecModel) throws IOException { return NeuralNetworkRuleCreator.createRules(messages, this, word2vecModel); } /** @since 3.6 */ @Override public void close() throws Exception { if (languageModel != null) { languageModel.close(); } } @Override public int getPriorityForId(String id) { switch (id) { case "FRAGMENT_TWO_ARTICLES": return 50; case "DEGREE_MINUTES_SECONDS": return 30; case "INTERJECTIONS_PUNTUATION": return 20; case "CONFUSION_POR": return 10; case "HOMOPHONE_AS_CARD": return 5; case "TODOS_FOLLOWED_BY_NOUN_PLURAL": return 3; case "TODOS_FOLLOWED_BY_NOUN_SINGULAR": return 2; case "UNPAIRED_BRACKETS": return -5; case "PROFANITY": return -6; case "PT_BARBARISMS_REPLACE": return -10; case "PT_PT_SIMPLE_REPLACE": return -11; case "PT_REDUNDANCY_REPLACE": return -12; case "PT_WORDINESS_REPLACE": return -13; case "PT_CLICHE_REPLACE": return -17; case "CHILDISH_LANGUAGE": return -25; case "ARCHAISMS": return -26; case "INFORMALITIES": return -27; case "PUFFERY": return -30; case "BIASED_OPINION_WORDS": return -31; case "WEAK_WORDS": return -32; case "PT_AGREEMENT_REPLACE": return -35; case "HUNSPELL_RULE": return -50; case "NO_VERB": return -52; case "CRASE_CONFUSION": return -55; case "FINAL_STOPS": return -75; case "EU_NÓS_REMOVAL": return -90; case "T-V_DISTINCTION": return -100; case "T-V_DISTINCTION_ALL": return -101; case "REPEATED_WORDS": return -210; case "REPEATED_WORDS_3X": return -211; case "PT_WIKIPEDIA_COMMON_ERRORS":return -500; case "FILLER_WORDS_PT": return -990; case LongSentenceRule.RULE_ID: return -997; case LongParagraphRule.RULE_ID: return -998; case "CACOPHONY": return -2000; } return 0; } }
[pt] add rule priority
languagetool-language-modules/pt/src/main/java/org/languagetool/language/Portuguese.java
[pt] add rule priority
Java
lgpl-2.1
5cbde1b45635b63f8302476e0ceadada01f6123a
0
samskivert/samskivert,samskivert/samskivert
// // $Id$ // // samskivert library - useful routines for java programs // Copyright (C) 2001-2010 Michael Bayne, et al. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import com.samskivert.annotation.ReplacedBy; /** * A collection of collection-related utility functions. */ public class CollectionUtil { /** * Adds all items returned by the enumeration to the supplied collection * and returns the supplied collection. */ @ReplacedBy("com.google.common.collect.Iterators#addAll(Collection, com.google.common.collect.Iterators#forEnumeration(Enumeration))") public static <T, C extends Collection<T>> C addAll (C col, Enumeration<? extends T> enm) { while (enm.hasMoreElements()) { col.add(enm.nextElement()); } return col; } /** * Adds all items returned by the iterator to the supplied collection and * returns the supplied collection. */ @ReplacedBy("com.google.common.collect.Iterators#addAll()") public static <T, C extends Collection<T>> C addAll (C col, Iterator<? extends T> iter) { while (iter.hasNext()) { col.add(iter.next()); } return col; } /** * Adds all items in the given object array to the supplied collection and * returns the supplied collection. If the supplied array is null, nothing * is added to the collection. */ @ReplacedBy("java.util.Collections#addAll()") public static <T, E extends T, C extends Collection<T>> C addAll (C col, E[] values) { if (values != null) { for (E value : values) { col.add(value); } } return col; } /** * Folds all the specified values into the supplied collection and returns it. */ public static <T, C extends Collection<T>> C addAll ( C col, Iterable<? extends Collection<? extends T>> values) { for (Collection<? extends T> val : values) { col.addAll(val); } return col; } /** * Folds all the specified values into the supplied map and returns it. */ public static <K, V, M extends Map<K, V>> M putAll ( M map, Iterable<? extends Map<? extends K, ? extends V>> values) { for (Map<? extends K, ? extends V> val : values) { map.putAll(val); } return map; } /** * Modify the specified Collection so that only the first <code>limit</code> elements * remain, as determined by iteration order. If the Collection is smaller than limit, * it is unmodified. */ public static void limit (Collection<?> col, int limit) { int size = col.size(); if (size > limit) { if (col instanceof List<?>) { ((List<?>) col).subList(limit, size).clear(); } else { Iterator<?> itr = col.iterator(); for (int ii = 0; ii < limit; ii++) { itr.next(); } while (itr.hasNext()) { itr.next(); itr.remove(); } } } } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the maximum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T extends Comparable<? super T>> List<T> maxList (Iterable<? extends T> iterable) { return maxList(iterable, new Comparator<T>() { public int compare (T o1, T o2) { return o1.compareTo(o2); } }); } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the maximum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T> List<T> maxList (Iterable<? extends T> iterable, Comparator<? super T> comp) { Iterator<? extends T> itr = iterable.iterator(); T max = itr.next(); List<T> maxes = new ArrayList<T>(); maxes.add(max); if (itr.hasNext()) { do { T elem = itr.next(); int cmp = comp.compare(max, elem); if (cmp <= 0) { if (cmp < 0) { max = elem; maxes.clear(); } maxes.add(elem); } } while (itr.hasNext()); } else if (0 != comp.compare(max, max)) { // The main point of this test is to compare the sole element to something, // in case it turns out to be incompatible with the Comparator for some reason. // In that case, we don't even get to this IAE, we've probably already bombed out // with an NPE or CCE. For example, the Comparable version could be called with // a sole element of null. (Collections.max() gets this wrong.) throw new IllegalArgumentException(); } return maxes; } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the minimum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T extends Comparable<? super T>> List<T> minList (Iterable<? extends T> iterable) { return maxList(iterable, java.util.Collections.reverseOrder()); } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the minimum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T> List<T> minList (Iterable<? extends T> iterable, Comparator<? super T> comp) { return maxList(iterable, java.util.Collections.reverseOrder(comp)); } /** * Returns a list containing a random selection of elements from the * specified collection. The total number of elements selected will be * equal to <code>count</code>, each element in the source collection will * be selected with equal probability and no element will be included more * than once. The elements in the random subset will always be included in * the order they are returned from the source collection's iterator. * * <p> Algorithm courtesy of William R. Mahoney, published in * <cite>Dr. Dobbs Journal, February 2002</cite>. * * @exception IllegalArgumentException thrown if the size of the collection * is smaller than the number of elements requested for the random subset. */ public static <T> List<T> selectRandomSubset (Collection<T> col, int count) { int csize = col.size(); if (csize < count) { String errmsg = "Cannot select " + count + " elements " + "from a collection of only " + csize + " elements."; throw new IllegalArgumentException(errmsg); } ArrayList<T> subset = new ArrayList<T>(count); Iterator<T> iter = col.iterator(); int s = 0; for (int k = 0; iter.hasNext(); k++) { T elem = iter.next(); // the probability that an element is select for inclusion in our // random subset is proportional to the number of elements // remaining to be checked for inclusion divided by the number of // elements remaining to be included float limit = ((float)(count - s)) / ((float)(csize - k)); // include the record if our random value is below the limit if (Math.random() < limit) { subset.add(elem); // stop looking if we've reached our target size if (++s == count) { break; } } } return subset; } /** * Returns an Array, of the type specified by the runtime-type token <code>type</code>, * containing the elements of the collection. */ @ReplacedBy("com.google.common.collect.Iterables#toArray()") public static <T> T[] toArray (Collection<? extends T> col, Class<T> type) { @SuppressWarnings("unchecked") T[] array = (T[]) Array.newInstance(type, col.size()); return col.toArray(array); } /** * If a collection contains only <code>Integer</code> objects, it can be * passed to this function and converted into an int array. * * @param col the collection to be converted. * * @return an int array containing the contents of the collection (in the * order returned by the collection's iterator). The size of the array will * be equal to the size of the collection. */ @ReplacedBy("com.google.common.primitives.Ints#toArray()") public static int[] toIntArray (Collection<Integer> col) { Iterator<Integer> iter = col.iterator(); int[] array = new int[col.size()]; for (int i = 0; iter.hasNext(); i++) { array[i] = iter.next().intValue(); } return array; } }
src/main/java/com/samskivert/util/CollectionUtil.java
// // $Id$ // // samskivert library - useful routines for java programs // Copyright (C) 2001-2010 Michael Bayne, et al. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import com.samskivert.annotation.ReplacedBy; /** * A collection of collection-related utility functions. */ public class CollectionUtil { /** * Adds all items returned by the enumeration to the supplied collection * and returns the supplied collection. */ @ReplacedBy("com.google.common.collect.Iterators#addAll(Collection, com.google.common.collect.Iterators#forEnumeration(Enumeration))") public static <T, C extends Collection<T>> C addAll (C col, Enumeration<? extends T> enm) { while (enm.hasMoreElements()) { col.add(enm.nextElement()); } return col; } /** * Adds all items returned by the iterator to the supplied collection and * returns the supplied collection. */ @ReplacedBy("com.google.common.collect.Iterators#addAll()") public static <T, C extends Collection<T>> C addAll (C col, Iterator<? extends T> iter) { while (iter.hasNext()) { col.add(iter.next()); } return col; } /** * Adds all items in the given object array to the supplied collection and * returns the supplied collection. If the supplied array is null, nothing * is added to the collection. */ @ReplacedBy("java.util.Collections#addAll()") public static <T, E extends T, C extends Collection<T>> C addAll (C col, E[] values) { if (values != null) { for (E value : values) { col.add(value); } } return col; } /** * Modify the specified Collection so that only the first <code>limit</code> elements * remain, as determined by iteration order. If the Collection is smaller than limit, * it is unmodified. */ public static void limit (Collection<?> col, int limit) { int size = col.size(); if (size > limit) { if (col instanceof List<?>) { ((List<?>) col).subList(limit, size).clear(); } else { Iterator<?> itr = col.iterator(); for (int ii = 0; ii < limit; ii++) { itr.next(); } while (itr.hasNext()) { itr.next(); itr.remove(); } } } } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the maximum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T extends Comparable<? super T>> List<T> maxList (Iterable<? extends T> iterable) { return maxList(iterable, new Comparator<T>() { public int compare (T o1, T o2) { return o1.compareTo(o2); } }); } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the maximum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T> List<T> maxList (Iterable<? extends T> iterable, Comparator<? super T> comp) { Iterator<? extends T> itr = iterable.iterator(); T max = itr.next(); List<T> maxes = new ArrayList<T>(); maxes.add(max); if (itr.hasNext()) { do { T elem = itr.next(); int cmp = comp.compare(max, elem); if (cmp <= 0) { if (cmp < 0) { max = elem; maxes.clear(); } maxes.add(elem); } } while (itr.hasNext()); } else if (0 != comp.compare(max, max)) { // The main point of this test is to compare the sole element to something, // in case it turns out to be incompatible with the Comparator for some reason. // In that case, we don't even get to this IAE, we've probably already bombed out // with an NPE or CCE. For example, the Comparable version could be called with // a sole element of null. (Collections.max() gets this wrong.) throw new IllegalArgumentException(); } return maxes; } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the minimum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T extends Comparable<? super T>> List<T> minList (Iterable<? extends T> iterable) { return maxList(iterable, java.util.Collections.reverseOrder()); } /** * Return a List containing all the elements of the specified Iterable that compare as being * equal to the minimum element. * * @throws NoSuchElementException if the Iterable is empty. */ public static <T> List<T> minList (Iterable<? extends T> iterable, Comparator<? super T> comp) { return maxList(iterable, java.util.Collections.reverseOrder(comp)); } /** * Returns a list containing a random selection of elements from the * specified collection. The total number of elements selected will be * equal to <code>count</code>, each element in the source collection will * be selected with equal probability and no element will be included more * than once. The elements in the random subset will always be included in * the order they are returned from the source collection's iterator. * * <p> Algorithm courtesy of William R. Mahoney, published in * <cite>Dr. Dobbs Journal, February 2002</cite>. * * @exception IllegalArgumentException thrown if the size of the collection * is smaller than the number of elements requested for the random subset. */ public static <T> List<T> selectRandomSubset (Collection<T> col, int count) { int csize = col.size(); if (csize < count) { String errmsg = "Cannot select " + count + " elements " + "from a collection of only " + csize + " elements."; throw new IllegalArgumentException(errmsg); } ArrayList<T> subset = new ArrayList<T>(count); Iterator<T> iter = col.iterator(); int s = 0; for (int k = 0; iter.hasNext(); k++) { T elem = iter.next(); // the probability that an element is select for inclusion in our // random subset is proportional to the number of elements // remaining to be checked for inclusion divided by the number of // elements remaining to be included float limit = ((float)(count - s)) / ((float)(csize - k)); // include the record if our random value is below the limit if (Math.random() < limit) { subset.add(elem); // stop looking if we've reached our target size if (++s == count) { break; } } } return subset; } /** * Returns an Array, of the type specified by the runtime-type token <code>type</code>, * containing the elements of the collection. */ @ReplacedBy("com.google.common.collect.Iterables#toArray()") public static <T> T[] toArray (Collection<? extends T> col, Class<T> type) { @SuppressWarnings("unchecked") T[] array = (T[]) Array.newInstance(type, col.size()); return col.toArray(array); } /** * If a collection contains only <code>Integer</code> objects, it can be * passed to this function and converted into an int array. * * @param col the collection to be converted. * * @return an int array containing the contents of the collection (in the * order returned by the collection's iterator). The size of the array will * be equal to the size of the collection. */ @ReplacedBy("com.google.common.primitives.Ints#toArray()") public static int[] toIntArray (Collection<Integer> col) { Iterator<Integer> iter = col.iterator(); int[] array = new int[col.size()]; for (int i = 0; iter.hasNext(); i++) { array[i] = iter.next().intValue(); } return array; } }
Created an addAll() that folds a supplied Iterable of Collections into the starter collection using addAll. Certain Collections, like guava's Multiset have optimized addAll() methods that recognize other Multisets. There is also a putAll() equivalent for Maps. git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@2891 6335cc39-0255-0410-8fd6-9bcaacd3b74c
src/main/java/com/samskivert/util/CollectionUtil.java
Created an addAll() that folds a supplied Iterable of Collections into the starter collection using addAll. Certain Collections, like guava's Multiset have optimized addAll() methods that recognize other Multisets. There is also a putAll() equivalent for Maps.
Java
lgpl-2.1
99d5ecb10002f2c343dff93598db480da327b92e
0
jolie/jolie,jolie/jolie,jolie/jolie
/*************************************************************************** * Copyright (C) 2006-2011 by Fabrizio Montesi <famontesi@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * For details about the authors of this software, see the AUTHORS file. * ***************************************************************************/ package jolie.lang.parse; import java.util.Collection; import jolie.lang.parse.context.ParsingContext; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Logger; import jolie.lang.Constants.ExecutionMode; import jolie.lang.Constants.OperandType; import jolie.lang.parse.CorrelationFunctionInfo.CorrelationPairInfo; import jolie.lang.parse.ast.AddAssignStatement; import jolie.lang.parse.ast.AndConditionNode; import jolie.lang.parse.ast.AssignStatement; import jolie.lang.parse.ast.DocumentationComment; import jolie.lang.parse.ast.CompareConditionNode; import jolie.lang.parse.ast.CompensateStatement; import jolie.lang.parse.ast.ConstantIntegerExpression; import jolie.lang.parse.ast.ConstantRealExpression; import jolie.lang.parse.ast.ConstantStringExpression; import jolie.lang.parse.ast.CorrelationSetInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationAliasInfo; import jolie.lang.parse.ast.CurrentHandlerStatement; import jolie.lang.parse.ast.DeepCopyStatement; import jolie.lang.parse.ast.EmbeddedServiceNode; import jolie.lang.parse.ast.ExecutionInfo; import jolie.lang.parse.ast.ExitStatement; import jolie.lang.parse.ast.ExpressionConditionNode; import jolie.lang.parse.ast.ForEachStatement; import jolie.lang.parse.ast.ForStatement; import jolie.lang.parse.ast.IfStatement; import jolie.lang.parse.ast.InstallFixedVariableExpressionNode; import jolie.lang.parse.ast.InstallStatement; import jolie.lang.parse.ast.IsTypeExpressionNode; import jolie.lang.parse.ast.LinkInStatement; import jolie.lang.parse.ast.LinkOutStatement; import jolie.lang.parse.ast.NDChoiceStatement; import jolie.lang.parse.ast.NotConditionNode; import jolie.lang.parse.ast.NotificationOperationStatement; import jolie.lang.parse.ast.NullProcessStatement; import jolie.lang.parse.ast.OLSyntaxNode; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OneWayOperationStatement; import jolie.lang.parse.ast.OperationDeclaration; import jolie.lang.parse.ast.OrConditionNode; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.ParallelStatement; import jolie.lang.parse.ast.PointerStatement; import jolie.lang.parse.ast.PostDecrementStatement; import jolie.lang.parse.ast.PostIncrementStatement; import jolie.lang.parse.ast.PreDecrementStatement; import jolie.lang.parse.ast.PreIncrementStatement; import jolie.lang.parse.ast.ProductExpressionNode; import jolie.lang.parse.ast.Program; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.RequestResponseOperationStatement; import jolie.lang.parse.ast.RunStatement; import jolie.lang.parse.ast.Scope; import jolie.lang.parse.ast.SequenceStatement; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.SolicitResponseOperationStatement; import jolie.lang.parse.ast.DefinitionCallStatement; import jolie.lang.parse.ast.DefinitionNode; import jolie.lang.parse.ast.DivideAssignStatement; import jolie.lang.parse.ast.InterfaceDefinition; import jolie.lang.parse.ast.SubtractAssignStatement; import jolie.lang.parse.ast.MultiplyAssignStatement; import jolie.lang.parse.ast.SpawnStatement; import jolie.lang.parse.ast.SumExpressionNode; import jolie.lang.parse.ast.SynchronizedStatement; import jolie.lang.parse.ast.ThrowStatement; import jolie.lang.parse.ast.TypeCastExpressionNode; import jolie.lang.parse.ast.UndefStatement; import jolie.lang.parse.ast.ValueVectorSizeExpressionNode; import jolie.lang.parse.ast.VariableExpressionNode; import jolie.lang.parse.ast.VariablePathNode; import jolie.lang.parse.ast.WhileStatement; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.lang.parse.ast.types.TypeDefinitionLink; import jolie.lang.parse.ast.types.TypeInlineDefinition; import jolie.lang.parse.context.URIParsingContext; import jolie.util.ArrayListMultiMap; import jolie.util.MultiMap; import jolie.util.Pair; /** * Checks the well-formedness and validity of a JOLIE program. * @see Program * @author Fabrizio Montesi */ public class SemanticVerifier implements OLVisitor { public static class Configuration { public boolean checkForMain = true; } private final Program program; private boolean valid = true; private final Configuration configuration; private ExecutionInfo executionInfo = new ExecutionInfo( URIParsingContext.DEFAULT, ExecutionMode.SINGLE ); private final Map< String, InputPortInfo > inputPorts = new HashMap< String, InputPortInfo >(); private final Map< String, OutputPortInfo > outputPorts = new HashMap< String, OutputPortInfo >(); private final Set< String > subroutineNames = new HashSet< String > (); private final Map< String, OneWayOperationDeclaration > oneWayOperations = new HashMap< String, OneWayOperationDeclaration >(); private final Map< String, RequestResponseOperationDeclaration > requestResponseOperations = new HashMap< String, RequestResponseOperationDeclaration >(); private final Map< TypeDefinition, List< TypeDefinition > > typesToBeEqual = new HashMap< TypeDefinition, List< TypeDefinition > >(); private final Map< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > owToBeEqual = new HashMap< OneWayOperationDeclaration, List< OneWayOperationDeclaration > >(); private final Map< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > rrToBeEqual = new HashMap< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > >(); private final List< CorrelationSetInfo > correlationSets = new LinkedList< CorrelationSetInfo >(); private boolean insideInputPort = false; private boolean insideInit = false; private boolean mainDefined = false; private CorrelationFunctionInfo correlationFunctionInfo = new CorrelationFunctionInfo(); private final MultiMap< String, String > inputTypeNameMap = new ArrayListMultiMap< String, String >(); // Maps type names to the input operations that use them private ExecutionMode executionMode = ExecutionMode.SINGLE; private static final Logger logger = Logger.getLogger( "JOLIE" ); private final Map< String, TypeDefinition > definedTypes; private final List< TypeDefinitionLink > definedTypeLinks = new LinkedList< TypeDefinitionLink >(); //private TypeDefinition rootType; // the type representing the whole session state private final Map< String, Boolean > isConstantMap = new HashMap< String, Boolean >(); public SemanticVerifier( Program program, Configuration configuration ) { this.program = program; this.definedTypes = OLParser.createTypeDeclarationMap( program.context() ); this.configuration = configuration; /*rootType = new TypeInlineDefinition( new ParsingContext(), "#RootType", NativeType.VOID, jolie.lang.Constants.RANGE_ONE_TO_ONE );*/ } public SemanticVerifier( Program program ) { this( program, new Configuration() ); } public CorrelationFunctionInfo correlationFunctionInfo() { return correlationFunctionInfo; } public ExecutionMode executionMode() { return executionMode; } private void encounteredAssignment( String varName ) { if ( isConstantMap.containsKey( varName ) ) { isConstantMap.put( varName, false ); } else { isConstantMap.put( varName, true ); } } private void addTypeEqualnessCheck( TypeDefinition key, TypeDefinition type ) { List< TypeDefinition > toBeEqualList = typesToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList< TypeDefinition >(); typesToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( type ); } private void addOneWayEqualnessCheck( OneWayOperationDeclaration key, OneWayOperationDeclaration oneWay ) { List< OneWayOperationDeclaration > toBeEqualList = owToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList< OneWayOperationDeclaration >(); owToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( oneWay ); } private void addRequestResponseEqualnessCheck( RequestResponseOperationDeclaration key, RequestResponseOperationDeclaration requestResponse ) { List< RequestResponseOperationDeclaration > toBeEqualList = rrToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList< RequestResponseOperationDeclaration >(); rrToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( requestResponse ); } private void encounteredAssignment( VariablePathNode path ) { encounteredAssignment( ((ConstantStringExpression)path.path().get( 0 ).key()).value() ); } public Map< String, Boolean > isConstantMap() { return isConstantMap; } private void warning( OLSyntaxNode node, String message ) { if ( node == null ) { logger.warning( message ); } else { logger.warning( node.context().sourceName() + ":" + node.context().line() + ": " + message ); } } private void error( OLSyntaxNode node, String message ) { valid = false; if ( node != null ) { ParsingContext context = node.context(); logger.severe( context.sourceName() + ":" + context.line() + ": " + message ); } else { logger.severe( message ); } } private void resolveLazyLinks() { for( TypeDefinitionLink l : definedTypeLinks ) { l.setLinkedType( definedTypes.get( l.linkedTypeName() ) ); if ( l.linkedType() == null ) { error( l, "type " + l.id() + "points to an undefined type (" + l.linkedTypeName() + ")" ); } } } private void checkToBeEqualTypes() { for( Entry< TypeDefinition, List< TypeDefinition > > entry : typesToBeEqual.entrySet() ) { for( TypeDefinition type : entry.getValue() ) { if ( entry.getKey().isEquivalentTo( type ) == false ) { error( type, "type " + type.id() + " has already been defined with a different structure" ); } } } for( Entry< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > entry : owToBeEqual.entrySet() ) { for( OneWayOperationDeclaration ow : entry.getValue() ) { checkEqualness( entry.getKey(), ow ); } } for( Entry< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > entry : rrToBeEqual.entrySet() ) { for( RequestResponseOperationDeclaration rr : entry.getValue() ) { checkEqualness( entry.getKey(), rr ); } } } private void checkCorrelationSets() { Collection< String > operations; Set< String > correlatingOperations = new HashSet< String >(); Set< String > currCorrelatingOperations = new HashSet< String >(); for( CorrelationSetInfo cset : correlationSets ) { correlationFunctionInfo.correlationSets().add( cset ); currCorrelatingOperations.clear(); for( CorrelationSetInfo.CorrelationVariableInfo csetVar : cset.variables() ) { for( CorrelationAliasInfo alias : csetVar.aliases() ) { checkCorrelationAlias( alias ); operations = inputTypeNameMap.get( alias.guardName() ); for( String operationName : operations ) { currCorrelatingOperations.add( operationName ); correlationFunctionInfo.putCorrelationPair( operationName, new CorrelationPairInfo( csetVar.correlationVariablePath(), alias.variablePath() ) ); } } } for( String operationName : currCorrelatingOperations ) { if ( correlatingOperations.contains( operationName ) ) { error( cset, "Operation " + operationName + " is specified on more than one correlation set. Each operation can correlate using only one correlation set." ); } else { correlatingOperations.add( operationName ); correlationFunctionInfo.operationCorrelationSetMap().put( operationName, cset ); correlationFunctionInfo.correlationSetOperations().put( cset, operationName ); } } } Collection< CorrelationPairInfo > pairs; for( Map.Entry< String, CorrelationSetInfo > entry : correlationFunctionInfo.operationCorrelationSetMap().entrySet() ) { pairs = correlationFunctionInfo.getOperationCorrelationPairs( entry.getKey() ); if ( pairs.size() != entry.getValue().variables().size() ) { error( entry.getValue(), "Operation " + entry.getKey() + " has not an alias specified for every variable in the correlation set." ); } } } private void checkCorrelationAlias( CorrelationAliasInfo alias ) { TypeDefinition type = definedTypes.get( alias.guardName() ); if ( type == null ) { error( alias.variablePath(), "type " + alias.guardName() + " is undefined" ); } if ( type.containsPath( alias.variablePath() ) == false ) { error( alias.variablePath(), "type " + alias.guardName() + " does not contain the specified path" ); } } public boolean validate() { program.accept( this ); resolveLazyLinks(); checkToBeEqualTypes(); checkCorrelationSets(); if ( configuration.checkForMain && mainDefined == false ) { error( null, "Main procedure not defined" ); } if ( !valid ) { logger.severe( "Aborting: input file semantically invalid." ); return false; } return valid; } private boolean isTopLevelType = true; public void visit( TypeInlineDefinition n ) { checkCardinality( n ); boolean backupRootType = isTopLevelType; if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } } isTopLevelType = false; if ( n.hasSubTypes() ) { for( Entry< String, TypeDefinition > entry : n.subTypes() ) { entry.getValue().accept( this ); } } isTopLevelType = backupRootType; if ( isTopLevelType ) { definedTypes.put( n.id(), n ); } } public void visit( TypeDefinitionLink n ) { checkCardinality( n ); if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } definedTypes.put( n.id(), n ); } definedTypeLinks.add( n ); } private void checkCardinality( TypeDefinition type ) { if ( type.cardinality().min() < 0 ) { error( type, "type " + type.id() + " specifies an invalid minimum range value (must be positive)" ); } if ( type.cardinality().max() < 0 ) { error( type, "type " + type.id() + " specifies an invalid maximum range value (must be positive)" ); } } public void visit( SpawnStatement n ) { n.body().accept( this ); } public void visit( DocumentationComment n ) {} public void visit( Program n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( VariablePathNode n ) { if ( insideInit && n.isCSet() ) { error( n, "Correlation variable access is forbidden in init procedures" ); } if ( n.isCSet() && !n.isStatic() ) { error( n, "Correlation paths must be statically defined" ); } } public void visit( InputPortInfo n ) { if ( inputPorts.get( n.id() ) != null ) { error( n, "input port " + n.id() + " has been already defined" ); } inputPorts.put( n.id(), n ); insideInputPort = true; Set< String > opSet = new HashSet< String >(); for( OperationDeclaration op : n.operations() ) { if ( opSet.contains( op.id() ) ) { error( n, "input port " + n.id() + " declares operation " + op.id() + " multiple times" ); } else { opSet.add( op.id() ); op.accept( this ); } } OutputPortInfo outputPort; for( String portName : n.aggregationList() ) { outputPort = outputPorts.get( portName ); if ( outputPort == null ) { error( n, "input port " + n.id() + " aggregates an undefined output port (" + portName + ")" ); }/* else { for( OperationDeclaration op : outputPort.operations() ) { if ( opSet.contains( op.id() ) ) { error( n, "input port " + n.id() + " declares duplicate operation " + op.id() + " from aggregated output port " + outputPort.id() ); } else { opSet.add( op.id() ); } } }*/ } insideInputPort = false; } public void visit( OutputPortInfo n ) { if ( outputPorts.get( n.id() ) != null ) error( n, "output port " + n.id() + " has been already defined" ); outputPorts.put( n.id(), n ); encounteredAssignment( n.id() ); for( OperationDeclaration op : n.operations() ) { op.accept( this ); } } public void visit( OneWayOperationDeclaration n ) { if ( definedTypes.get( n.requestType().id() ) == null ) { error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() ); } if ( insideInputPort ) { // Input operation if ( oneWayOperations.containsKey( n.id() ) ) { OneWayOperationDeclaration other = oneWayOperations.get( n.id() ); addOneWayEqualnessCheck( n, other ); } else { oneWayOperations.put( n.id(), n ); inputTypeNameMap.put( n.requestType().id(), n.id() ); } } } public void visit( RequestResponseOperationDeclaration n ) { if ( definedTypes.get( n.requestType().id() ) == null ) { error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() ); } if ( definedTypes.get( n.responseType().id() ) == null ) { error( n, "unknown type: " + n.responseType().id() + " for operation " + n.id() ); } for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) { if ( definedTypes.containsKey( fault.getValue().id() ) == false ) { error( n, "unknown type for fault " + fault.getKey() ); } } if ( insideInputPort ) { // Input operation if ( requestResponseOperations.containsKey( n.id() ) ) { RequestResponseOperationDeclaration other = requestResponseOperations.get( n.id() ); addRequestResponseEqualnessCheck( n, other ); } else { requestResponseOperations.put( n.id(), n ); inputTypeNameMap.put( n.requestType().id(), n.id() ); } } } private void checkEqualness( OneWayOperationDeclaration n, OneWayOperationDeclaration other ) { if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) { error( n, "input operations sharing the same name cannot declare different request types (One-Way operation " + n.id() + ")" ); } } private void checkEqualness( RequestResponseOperationDeclaration n, RequestResponseOperationDeclaration other ) { if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) { error( n, "input operations sharing the same name cannot declare different request types (Request-Response operation " + n.id() + ")" ); } if ( n.responseType().isEquivalentTo( other.responseType() ) == false ) { error( n, "input operations sharing the same name cannot declare different response types (Request-Response operation " + n.id() + ")" ); } if ( n.faults().size() != other.faults().size() ) { error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() ); } for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) { if ( fault.getValue() != null ) { if ( !other.faults().containsKey( fault.getKey() ) || !other.faults().get( fault.getKey() ).isEquivalentTo( fault.getValue() ) ) { error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() ); } } } } public void visit( DefinitionNode n ) { if ( subroutineNames.contains( n.id() ) ) { error( n, "Procedure " + n.id() + " uses an already defined identifier" ); } else { subroutineNames.add( n.id() ); } if ( "main".equals( n.id() ) ) { mainDefined = true; if ( executionInfo.mode() != ExecutionMode.SINGLE ) { if ( ( n.body() instanceof NDChoiceStatement || n.body() instanceof RequestResponseOperationStatement || n.body() instanceof OneWayOperationStatement ) == false ) { // The main body is not an input if ( n.body() instanceof SequenceStatement ) { OLSyntaxNode first = ((SequenceStatement)n.body()).children().get( 0 ); if ( (first instanceof RequestResponseOperationStatement || first instanceof OneWayOperationStatement) == false ) { // The main body is not even a sequence starting with an input error( n.body(), "The first statement of the main procedure must be an input if the execution mode is not single" ); } } else { // The main body is not even a sequence error( n.body(), "The first statement of the main procedure must be an input if the execution mode is not single" ); } } } } if ( n.id().equals( "init" ) ) { insideInit = true; } n.body().accept( this ); insideInit = false; } public void visit( ParallelStatement stm ) { for( OLSyntaxNode node : stm.children() ) { node.accept( this ); } } public void visit( SequenceStatement stm ) { for( OLSyntaxNode node : stm.children() ) { node.accept( this ); } } public void visit( NDChoiceStatement stm ) { Set< String > operations = new HashSet< String >(); String name = null; for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) { if ( pair.key() instanceof OneWayOperationStatement ) { name = ((OneWayOperationStatement)pair.key()).id(); } else if ( pair.key() instanceof RequestResponseOperationStatement ) { name = ((RequestResponseOperationStatement)pair.key()).id(); } else { error( pair.key(), "Input choices can contain only One-Way or Request-Response guards" ); } if ( operations.contains( name ) ) { error( pair.key(), "Input choices can not have duplicate input guards (input statement for operation " + name + ")" ); } else { operations.add( name ); } pair.key().accept( this ); pair.value().accept( this ); } } public void visit( NotificationOperationStatement n ) { OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() ); else if ( !( decl instanceof OneWayOperationDeclaration ) ) error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() ); } } public void visit( SolicitResponseOperationStatement n ) { if ( n.inputVarPath() != null ) { encounteredAssignment( n.inputVarPath() ); } OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) { error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() ); } else if ( !(decl instanceof RequestResponseOperationDeclaration) ) { error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() ); } } /*if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); }*/ } public void visit( ThrowStatement n ) { verify( n.expression() ); } public void visit( CompensateStatement n ) {} public void visit( InstallStatement n ) { for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) { pair.value().accept( this ); } } public void visit( Scope n ) { n.body().accept( this ); } public void visit( OneWayOperationStatement n ) { verify( n.inputVarPath() ); if ( n.inputVarPath() != null ) { if ( n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); } encounteredAssignment( n.inputVarPath() ); } } public void visit( RequestResponseOperationStatement n ) { verify( n.inputVarPath() ); verify( n.process() ); if ( n.inputVarPath() != null ) { if ( n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); } encounteredAssignment( n.inputVarPath() ); } } public void visit( LinkInStatement n ) {} public void visit( LinkOutStatement n ) {} public void visit( SynchronizedStatement n ) { n.body().accept( this ); } public void visit( AssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( AddAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( SubtractAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( MultiplyAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( DivideAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } private void verify( OLSyntaxNode n ) { if ( n != null ) { n.accept( this ); } } public void visit( PointerStatement n ) { encounteredAssignment( n.leftPath() ); encounteredAssignment( n.rightPath() ); n.leftPath().accept( this ); n.rightPath().accept( this ); if ( n.rightPath().isCSet() ) { error( n, "Making an alias to a correlation variable is forbidden" ); } } public void visit( DeepCopyStatement n ) { encounteredAssignment( n.leftPath() ); n.leftPath().accept( this ); n.rightPath().accept( this ); if ( n.leftPath().isCSet() ) { error( n, "Deep copy on a correlation variable is forbidden" ); } } public void visit( IfStatement n ) { for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) { verify( choice.key() ); verify( choice.value() ); } verify( n.elseProcess() ); } public void visit( DefinitionCallStatement n ) {} public void visit( WhileStatement n ) { n.condition().accept( this ); n.body().accept( this ); } public void visit( OrConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( AndConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( NotConditionNode n ) { n.condition().accept( this ); } public void visit( CompareConditionNode n ) { n.leftExpression().accept( this ); n.rightExpression().accept( this ); } public void visit( ExpressionConditionNode n ) { n.expression().accept( this ); } public void visit( ConstantIntegerExpression n ) {} public void visit( ConstantRealExpression n ) {} public void visit( ConstantStringExpression n ) {} public void visit( ProductExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } public void visit( SumExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } public void visit( VariableExpressionNode n ) { n.variablePath().accept( this ); } public void visit( InstallFixedVariableExpressionNode n ) { n.variablePath().accept( this ); } public void visit( NullProcessStatement n ) {} public void visit( ExitStatement n ) {} public void visit( ExecutionInfo n ) { executionMode = n.mode(); executionInfo = n; } public void visit( CorrelationSetInfo n ) { VariablePathSet pathSet = new VariablePathSet(); VariablePathNode path; for( CorrelationSetInfo.CorrelationVariableInfo csetVar : n.variables() ) { path = csetVar.correlationVariablePath(); if ( path.isGlobal() ) { error( path, "Correlation variables can not be global" ); } else if ( path.isCSet() ) { error( path, "Correlation variables can not be in the csets structure" ); } else { if ( path.isStatic() == false ) { error( path, "correlation variable paths can not make use of dynamic evaluation" ); } } if ( pathSet.contains( path ) ) { error( path, "Duplicate correlation variable" ); } else { pathSet.add( path ); } for( CorrelationAliasInfo alias : csetVar.aliases() ) { if ( alias.variablePath().isGlobal() ) { error( alias.variablePath(), "Correlation variables can not be global" ); } else if ( path.isCSet() ) { error( alias.variablePath(), "Correlation variables can not be in the csets structure" ); } else { if ( alias.variablePath().isStatic() == false ) { error( alias.variablePath(), "correlation variable path aliases can not make use of dynamic evaluation" ); } } } } correlationSets.add( n ); /*VariablePathNode varPath; List< Pair< OLSyntaxNode, OLSyntaxNode > > path; for( List< VariablePathNode > list : n.variables() ) { varPath = list.get( 0 ); if ( varPath.isGlobal() ) { error( list.get( 0 ), "Correlation variables can not be global" ); } path = varPath.path(); if ( path.size() > 1 ) { error( varPath, "Correlation variables can not be nested paths" ); } else if ( path.get( 0 ).value() != null ) { error( varPath, "Correlation variables can not use arrays" ); } else { correlationSet.add( ((ConstantStringExpression)path.get( 0 ).key()).value() ); } }*/ } public void visit( RunStatement n ) { warning( n, "Run statement is not a stable feature yet." ); } public void visit( ValueVectorSizeExpressionNode n ) { n.variablePath().accept( this ); } public void visit( PreIncrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( PostIncrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( PreDecrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( PostDecrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( UndefStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); if ( n.variablePath().isCSet() ) { error( n, "Undefining a correlation variable is forbidden" ); } } public void visit( ForStatement n ) { n.init().accept( this ); n.condition().accept( this ); n.post().accept( this ); n.body().accept( this ); } public void visit( ForEachStatement n ) { n.keyPath().accept( this ); n.targetPath().accept( this ); n.body().accept( this ); } public void visit( IsTypeExpressionNode n ) { n.variablePath().accept( this ); } public void visit( TypeCastExpressionNode n ) { n.expression().accept( this ); } public void visit( EmbeddedServiceNode n ) {} /** * @todo Must check if it's inside an install function */ public void visit( CurrentHandlerStatement n ) {} public void visit( InterfaceDefinition n ) {} }
libjolie/src/jolie/lang/parse/SemanticVerifier.java
/*************************************************************************** * Copyright (C) 2006-2011 by Fabrizio Montesi <famontesi@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * For details about the authors of this software, see the AUTHORS file. * ***************************************************************************/ package jolie.lang.parse; import java.util.Collection; import jolie.lang.parse.context.ParsingContext; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Logger; import jolie.lang.Constants.ExecutionMode; import jolie.lang.Constants.OperandType; import jolie.lang.parse.CorrelationFunctionInfo.CorrelationPairInfo; import jolie.lang.parse.ast.AddAssignStatement; import jolie.lang.parse.ast.AndConditionNode; import jolie.lang.parse.ast.AssignStatement; import jolie.lang.parse.ast.DocumentationComment; import jolie.lang.parse.ast.CompareConditionNode; import jolie.lang.parse.ast.CompensateStatement; import jolie.lang.parse.ast.ConstantIntegerExpression; import jolie.lang.parse.ast.ConstantRealExpression; import jolie.lang.parse.ast.ConstantStringExpression; import jolie.lang.parse.ast.CorrelationSetInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationAliasInfo; import jolie.lang.parse.ast.CurrentHandlerStatement; import jolie.lang.parse.ast.DeepCopyStatement; import jolie.lang.parse.ast.EmbeddedServiceNode; import jolie.lang.parse.ast.ExecutionInfo; import jolie.lang.parse.ast.ExitStatement; import jolie.lang.parse.ast.ExpressionConditionNode; import jolie.lang.parse.ast.ForEachStatement; import jolie.lang.parse.ast.ForStatement; import jolie.lang.parse.ast.IfStatement; import jolie.lang.parse.ast.InstallFixedVariableExpressionNode; import jolie.lang.parse.ast.InstallStatement; import jolie.lang.parse.ast.IsTypeExpressionNode; import jolie.lang.parse.ast.LinkInStatement; import jolie.lang.parse.ast.LinkOutStatement; import jolie.lang.parse.ast.NDChoiceStatement; import jolie.lang.parse.ast.NotConditionNode; import jolie.lang.parse.ast.NotificationOperationStatement; import jolie.lang.parse.ast.NullProcessStatement; import jolie.lang.parse.ast.OLSyntaxNode; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OneWayOperationStatement; import jolie.lang.parse.ast.OperationDeclaration; import jolie.lang.parse.ast.OrConditionNode; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.ParallelStatement; import jolie.lang.parse.ast.PointerStatement; import jolie.lang.parse.ast.PostDecrementStatement; import jolie.lang.parse.ast.PostIncrementStatement; import jolie.lang.parse.ast.PreDecrementStatement; import jolie.lang.parse.ast.PreIncrementStatement; import jolie.lang.parse.ast.ProductExpressionNode; import jolie.lang.parse.ast.Program; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.RequestResponseOperationStatement; import jolie.lang.parse.ast.RunStatement; import jolie.lang.parse.ast.Scope; import jolie.lang.parse.ast.SequenceStatement; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.SolicitResponseOperationStatement; import jolie.lang.parse.ast.DefinitionCallStatement; import jolie.lang.parse.ast.DefinitionNode; import jolie.lang.parse.ast.DivideAssignStatement; import jolie.lang.parse.ast.InterfaceDefinition; import jolie.lang.parse.ast.SubtractAssignStatement; import jolie.lang.parse.ast.MultiplyAssignStatement; import jolie.lang.parse.ast.SpawnStatement; import jolie.lang.parse.ast.SumExpressionNode; import jolie.lang.parse.ast.SynchronizedStatement; import jolie.lang.parse.ast.ThrowStatement; import jolie.lang.parse.ast.TypeCastExpressionNode; import jolie.lang.parse.ast.UndefStatement; import jolie.lang.parse.ast.ValueVectorSizeExpressionNode; import jolie.lang.parse.ast.VariableExpressionNode; import jolie.lang.parse.ast.VariablePathNode; import jolie.lang.parse.ast.WhileStatement; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.lang.parse.ast.types.TypeDefinitionLink; import jolie.lang.parse.ast.types.TypeInlineDefinition; import jolie.lang.parse.context.URIParsingContext; import jolie.util.ArrayListMultiMap; import jolie.util.MultiMap; import jolie.util.Pair; /** * Checks the well-formedness and validity of a JOLIE program. * @see Program * @author Fabrizio Montesi */ public class SemanticVerifier implements OLVisitor { public static class Configuration { public boolean checkForMain = true; } private final Program program; private boolean valid = true; private final Configuration configuration; private ExecutionInfo executionInfo = new ExecutionInfo( URIParsingContext.DEFAULT, ExecutionMode.SINGLE ); private final Map< String, InputPortInfo > inputPorts = new HashMap< String, InputPortInfo >(); private final Map< String, OutputPortInfo > outputPorts = new HashMap< String, OutputPortInfo >(); private final Set< String > subroutineNames = new HashSet< String > (); private final Map< String, OneWayOperationDeclaration > oneWayOperations = new HashMap< String, OneWayOperationDeclaration >(); private final Map< String, RequestResponseOperationDeclaration > requestResponseOperations = new HashMap< String, RequestResponseOperationDeclaration >(); private final Map< TypeDefinition, List< TypeDefinition > > typesToBeEqual = new HashMap< TypeDefinition, List< TypeDefinition > >(); private final Map< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > owToBeEqual = new HashMap< OneWayOperationDeclaration, List< OneWayOperationDeclaration > >(); private final Map< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > rrToBeEqual = new HashMap< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > >(); private final List< CorrelationSetInfo > correlationSets = new LinkedList< CorrelationSetInfo >(); private boolean insideInputPort = false; private boolean insideInit = false; private boolean mainDefined = false; private CorrelationFunctionInfo correlationFunctionInfo = new CorrelationFunctionInfo(); private final MultiMap< String, String > inputTypeNameMap = new ArrayListMultiMap< String, String >(); // Maps type names to the input operations that use them private ExecutionMode executionMode = ExecutionMode.SINGLE; private static final Logger logger = Logger.getLogger( "JOLIE" ); private final Map< String, TypeDefinition > definedTypes; private final List< TypeDefinitionLink > definedTypeLinks = new LinkedList< TypeDefinitionLink >(); //private TypeDefinition rootType; // the type representing the whole session state private final Map< String, Boolean > isConstantMap = new HashMap< String, Boolean >(); public SemanticVerifier( Program program, Configuration configuration ) { this.program = program; this.definedTypes = OLParser.createTypeDeclarationMap( program.context() ); this.configuration = configuration; /*rootType = new TypeInlineDefinition( new ParsingContext(), "#RootType", NativeType.VOID, jolie.lang.Constants.RANGE_ONE_TO_ONE );*/ } public SemanticVerifier( Program program ) { this( program, new Configuration() ); } public CorrelationFunctionInfo correlationFunctionInfo() { return correlationFunctionInfo; } public ExecutionMode executionMode() { return executionMode; } private void encounteredAssignment( String varName ) { if ( isConstantMap.containsKey( varName ) ) { isConstantMap.put( varName, false ); } else { isConstantMap.put( varName, true ); } } private void addTypeEqualnessCheck( TypeDefinition key, TypeDefinition type ) { List< TypeDefinition > toBeEqualList = typesToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList< TypeDefinition >(); typesToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( type ); } private void addOneWayEqualnessCheck( OneWayOperationDeclaration key, OneWayOperationDeclaration oneWay ) { List< OneWayOperationDeclaration > toBeEqualList = owToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList< OneWayOperationDeclaration >(); owToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( oneWay ); } private void addRequestResponseEqualnessCheck( RequestResponseOperationDeclaration key, RequestResponseOperationDeclaration requestResponse ) { List< RequestResponseOperationDeclaration > toBeEqualList = rrToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList< RequestResponseOperationDeclaration >(); rrToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( requestResponse ); } private void encounteredAssignment( VariablePathNode path ) { encounteredAssignment( ((ConstantStringExpression)path.path().get( 0 ).key()).value() ); } public Map< String, Boolean > isConstantMap() { return isConstantMap; } private void warning( OLSyntaxNode node, String message ) { if ( node == null ) { logger.warning( message ); } else { logger.warning( node.context().sourceName() + ":" + node.context().line() + ": " + message ); } } private void error( OLSyntaxNode node, String message ) { valid = false; if ( node != null ) { ParsingContext context = node.context(); logger.severe( context.sourceName() + ":" + context.line() + ": " + message ); } else { logger.severe( message ); } } private void resolveLazyLinks() { for( TypeDefinitionLink l : definedTypeLinks ) { l.setLinkedType( definedTypes.get( l.linkedTypeName() ) ); if ( l.linkedType() == null ) { error( l, "type " + l.id() + "points to an undefined type (" + l.linkedTypeName() + ")" ); } } } private void checkToBeEqualTypes() { for( Entry< TypeDefinition, List< TypeDefinition > > entry : typesToBeEqual.entrySet() ) { for( TypeDefinition type : entry.getValue() ) { if ( entry.getKey().isEquivalentTo( type ) == false ) { error( type, "type " + type.id() + " has already been defined with a different structure" ); } } } for( Entry< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > entry : owToBeEqual.entrySet() ) { for( OneWayOperationDeclaration ow : entry.getValue() ) { checkEqualness( entry.getKey(), ow ); } } for( Entry< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > entry : rrToBeEqual.entrySet() ) { for( RequestResponseOperationDeclaration rr : entry.getValue() ) { checkEqualness( entry.getKey(), rr ); } } } private void checkCorrelationSets() { Collection< String > operations; Set< String > correlatingOperations = new HashSet< String >(); Set< String > currCorrelatingOperations = new HashSet< String >(); for( CorrelationSetInfo cset : correlationSets ) { correlationFunctionInfo.correlationSets().add( cset ); currCorrelatingOperations.clear(); for( CorrelationSetInfo.CorrelationVariableInfo csetVar : cset.variables() ) { for( CorrelationAliasInfo alias : csetVar.aliases() ) { checkCorrelationAlias( alias ); operations = inputTypeNameMap.get( alias.guardName() ); for( String operationName : operations ) { currCorrelatingOperations.add( operationName ); correlationFunctionInfo.putCorrelationPair( operationName, new CorrelationPairInfo( csetVar.correlationVariablePath(), alias.variablePath() ) ); } } } for( String operationName : currCorrelatingOperations ) { if ( correlatingOperations.contains( operationName ) ) { error( cset, "Operation " + operationName + " is specified on more than one correlation set. Each operation can correlate using only one correlation set." ); } else { correlatingOperations.add( operationName ); correlationFunctionInfo.operationCorrelationSetMap().put( operationName, cset ); correlationFunctionInfo.correlationSetOperations().put( cset, operationName ); } } } Collection< CorrelationPairInfo > pairs; for( Map.Entry< String, CorrelationSetInfo > entry : correlationFunctionInfo.operationCorrelationSetMap().entrySet() ) { pairs = correlationFunctionInfo.getOperationCorrelationPairs( entry.getKey() ); if ( pairs.size() != entry.getValue().variables().size() ) { error( entry.getValue(), "Operation " + entry.getKey() + " has not an alias specified for every variable in the correlation set." ); } } } private void checkCorrelationAlias( CorrelationAliasInfo alias ) { TypeDefinition type = definedTypes.get( alias.guardName() ); if ( type == null ) { error( alias.variablePath(), "type " + alias.guardName() + " is undefined" ); } if ( type.containsPath( alias.variablePath() ) == false ) { error( alias.variablePath(), "type " + alias.guardName() + " does not contain the specified path" ); } } public boolean validate() { program.accept( this ); resolveLazyLinks(); checkToBeEqualTypes(); checkCorrelationSets(); if ( configuration.checkForMain && mainDefined == false ) { error( null, "Main procedure not defined" ); } if ( !valid ) { logger.severe( "Aborting: input file semantically invalid." ); return false; } return valid; } private boolean isTopLevelType = true; public void visit( TypeInlineDefinition n ) { checkCardinality( n ); boolean backupRootType = isTopLevelType; if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } } isTopLevelType = false; if ( n.hasSubTypes() ) { for( Entry< String, TypeDefinition > entry : n.subTypes() ) { entry.getValue().accept( this ); } } isTopLevelType = backupRootType; if ( isTopLevelType ) { definedTypes.put( n.id(), n ); } } public void visit( TypeDefinitionLink n ) { checkCardinality( n ); if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } definedTypes.put( n.id(), n ); } definedTypeLinks.add( n ); } private void checkCardinality( TypeDefinition type ) { if ( type.cardinality().min() < 0 ) { error( type, "type " + type.id() + " specifies an invalid minimum range value (must be positive)" ); } if ( type.cardinality().max() < 0 ) { error( type, "type " + type.id() + " specifies an invalid maximum range value (must be positive)" ); } } public void visit( SpawnStatement n ) { n.body().accept( this ); } public void visit( DocumentationComment n ) {} public void visit( Program n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( VariablePathNode n ) { if ( insideInit && n.isCSet() ) { error( n, "Correlation variable access is forbidden in init procedures" ); } if ( n.isCSet() && !n.isStatic() ) { error( n, "Correlation paths must be statically defined" ); } } public void visit( InputPortInfo n ) { if ( inputPorts.get( n.id() ) != null ) { error( n, "input port " + n.id() + " has been already defined" ); } inputPorts.put( n.id(), n ); insideInputPort = true; Set< String > opSet = new HashSet< String >(); for( OperationDeclaration op : n.operations() ) { if ( opSet.contains( op.id() ) ) { error( n, "input port " + n.id() + " declares operation " + op.id() + " multiple times" ); } else { opSet.add( op.id() ); op.accept( this ); } } OutputPortInfo outputPort; for( String portName : n.aggregationList() ) { outputPort = outputPorts.get( portName ); if ( outputPort == null ) { error( n, "input port " + n.id() + " aggregates an undefined output port (" + portName + ")" ); }/* else { for( OperationDeclaration op : outputPort.operations() ) { if ( opSet.contains( op.id() ) ) { error( n, "input port " + n.id() + " declares duplicate operation " + op.id() + " from aggregated output port " + outputPort.id() ); } else { opSet.add( op.id() ); } } }*/ } insideInputPort = false; } public void visit( OutputPortInfo n ) { if ( outputPorts.get( n.id() ) != null ) error( n, "output port " + n.id() + " has been already defined" ); outputPorts.put( n.id(), n ); encounteredAssignment( n.id() ); for( OperationDeclaration op : n.operations() ) { op.accept( this ); } } public void visit( OneWayOperationDeclaration n ) { if ( definedTypes.get( n.requestType().id() ) == null ) { error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() ); } if ( insideInputPort ) { // Input operation if ( oneWayOperations.containsKey( n.id() ) ) { OneWayOperationDeclaration other = oneWayOperations.get( n.id() ); addOneWayEqualnessCheck( n, other ); } else { oneWayOperations.put( n.id(), n ); inputTypeNameMap.put( n.requestType().id(), n.id() ); } } } public void visit( RequestResponseOperationDeclaration n ) { if ( definedTypes.get( n.requestType().id() ) == null ) { error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() ); } if ( definedTypes.get( n.responseType().id() ) == null ) { error( n, "unknown type: " + n.responseType().id() + " for operation " + n.id() ); } for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) { if ( definedTypes.containsKey( fault.getValue().id() ) == false ) { error( n, "unknown type for fault " + fault.getKey() ); } } if ( insideInputPort ) { // Input operation if ( requestResponseOperations.containsKey( n.id() ) ) { RequestResponseOperationDeclaration other = requestResponseOperations.get( n.id() ); addRequestResponseEqualnessCheck( n, other ); } else { requestResponseOperations.put( n.id(), n ); inputTypeNameMap.put( n.requestType().id(), n.id() ); } } } private void checkEqualness( OneWayOperationDeclaration n, OneWayOperationDeclaration other ) { if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) { error( n, "input operations sharing the same name cannot declare different request types (One-Way operation " + n.id() + ")" ); } } private void checkEqualness( RequestResponseOperationDeclaration n, RequestResponseOperationDeclaration other ) { if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) { error( n, "input operations sharing the same name cannot declare different request types (Request-Response operation " + n.id() + ")" ); } if ( n.responseType().isEquivalentTo( other.responseType() ) == false ) { error( n, "input operations sharing the same name cannot declare different response types (Request-Response operation " + n.id() + ")" ); } if ( n.faults().size() != other.faults().size() ) { error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() ); } for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) { if ( fault.getValue() != null ) { if ( !other.faults().containsKey( fault.getKey() ) || !other.faults().get( fault.getKey() ).isEquivalentTo( fault.getValue() ) ) { error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() ); } } } } public void visit( DefinitionNode n ) { if ( subroutineNames.contains( n.id() ) ) { error( n, "Procedure " + n.id() + " uses an already defined identifier" ); } else { subroutineNames.add( n.id() ); } if ( "main".equals( n.id() ) ) { mainDefined = true; if ( ( n.body() instanceof NDChoiceStatement || n.body() instanceof RequestResponseOperationStatement || n.body() instanceof OneWayOperationStatement ) == false ) { // The main body is not an input if ( n.body() instanceof SequenceStatement ) { OLSyntaxNode first = ((SequenceStatement)n.body()).children().get( 0 ); if ( (first instanceof RequestResponseOperationStatement || first instanceof OneWayOperationStatement) == false ) { // The main body is not even a sequence starting with an input if ( executionInfo.mode() != ExecutionMode.SINGLE ) { error( n.body(), "The first statement of the main procedure must be an input if the execution mode is not single" ); } } } else { error( n.body(), "The first statement of the main procedure must be an input if the execution mode is not single" ); } } } if ( n.id().equals( "init" ) ) { insideInit = true; } n.body().accept( this ); insideInit = false; } public void visit( ParallelStatement stm ) { for( OLSyntaxNode node : stm.children() ) { node.accept( this ); } } public void visit( SequenceStatement stm ) { for( OLSyntaxNode node : stm.children() ) { node.accept( this ); } } public void visit( NDChoiceStatement stm ) { Set< String > operations = new HashSet< String >(); String name = null; for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) { if ( pair.key() instanceof OneWayOperationStatement ) { name = ((OneWayOperationStatement)pair.key()).id(); } else if ( pair.key() instanceof RequestResponseOperationStatement ) { name = ((RequestResponseOperationStatement)pair.key()).id(); } else { error( pair.key(), "Input choices can contain only One-Way or Request-Response guards" ); } if ( operations.contains( name ) ) { error( pair.key(), "Input choices can not have duplicate input guards (input statement for operation " + name + ")" ); } else { operations.add( name ); } pair.key().accept( this ); pair.value().accept( this ); } } public void visit( NotificationOperationStatement n ) { OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() ); else if ( !( decl instanceof OneWayOperationDeclaration ) ) error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() ); } } public void visit( SolicitResponseOperationStatement n ) { if ( n.inputVarPath() != null ) { encounteredAssignment( n.inputVarPath() ); } OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) { error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() ); } else if ( !(decl instanceof RequestResponseOperationDeclaration) ) { error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() ); } } /*if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); }*/ } public void visit( ThrowStatement n ) { verify( n.expression() ); } public void visit( CompensateStatement n ) {} public void visit( InstallStatement n ) { for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) { pair.value().accept( this ); } } public void visit( Scope n ) { n.body().accept( this ); } public void visit( OneWayOperationStatement n ) { verify( n.inputVarPath() ); if ( n.inputVarPath() != null ) { if ( n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); } encounteredAssignment( n.inputVarPath() ); } } public void visit( RequestResponseOperationStatement n ) { verify( n.inputVarPath() ); verify( n.process() ); if ( n.inputVarPath() != null ) { if ( n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); } encounteredAssignment( n.inputVarPath() ); } } public void visit( LinkInStatement n ) {} public void visit( LinkOutStatement n ) {} public void visit( SynchronizedStatement n ) { n.body().accept( this ); } public void visit( AssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( AddAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( SubtractAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( MultiplyAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } public void visit( DivideAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } private void verify( OLSyntaxNode n ) { if ( n != null ) { n.accept( this ); } } public void visit( PointerStatement n ) { encounteredAssignment( n.leftPath() ); encounteredAssignment( n.rightPath() ); n.leftPath().accept( this ); n.rightPath().accept( this ); if ( n.rightPath().isCSet() ) { error( n, "Making an alias to a correlation variable is forbidden" ); } } public void visit( DeepCopyStatement n ) { encounteredAssignment( n.leftPath() ); n.leftPath().accept( this ); n.rightPath().accept( this ); if ( n.leftPath().isCSet() ) { error( n, "Deep copy on a correlation variable is forbidden" ); } } public void visit( IfStatement n ) { for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) { verify( choice.key() ); verify( choice.value() ); } verify( n.elseProcess() ); } public void visit( DefinitionCallStatement n ) {} public void visit( WhileStatement n ) { n.condition().accept( this ); n.body().accept( this ); } public void visit( OrConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( AndConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( NotConditionNode n ) { n.condition().accept( this ); } public void visit( CompareConditionNode n ) { n.leftExpression().accept( this ); n.rightExpression().accept( this ); } public void visit( ExpressionConditionNode n ) { n.expression().accept( this ); } public void visit( ConstantIntegerExpression n ) {} public void visit( ConstantRealExpression n ) {} public void visit( ConstantStringExpression n ) {} public void visit( ProductExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } public void visit( SumExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } public void visit( VariableExpressionNode n ) { n.variablePath().accept( this ); } public void visit( InstallFixedVariableExpressionNode n ) { n.variablePath().accept( this ); } public void visit( NullProcessStatement n ) {} public void visit( ExitStatement n ) {} public void visit( ExecutionInfo n ) { executionMode = n.mode(); executionInfo = n; } public void visit( CorrelationSetInfo n ) { VariablePathSet pathSet = new VariablePathSet(); VariablePathNode path; for( CorrelationSetInfo.CorrelationVariableInfo csetVar : n.variables() ) { path = csetVar.correlationVariablePath(); if ( path.isGlobal() ) { error( path, "Correlation variables can not be global" ); } else if ( path.isCSet() ) { error( path, "Correlation variables can not be in the csets structure" ); } else { if ( path.isStatic() == false ) { error( path, "correlation variable paths can not make use of dynamic evaluation" ); } } if ( pathSet.contains( path ) ) { error( path, "Duplicate correlation variable" ); } else { pathSet.add( path ); } for( CorrelationAliasInfo alias : csetVar.aliases() ) { if ( alias.variablePath().isGlobal() ) { error( alias.variablePath(), "Correlation variables can not be global" ); } else if ( path.isCSet() ) { error( alias.variablePath(), "Correlation variables can not be in the csets structure" ); } else { if ( alias.variablePath().isStatic() == false ) { error( alias.variablePath(), "correlation variable path aliases can not make use of dynamic evaluation" ); } } } } correlationSets.add( n ); /*VariablePathNode varPath; List< Pair< OLSyntaxNode, OLSyntaxNode > > path; for( List< VariablePathNode > list : n.variables() ) { varPath = list.get( 0 ); if ( varPath.isGlobal() ) { error( list.get( 0 ), "Correlation variables can not be global" ); } path = varPath.path(); if ( path.size() > 1 ) { error( varPath, "Correlation variables can not be nested paths" ); } else if ( path.get( 0 ).value() != null ) { error( varPath, "Correlation variables can not use arrays" ); } else { correlationSet.add( ((ConstantStringExpression)path.get( 0 ).key()).value() ); } }*/ } public void visit( RunStatement n ) { warning( n, "Run statement is not a stable feature yet." ); } public void visit( ValueVectorSizeExpressionNode n ) { n.variablePath().accept( this ); } public void visit( PreIncrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( PostIncrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( PreDecrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( PostDecrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } public void visit( UndefStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); if ( n.variablePath().isCSet() ) { error( n, "Undefining a correlation variable is forbidden" ); } } public void visit( ForStatement n ) { n.init().accept( this ); n.condition().accept( this ); n.post().accept( this ); n.body().accept( this ); } public void visit( ForEachStatement n ) { n.keyPath().accept( this ); n.targetPath().accept( this ); n.body().accept( this ); } public void visit( IsTypeExpressionNode n ) { n.variablePath().accept( this ); } public void visit( TypeCastExpressionNode n ) { n.expression().accept( this ); } public void visit( EmbeddedServiceNode n ) {} /** * @todo Must check if it's inside an install function */ public void visit( CurrentHandlerStatement n ) {} public void visit( InterfaceDefinition n ) {} }
Former-commit-id: 9e4e208be203908b4d22e2f05769c2a4b3a0117e
libjolie/src/jolie/lang/parse/SemanticVerifier.java
Java
apache-2.0
78ec80ec60b5d4b52642a75e217fe001371d99a6
0
01org/vmf,01org/vmf,apavlenko/vmf,apavlenko/vmf,01org/vmf,01org/vmf,apavlenko/vmf,apavlenko/vmf,apavlenko/vmf,01org/vmf
package com.intel.vmf; public class FieldDesc { static { System.loadLibrary("vmf"); } protected final long nativeObj; public boolean optional; public String name; public Variant.Type type; public FieldDesc () { nativeObj = n_FieldDesc(); } public boolean isEquals(long obj) { return n_isEquals(nativeObj, obj); } @Override protected void finalize () throws Throwable { n_delete (nativeObj); super.finalize(); } private native long n_FieldDesc (); private native boolean n_isEquals(long nativeObj); private static native void n_delete (long nativeObj); }
modules/vmfcore/java/FieldDesc.java
package com.intel.vmf; public class FieldDesc { static { System.loadLibrary("vmf"); } protected final long nativeObj; public boolean optional; public String name; public Variant.Type type; public FieldDesc () { nativeObj = n_FieldDesc(); } public boolean isEquals(long obj) { return n_isEquals(nativeObj, obj); } @Override protected void finalize () throws Throwable { n_delete (nativeObj); super.finalize(); } private native long n_FieldDesc (); private native boolean n_isEquals(long nativeObj); private static native void n_delete (long nativeObj); }
minor changes for FieldDesc class
modules/vmfcore/java/FieldDesc.java
minor changes for FieldDesc class
Java
apache-2.0
b29805f0c3056c5edc843c1a1a6b9296de09752e
0
mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,hsaputra/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,chtyim/cdap,caskdata/cdap,caskdata/cdap,mpouttuclarke/cdap,hsaputra/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,anthcp/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,hsaputra/cdap,anthcp/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap
/* * Copyright 2012-2013 Continuuity,Inc. All Rights Reserved. */ package com.continuuity.metrics.query; import com.continuuity.common.metrics.MetricsScope; import junit.framework.Assert; import org.apache.commons.httpclient.util.URIUtil; import org.apache.http.client.utils.URIUtils; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; /** * */ public class MetricsRequestParserTest { @Test public void testOverview() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/process/busyness?count=60")); Assert.assertNull(request.getContextPrefix()); Assert.assertEquals("process.busyness", request.getMetricPrefix()); } @Test public void testFlow() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/process/bytes/app1?count=60")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("process.bytes", request.getMetricPrefix()); Assert.assertEquals(60, request.getCount()); request = MetricsRequestParser.parse(URI.create("/process/bytes/app1/flows/flowId?count=60&start=1&end=61")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); Assert.assertEquals("process.bytes", request.getMetricPrefix()); Assert.assertEquals(1, request.getStartTime()); Assert.assertEquals(61, request.getEndTime()); request = MetricsRequestParser.parse(URI.create("/process/bytes/app1/flows/flowId/flowletId?summary=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals(MetricsRequest.Type.SUMMARY, request.getType()); request = MetricsRequestParser.parse( URI.create("/process/events/app1/flows/flowId/flowletId/ins/queueId?aggregate=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("process.events.ins.queueId", request.getMetricPrefix()); Assert.assertEquals(MetricsRequest.Type.AGGREGATE, request.getType()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testMapReduce() { MetricsRequest request = MetricsRequestParser.parse( URI.create("/process/completion/app1/mapreduces/jobId?summary=true")); Assert.assertEquals("app1.b.jobId", request.getContextPrefix()); request = MetricsRequestParser.parse( URI.create("/process/completion/app1/mapreduces/jobId/mappers?summary=true")); Assert.assertEquals("app1.b.jobId.m", request.getContextPrefix()); request = MetricsRequestParser.parse( URI.create("/process/completion/app1/mapreduces/jobId/mappers/mapperId?summary=true")); Assert.assertEquals("app1.b.jobId.m.mapperId", request.getContextPrefix()); Assert.assertEquals(MetricsRequest.Type.SUMMARY, request.getType()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testProcessEvents() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/process/events/app1/flows/flowId?summary=true")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); Assert.assertEquals("process.events.processed", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/process/events/app1/flows/flowId/flowletId?summary=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("process.events.processed", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/process/events/app1/flows/flowId/flowletId/ins/q?summary=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("process.events.ins.q", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testStoreApp() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/store/bytes/apps/app1?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("store.bytes", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/store/bytes/apps/app1/flows/flowId?aggregate=true")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); request = MetricsRequestParser.parse( URI.create("/store/bytes/apps/app1/flows/flowId/flowletId/datasets/dataset1?aggregate=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("store.bytes", request.getMetricPrefix()); Assert.assertEquals("dataset1", request.getTagPrefix()); request = MetricsRequestParser.parse( URI.create("/store/reads/apps/app1/mapreduces/jobId/datasets/dataset1?aggregate=true")); Assert.assertEquals("app1.b.jobId", request.getContextPrefix()); Assert.assertEquals("store.reads", request.getMetricPrefix()); Assert.assertEquals("dataset1", request.getTagPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testStoreDataset() { MetricsRequest request = MetricsRequestParser.parse( URI.create("/store/reads/datasets/dataset1/app1/flows/flowId?aggregate=true")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); Assert.assertEquals("store.reads", request.getMetricPrefix()); Assert.assertEquals("dataset1", request.getTagPrefix()); request = MetricsRequestParser.parse( URI.create("/store/reads/datasets/dataset2/app1/mapreduces/jobId?aggregate=true")); Assert.assertEquals("app1.b.jobId", request.getContextPrefix()); Assert.assertEquals("store.reads", request.getMetricPrefix()); Assert.assertEquals("dataset2", request.getTagPrefix()); request = MetricsRequestParser.parse(URI.create("/store/bytes/datasets/dataset2?aggregate=true")); Assert.assertNull(request.getContextPrefix()); Assert.assertEquals("dataset2", request.getTagPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testCollect() { MetricsRequest request = MetricsRequestParser.parse( URI.create("/collect/events/apps/app1?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("collect.events", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/collect/events/streams/stream1?aggregate=true")); Assert.assertNull(request.getContextPrefix()); Assert.assertEquals("stream1", request.getTagPrefix()); request = MetricsRequestParser.parse(URI.create("/collect/events/streams/stream1/app1/flows/flow1?aggregate=true")); Assert.assertEquals("app1.f.flow1", request.getContextPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testUser() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/metric?aggregate=true")); Assert.assertEquals("app1.f", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/metric?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/flow1/flowlet1/metric?aggregate=true")); Assert.assertEquals("app1.f.flow1.flowlet1", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/procedures/procedure1/metric?aggregate=true")); Assert.assertEquals("app1.p.procedure1", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/mapreduces/mapred1/mappers/metric?aggregate=true")); Assert.assertEquals("app1.b.mapred1.m", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); } @Test public void testUserMetricURIDecoding() throws UnsupportedEncodingException { String weirdMetric = "/weird?me+tr ic#$name////"; // encoded version or weirdMetric String encodedWeirdMetric = "%2Fweird%3Fme%2Btr%20ic%23%24name%2F%2F%2F%2F"; MetricsRequest request = MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/" + encodedWeirdMetric + "?aggregate=true")); Assert.assertEquals("app1.f", request.getContextPrefix()); Assert.assertEquals(weirdMetric, request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/" + encodedWeirdMetric + "?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals(weirdMetric, request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); } @Test(expected = IllegalArgumentException.class) public void testUserMetricBadURIThrowsException() { String badEncoding = "%2"; MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/" + badEncoding + "?aggregate=true")); } }
watchdog/src/test/java/com/continuuity/metrics/query/MetricsRequestParserTest.java
/* * Copyright 2012-2013 Continuuity,Inc. All Rights Reserved. */ package com.continuuity.metrics.query; import com.continuuity.common.metrics.MetricsScope; import junit.framework.Assert; import org.apache.commons.httpclient.util.URIUtil; import org.apache.http.client.utils.URIUtils; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; /** * */ public class MetricsRequestParserTest { @Test public void testOverview() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/process/busyness?count=60")); Assert.assertNull(request.getContextPrefix()); Assert.assertEquals("process.busyness", request.getMetricPrefix()); } @Test public void testFlow() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/process/bytes/app1?count=60")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("process.bytes", request.getMetricPrefix()); Assert.assertEquals(60, request.getCount()); request = MetricsRequestParser.parse(URI.create("/process/bytes/app1/flows/flowId?count=60&start=1&end=61")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); Assert.assertEquals("process.bytes", request.getMetricPrefix()); Assert.assertEquals(1, request.getStartTime()); Assert.assertEquals(61, request.getEndTime()); request = MetricsRequestParser.parse(URI.create("/process/bytes/app1/flows/flowId/flowletId?summary=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals(MetricsRequest.Type.SUMMARY, request.getType()); request = MetricsRequestParser.parse( URI.create("/process/events/app1/flows/flowId/flowletId/ins/queueId?aggregate=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("process.events.ins.queueId", request.getMetricPrefix()); Assert.assertEquals(MetricsRequest.Type.AGGREGATE, request.getType()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testMapReduce() { MetricsRequest request = MetricsRequestParser.parse( URI.create("/process/completion/app1/mapreduce/jobId?summary=true")); Assert.assertEquals("app1.b.jobId", request.getContextPrefix()); request = MetricsRequestParser.parse( URI.create("/process/completion/app1/mapreduce/jobId/mappers?summary=true")); Assert.assertEquals("app1.b.jobId.m", request.getContextPrefix()); request = MetricsRequestParser.parse( URI.create("/process/completion/app1/mapreduce/jobId/mappers/mapperId?summary=true")); Assert.assertEquals("app1.b.jobId.m.mapperId", request.getContextPrefix()); Assert.assertEquals(MetricsRequest.Type.SUMMARY, request.getType()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testProcessEvents() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/process/events/app1/flows/flowId?summary=true")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); Assert.assertEquals("process.events.processed", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/process/events/app1/flows/flowId/flowletId?summary=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("process.events.processed", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/process/events/app1/flows/flowId/flowletId/ins/q?summary=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("process.events.ins.q", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testStoreApp() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/store/bytes/apps/app1?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("store.bytes", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/store/bytes/apps/app1/flows/flowId?aggregate=true")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); request = MetricsRequestParser.parse( URI.create("/store/bytes/apps/app1/flows/flowId/flowletId/datasets/dataset1?aggregate=true")); Assert.assertEquals("app1.f.flowId.flowletId", request.getContextPrefix()); Assert.assertEquals("store.bytes", request.getMetricPrefix()); Assert.assertEquals("dataset1", request.getTagPrefix()); request = MetricsRequestParser.parse( URI.create("/store/reads/apps/app1/mapreduce/jobId/datasets/dataset1?aggregate=true")); Assert.assertEquals("app1.b.jobId", request.getContextPrefix()); Assert.assertEquals("store.reads", request.getMetricPrefix()); Assert.assertEquals("dataset1", request.getTagPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testStoreDataset() { MetricsRequest request = MetricsRequestParser.parse( URI.create("/store/reads/datasets/dataset1/app1/flows/flowId?aggregate=true")); Assert.assertEquals("app1.f.flowId", request.getContextPrefix()); Assert.assertEquals("store.reads", request.getMetricPrefix()); Assert.assertEquals("dataset1", request.getTagPrefix()); request = MetricsRequestParser.parse( URI.create("/store/reads/datasets/dataset2/app1/mapreduce/jobId?aggregate=true")); Assert.assertEquals("app1.b.jobId", request.getContextPrefix()); Assert.assertEquals("store.reads", request.getMetricPrefix()); Assert.assertEquals("dataset2", request.getTagPrefix()); request = MetricsRequestParser.parse(URI.create("/store/bytes/datasets/dataset2?aggregate=true")); Assert.assertNull(request.getContextPrefix()); Assert.assertEquals("dataset2", request.getTagPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testCollect() { MetricsRequest request = MetricsRequestParser.parse( URI.create("/collect/events/apps/app1?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("collect.events", request.getMetricPrefix()); request = MetricsRequestParser.parse(URI.create("/collect/events/streams/stream1?aggregate=true")); Assert.assertNull(request.getContextPrefix()); Assert.assertEquals("stream1", request.getTagPrefix()); request = MetricsRequestParser.parse(URI.create("/collect/events/streams/stream1/app1/flows/flow1?aggregate=true")); Assert.assertEquals("app1.f.flow1", request.getContextPrefix()); Assert.assertEquals(MetricsScope.REACTOR, request.getScope()); } @Test public void testUser() { MetricsRequest request = MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/metric?aggregate=true")); Assert.assertEquals("app1.f", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/metric?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/flow1/flowlet1/metric?aggregate=true")); Assert.assertEquals("app1.f.flow1.flowlet1", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/procedures/procedure1/metric?aggregate=true")); Assert.assertEquals("app1.p.procedure1", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/mapreduce/mapred1/mappers/metric?aggregate=true")); Assert.assertEquals("app1.b.mapred1.m", request.getContextPrefix()); Assert.assertEquals("metric", request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); } @Test public void testUserMetricURIDecoding() throws UnsupportedEncodingException { String weirdMetric = "/weird?me+tr ic#$name////"; // encoded version or weirdMetric String encodedWeirdMetric = "%2Fweird%3Fme%2Btr%20ic%23%24name%2F%2F%2F%2F"; MetricsRequest request = MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/" + encodedWeirdMetric + "?aggregate=true")); Assert.assertEquals("app1.f", request.getContextPrefix()); Assert.assertEquals(weirdMetric, request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); request = MetricsRequestParser.parse(URI.create("/user/apps/app1/" + encodedWeirdMetric + "?aggregate=true")); Assert.assertEquals("app1", request.getContextPrefix()); Assert.assertEquals(weirdMetric, request.getMetricPrefix()); Assert.assertEquals(MetricsScope.USER, request.getScope()); } @Test(expected = IllegalArgumentException.class) public void testUserMetricBadURIThrowsException() { String badEncoding = "%2"; MetricsRequestParser.parse(URI.create("/user/apps/app1/flows/" + badEncoding + "?aggregate=true")); } }
Fixed test cases that were missed out during map reduce change.
watchdog/src/test/java/com/continuuity/metrics/query/MetricsRequestParserTest.java
Fixed test cases that were missed out during map reduce change.
Java
apache-2.0
649f405344ea6c91a53243b7ca45ff25a2c215ab
0
CC4401-TeraCity/TeraCity,Ciclop/Terasology,Ciclop/Terasology,CC4401-TeraCity/TeraCity
package flyMode; import org.terasology.HUDToggleButtons.systems.HUDToggleButtonsClientSystem; import org.terasology.entitySystem.entity.EntityManager; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent; import org.terasology.entitySystem.entity.lifecycleEvents.OnActivatedComponent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.characters.CharacterMovementComponent; import org.terasology.logic.characters.MovementMode; import org.terasology.logic.characters.events.SetMovementModeEvent; import org.terasology.logic.console.Console; import org.terasology.logic.location.LocationComponent; import org.terasology.math.geom.Vector3f; import org.terasology.math.geom.Vector3i; import org.terasology.network.ClientComponent; import org.terasology.registry.CoreRegistry; import org.terasology.registry.In; import org.terasology.world.WorldProvider; import org.terasology.world.block.BlockManager; import org.terasology.world.block.family.BlockFamily; import org.terasology.world.generator.WorldGenerator; import speedAlgorithm.CodeMapSpeed; import speedAlgorithm.Speed; /** * Class that toggles the Flying mode in Terasology when clicking a button */ @RegisterSystem public class FlyMode extends BaseComponentSystem implements HUDToggleButtonsClientSystem.HUDToggleButtonState { @In private HUDToggleButtonsClientSystem toggleButtonsClientSystem; @In private EntityManager entityManager; @In private Console console; @In private WorldGenerator worldGenerator; @In private BlockManager blockManager; private EntityRef localClientEntity; private Vector3f oldLocation; /* * @see org.terasology.entitySystem.systems.BaseComponentSystem#initialise() * We do override of this method for register the button into the GUI. */ @Override public void initialise() { toggleButtonsClientSystem.registerToggleButton(this); } /** * @return localClientEntity A reference to the local client Entity * Get the current client Entity (The local one) */ private EntityRef getLocalClientEntity() { if (localClientEntity == null) { for (EntityRef entityRef : entityManager.getEntitiesWith(ClientComponent.class)) { ClientComponent clientComponent = entityRef.getComponent(ClientComponent.class); if (clientComponent.local) { localClientEntity = entityRef; break; } } } return localClientEntity; } /** * @return EntityRef A reference to the local character Entity * Get the current character Entity (The local one) */ private EntityRef getLocalCharacterEntity() { EntityRef clientEntity = getLocalClientEntity(); ClientComponent clientComponent = clientEntity.getComponent(ClientComponent.class); return clientComponent.character; } /* * Overrides the toggle method of the Button State Interface for the flying button */ @Override public void toggle() { MovementMode nextMode = MovementMode.WALKING; if (getMovementMode() != MovementMode.FLYING) { nextMode = MovementMode.FLYING; } getLocalCharacterEntity().send(new SetMovementModeEvent(nextMode)); setNewSpeed(); } /** * This private method sets the new speed when the flying mode is toggled by clicking the button */ private void setNewSpeed(){ MovementMode move = getMovementMode(); // We create a new Speed object, according to the CodeMap city Speed newSpeed = new CodeMapSpeed(); ClientComponent clientComp = getLocalClientEntity().getComponent(ClientComponent.class); CharacterMovementComponent newMove = clientComp.character.getComponent(CharacterMovementComponent.class); if (move == MovementMode.FLYING) { // We must save the position before the fly mode was toggled saveOldPosition(clientComp); // We place a mark, in the place we start flying placeTorchMarks(clientComp.character.getComponent(LocationComponent.class)); // Calling of the method that calculates the speed newMove.speedMultiplier = newSpeed.getCalculatedSpeed(); clientComp.character.saveComponent(newMove); console.addMessage("Speed multiplier set to " + newMove.speedMultiplier + " (was 1.0f)"); console.addMessage("Max height of the map: " + newSpeed.getMaxHeight()); } else{ // In this case we're toggling the walking mode. We need to get back to the old position. goBack(clientComp); newMove.speedMultiplier = 1.0f; clientComp.character.saveComponent(newMove); console.addMessage("Setting the speed multiplier to the original value (1.0f)"); } } /** * @param clientComp Instance of the current ClientComponent * Helper method that changes back the position of the character to the old position (Before flying). */ private void goBack(ClientComponent clientComp) { // Deactivate the character to reset the CharacterPredictionSystem, // which would overwrite the character location clientComp.character.send(BeforeDeactivateComponent.newInstance()); LocationComponent newLocation = clientComp.character.getComponent(LocationComponent.class); console.addMessage("Current position is: " + newLocation.getWorldPosition().toString()); newLocation.setWorldPosition(this.oldLocation); clientComp.character.saveComponent(newLocation); // We must reactive the character clientComp.character.send(OnActivatedComponent.newInstance()); console.addMessage("You're back to the initial position. You're in: "+ this.oldLocation.toString()); } /** * @param locationComponent Component of the location of the character. Received when the button is clicked, for getting back to the surface. * Method that places a torch at the position that the character was when the button is clicked for going back. */ private void placeTorchMarks(LocationComponent locationComponent) { BlockFamily blockFamily = blockManager.getBlockFamily("core:Torch"); WorldProvider world = CoreRegistry.get(WorldProvider.class); if (world != null) { world.setBlock(new Vector3i((int) locationComponent.getWorldPosition().x, (int) locationComponent.getWorldPosition().y, (int) locationComponent.getWorldPosition().z), blockFamily.getArchetypeBlock()); } } /** * @param clientComp Instance of the current ClientComponent * Method that saves the position of the character before flying. */ private void saveOldPosition(ClientComponent clientComp) { LocationComponent oldLocation = clientComp.character.getComponent(LocationComponent.class); this.oldLocation = oldLocation.getWorldPosition(); console.addMessage("Saved the initial position. It was: "+ this.oldLocation.toString()); } @Override public boolean isValid() { return true; } /** * @return An instance of the current movement mode of the character * Method that returns the current movement mode of the character */ private MovementMode getMovementMode() { EntityRef character = getLocalCharacterEntity(); CharacterMovementComponent movementComponent = character.getComponent(CharacterMovementComponent.class); return movementComponent.mode; } /* * Set the right text into the button label */ @Override public String getText() { switch (getMovementMode()) { case CLIMBING: return "Climbing"; case FLYING: return "Flying"; case SWIMMING: return "Swimming"; case WALKING: return "Walking"; case GHOSTING: return "Ghosting"; default: return "Unknown"; } } }
modules/FlyMode/src/main/java/flyMode/FlyMode.java
package flyMode; import org.terasology.HUDToggleButtons.systems.HUDToggleButtonsClientSystem; import org.terasology.entitySystem.entity.EntityManager; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent; import org.terasology.entitySystem.entity.lifecycleEvents.OnActivatedComponent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.characters.CharacterMovementComponent; import org.terasology.logic.characters.MovementMode; import org.terasology.logic.characters.events.SetMovementModeEvent; import org.terasology.logic.console.Console; import org.terasology.logic.location.LocationComponent; import org.terasology.math.geom.Vector3f; import org.terasology.math.geom.Vector3i; import org.terasology.network.ClientComponent; import org.terasology.registry.CoreRegistry; import org.terasology.registry.In; import org.terasology.world.WorldProvider; import org.terasology.world.block.BlockManager; import org.terasology.world.block.family.BlockFamily; import org.terasology.world.generator.WorldGenerator; import speedAlgorithm.CodeMapSpeed; import speedAlgorithm.Speed; /** * Class that toggles the Flying mode in Terasology when clicking a button */ @RegisterSystem public class FlyMode extends BaseComponentSystem implements HUDToggleButtonsClientSystem.HUDToggleButtonState { @In private HUDToggleButtonsClientSystem toggleButtonsClientSystem; @In private EntityManager entityManager; @In private Console console; @In private WorldGenerator worldGenerator; @In private BlockManager blockManager; private EntityRef localClientEntity; private Vector3f oldLocation; /* * @see org.terasology.entitySystem.systems.BaseComponentSystem#initialise() * We do override of this method for register the button into the GUI. */ @Override public void initialise() { toggleButtonsClientSystem.registerToggleButton(this); } /** * @return localClientEntity A reference to the local client Entity * Get the current client Entity (The local one) */ private EntityRef getLocalClientEntity() { if (localClientEntity == null) { for (EntityRef entityRef : entityManager.getEntitiesWith(ClientComponent.class)) { ClientComponent clientComponent = entityRef.getComponent(ClientComponent.class); if (clientComponent.local) { localClientEntity = entityRef; break; } } } return localClientEntity; } /** * @return EntityRef A reference to the local character Entity * Get the current character Entity (The local one) */ private EntityRef getLocalCharacterEntity() { EntityRef clientEntity = getLocalClientEntity(); ClientComponent clientComponent = clientEntity.getComponent(ClientComponent.class); return clientComponent.character; } /* * Overrides the toggle method of the Button State Interface for the flying button */ @Override public void toggle() { MovementMode nextMode = MovementMode.WALKING; if (getMovementMode() != MovementMode.FLYING) { nextMode = MovementMode.FLYING; } getLocalCharacterEntity().send(new SetMovementModeEvent(nextMode)); setNewSpeed(); } /** * This private method sets the new speed when the flying mode is toggled by clicking the button */ private void setNewSpeed(){ MovementMode move = getMovementMode(); // We create a new Speed object, according to the CodeMap city Speed newSpeed = new CodeMapSpeed(); ClientComponent clientComp = getLocalClientEntity().getComponent(ClientComponent.class); CharacterMovementComponent newMove = clientComp.character.getComponent(CharacterMovementComponent.class); if (move == MovementMode.FLYING) { // We must save the position before the fly mode was toggled saveOldPosition(clientComp); // Calling of the method that calculates the speed newMove.speedMultiplier = newSpeed.getCalculatedSpeed(); clientComp.character.saveComponent(newMove); console.addMessage("Speed multiplier set to " + newMove.speedMultiplier + " (was 1.0f)"); console.addMessage("Max height of the map: " + newSpeed.getMaxHeight()); } else{ // In this case we're toggling the walking mode. We need to get back to the old position. placeTorchMarks(clientComp.character.getComponent(LocationComponent.class)); goBack(clientComp); newMove.speedMultiplier = 1.0f; clientComp.character.saveComponent(newMove); console.addMessage("Setting the speed multiplier to the original value (1.0f)"); } } /** * @param clientComp Instance of the current ClientComponent * Helper method that changes back the position of the character to the old position (Before flying). */ private void goBack(ClientComponent clientComp) { // Deactivate the character to reset the CharacterPredictionSystem, // which would overwrite the character location clientComp.character.send(BeforeDeactivateComponent.newInstance()); LocationComponent newLocation = clientComp.character.getComponent(LocationComponent.class); console.addMessage("Current position is: " + newLocation.getWorldPosition().toString()); newLocation.setWorldPosition(this.oldLocation); clientComp.character.saveComponent(newLocation); // We must reactive the character clientComp.character.send(OnActivatedComponent.newInstance()); console.addMessage("You're back to the initial position. You're in: "+ this.oldLocation.toString()); } /** * @param locationComponent Component of the location of the character. Received when the button is clicked, for getting back to the surface. * Method that places a torch at the position that the character was when the button is clicked for going back. */ private void placeTorchMarks(LocationComponent locationComponent) { BlockFamily blockFamily = blockManager.getBlockFamily("core:Torch"); WorldProvider world = CoreRegistry.get(WorldProvider.class); if (world != null) { world.setBlock(new Vector3i((int) locationComponent.getWorldPosition().x, (int) locationComponent.getWorldPosition().y, (int) locationComponent.getWorldPosition().z), blockFamily.getArchetypeBlock()); } } /** * @param clientComp Instance of the current ClientComponent * Method that saves the position of the character before flying. */ private void saveOldPosition(ClientComponent clientComp) { LocationComponent oldLocation = clientComp.character.getComponent(LocationComponent.class); this.oldLocation = oldLocation.getWorldPosition(); console.addMessage("Saved the initial position. It was: "+ this.oldLocation.toString()); } @Override public boolean isValid() { return true; } /** * @return An instance of the current movement mode of the character * Method that returns the current movement mode of the character */ private MovementMode getMovementMode() { EntityRef character = getLocalCharacterEntity(); CharacterMovementComponent movementComponent = character.getComponent(CharacterMovementComponent.class); return movementComponent.mode; } /* * Set the right text into the button label */ @Override public String getText() { switch (getMovementMode()) { case CLIMBING: return "Climbing"; case FLYING: return "Flying"; case SWIMMING: return "Swimming"; case WALKING: return "Walking"; case GHOSTING: return "Ghosting"; default: return "Unknown"; } } }
We place a torch when we toggle the flying button, leaving there a mark.
modules/FlyMode/src/main/java/flyMode/FlyMode.java
We place a torch when we toggle the flying button, leaving there a mark.
Java
apache-2.0
cd759e8154da715175e86f893059b38a16708c88
0
tuijldert/jitsi,jibaro/jitsi,level7systems/jitsi,damencho/jitsi,dkcreinoso/jitsi,damencho/jitsi,gpolitis/jitsi,gpolitis/jitsi,459below/jitsi,level7systems/jitsi,jitsi/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,level7systems/jitsi,damencho/jitsi,459below/jitsi,iant-gmbh/jitsi,dkcreinoso/jitsi,HelioGuilherme66/jitsi,gpolitis/jitsi,gpolitis/jitsi,cobratbq/jitsi,bebo/jitsi,cobratbq/jitsi,ringdna/jitsi,damencho/jitsi,cobratbq/jitsi,iant-gmbh/jitsi,damencho/jitsi,level7systems/jitsi,cobratbq/jitsi,iant-gmbh/jitsi,bebo/jitsi,459below/jitsi,iant-gmbh/jitsi,pplatek/jitsi,tuijldert/jitsi,dkcreinoso/jitsi,ringdna/jitsi,jibaro/jitsi,pplatek/jitsi,dkcreinoso/jitsi,jitsi/jitsi,tuijldert/jitsi,bebo/jitsi,mckayclarey/jitsi,pplatek/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,martin7890/jitsi,level7systems/jitsi,martin7890/jitsi,jibaro/jitsi,gpolitis/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,tuijldert/jitsi,cobratbq/jitsi,bebo/jitsi,mckayclarey/jitsi,ringdna/jitsi,jitsi/jitsi,martin7890/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,martin7890/jitsi,tuijldert/jitsi,bebo/jitsi,dkcreinoso/jitsi,jibaro/jitsi,jitsi/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,jibaro/jitsi,ringdna/jitsi,mckayclarey/jitsi,459below/jitsi,jitsi/jitsi,459below/jitsi
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.plugin.jabberaccregwizz; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; import javax.imageio.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.table.*; import javax.xml.parsers.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.util.*; import org.jitsi.service.fileaccess.*; import org.jitsi.util.xml.*; import org.osgi.framework.*; import org.w3c.dom.*; import org.xml.sax.*; /** * A dialog that shows the list of available Jabber servers. * * @author Nicolas Grandclaude */ public class JabberServerChooserDialog extends SIPCommDialog implements ListSelectionListener { /** * Serial version UID. */ private static final long serialVersionUID = 0L; private static final Logger logger = Logger .getLogger(JabberServerChooserDialog.class); // Servers Table private JTable serversTable; private JTextArea chooseArea = new JTextArea(Resources .getString("plugin.jabberaccregwizz.CHOOSE_SERVER_TEXT")); // Panel private JPanel mainPanel = new TransparentPanel(new BorderLayout()); private JPanel buttonPanel = new TransparentPanel(new FlowLayout( FlowLayout.RIGHT)); private Box buttonBox = new Box(BoxLayout.X_AXIS); private JPanel chooseAreaPanel = new TransparentPanel(new BorderLayout()); private JPanel westPanel = new TransparentPanel(new BorderLayout(10, 10)); private JPanel eastPanel = new TransparentPanel(new BorderLayout(10, 10)); private JLabel westIconLabel = new JLabel(); private JButton okButton = new JButton(Resources.getString("service.gui.OK")); private JButton cancelButton = new JButton(Resources .getString("service.gui.CANCEL")); private Vector<String> servers = new Vector<String>(); private FileAccessService faService = null; private String[] columnNames = { Resources.getString("plugin.jabberaccregwizz.SERVER_COLUMN"), Resources.getString("plugin.jabberaccregwizz.COMMENT_COLUMN")}; /** * If the OK button is pressed. */ public boolean isOK = false; /** * The selected server. */ public String serverSelected; /** * Creates an instance of <tt>JabberServerChooserDialog</tt>. */ public JabberServerChooserDialog() { this.setSize(new Dimension(550, 450)); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setTitle(Resources.getString( "plugin.jabberaccregwizz.CHOOSE_SERVER_TITLE")); this.setModal(true); // Place the window in the center Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(screenSize.width / 2 - this.getWidth() / 2, screenSize.height / 2 - this.getHeight() / 2); this.init(); } /** * Initializes all panels, buttons, etc. */ private void init() { chooseArea.setEditable(false); chooseArea.setOpaque(false); chooseArea.setLineWrap(true); chooseArea.setWrapStyleWord(true); chooseAreaPanel .setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 10)); chooseAreaPanel.add(chooseArea, BorderLayout.NORTH); eastPanel.add(chooseAreaPanel, BorderLayout.NORTH); // West Jabber icon westIconLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(20, 20, 20, 20), BorderFactory .createTitledBorder(""))); try { westIconLabel.setIcon(new ImageIcon(ImageIO .read(new ByteArrayInputStream(Resources .getImage(Resources.PAGE_IMAGE))))); } catch (IOException e) { logger.error("Could not read image.", e); } this.westPanel.add(westIconLabel, BorderLayout.NORTH); this.mainPanel.add(westPanel, BorderLayout.WEST); // Table with servers and comments serversTable = new JTable(new ServerChooserTableModel()); serversTable.setRowHeight(22); serversTable.getSelectionModel().addListSelectionListener(this); serversTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); serversTable.setPreferredScrollableViewportSize(new Dimension(500, 70)); // Fill the servers array with servers from servers.xml fillTable(); JScrollPane scrollPane = new JScrollPane(serversTable); eastPanel.add(scrollPane, BorderLayout.CENTER); // Ok button okButton.setMnemonic(Resources.getMnemonic("service.gui.OK")); okButton.setEnabled(false); // Cancel button cancelButton.setMnemonic(Resources.getMnemonic("service.gui.CANCEL")); // Box with Ok and Cancel buttonBox.setBorder(new EmptyBorder(new Insets(5, 10, 5, 10))); buttonBox.add(okButton); buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(cancelButton); buttonPanel.add(buttonBox); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { isOK = true; dispose(); } }); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dispose(); } }); this.mainPanel.add(eastPanel, BorderLayout.CENTER); this.mainPanel.add(buttonPanel, BorderLayout.SOUTH); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); this.getContentPane().add(mainPanel, BorderLayout.CENTER); this.setVisible(true); } /** * Fill the servers array variable with data from the remote servers.xml */ public void fillTable() { BundleContext bc = JabberAccRegWizzActivator.bundleContext; ServiceReference faServiceReference = bc .getServiceReference(FileAccessService.class.getName()); faService = (FileAccessService) bc.getService(faServiceReference); File localServersListFile = null; try { localServersListFile = faService.getTemporaryFile(); URL file = new URL("https://xmpp.net/services.php"); InputStream stream = file.openStream(); try { // Copy the remote file to the disk byte[] buf = new byte[2048]; int len; if (stream.available() > 0) { FileOutputStream fos = new FileOutputStream(localServersListFile); while ((len = stream.read(buf)) > 0) { fos.write(buf, 0, len); } fos.close(); } } finally { stream.close(); } FileInputStream fis = new FileInputStream(localServersListFile); DocumentBuilder constructor = XMLUtils.newDocumentBuilderFactory().newDocumentBuilder(); Document document = constructor.parse(fis); Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("item"); // Read the xml and fill servers variable for the JTable for (int i = 0; i < list.getLength(); i++) { Element e = (Element) list.item(i); servers.add(new String(e.getAttribute("jid"))); } fis.close(); } catch (Exception e) { logger.error( "Failed to get a reference to the Jabber servers list file.", e); } finally { if (localServersListFile != null) { localServersListFile.delete(); } } } /** * When a table row is selected enable the "Ok" button, otherwise disable it. */ public void valueChanged(ListSelectionEvent e) { int row = serversTable.getSelectedRow(); if (row != -1) { okButton.setEnabled(true); serverSelected = (String) serversTable.getValueAt(row, 0); } else { okButton.setEnabled(false); } } @Override protected void close(boolean isEscaped) { cancelButton.doClick(); } /** * The table model used for the table containing all servers. */ private class ServerChooserTableModel extends AbstractTableModel { /** * Serial version UID. */ private static final long serialVersionUID = 0L; private Document serverComments; private NodeList commentsList; public ServerChooserTableModel() { try { // Create the builder and parse the file serverComments = XMLUtils.newDocumentBuilderFactory().newDocumentBuilder() .parse(Resources.getPropertyInputStream( "plugin.jabberaccregwizz.SERVER_COMMENTS")); } catch (SAXException e) { logger.error("Failed to parse server comments.", e); } catch (ParserConfigurationException e) { logger.error("Failed to parse server comments.", e); } catch (IOException e) { logger.error("Failed to parse server comments.", e); } Element root = serverComments.getDocumentElement(); commentsList = root.getElementsByTagName("item"); } public int getColumnCount() { return 2; } public int getRowCount() { return servers.size(); } @Override public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { String commentString = new String(""); if (col == 0) // Column 1 (Server name) { return servers.get(row); } else { // Column 2 (Comment) int i = 0; Element e = (Element) commentsList.item(i); while ((i < commentsList.getLength()) && (e.getAttribute("jid").equals(servers.get(row)) == false)) { e = (Element) commentsList.item(i); i++; } if (e.getAttribute("jid").equals(servers.get(row))) { commentString = e.getAttribute("comment"); } return commentString; } } } }
src/net/java/sip/communicator/plugin/jabberaccregwizz/JabberServerChooserDialog.java
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.plugin.jabberaccregwizz; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; import javax.imageio.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.table.*; import javax.xml.parsers.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.util.*; import org.jitsi.service.fileaccess.*; import org.jitsi.util.xml.*; import org.osgi.framework.*; import org.w3c.dom.*; import org.xml.sax.*; /** * A dialog that shows the list of available Jabber servers. * * @author Nicolas Grandclaude */ public class JabberServerChooserDialog extends SIPCommDialog implements ListSelectionListener { /** * Serial version UID. */ private static final long serialVersionUID = 0L; private static final Logger logger = Logger .getLogger(JabberServerChooserDialog.class); // Servers Table private JTable serversTable; private JTextArea chooseArea = new JTextArea(Resources .getString("plugin.jabberaccregwizz.CHOOSE_SERVER_TEXT")); // Panel private JPanel mainPanel = new TransparentPanel(new BorderLayout()); private JPanel buttonPanel = new TransparentPanel(new FlowLayout( FlowLayout.RIGHT)); private Box buttonBox = new Box(BoxLayout.X_AXIS); private JPanel chooseAreaPanel = new TransparentPanel(new BorderLayout()); private JPanel westPanel = new TransparentPanel(new BorderLayout(10, 10)); private JPanel eastPanel = new TransparentPanel(new BorderLayout(10, 10)); private JLabel westIconLabel = new JLabel(); private JButton okButton = new JButton(Resources.getString("service.gui.OK")); private JButton cancelButton = new JButton(Resources .getString("service.gui.CANCEL")); private Vector<String> servers = new Vector<String>(); private FileAccessService faService = null; private String[] columnNames = { Resources.getString("plugin.jabberaccregwizz.SERVER_COLUMN"), Resources.getString("plugin.jabberaccregwizz.COMMENT_COLUMN")}; /** * If the OK button is pressed. */ public boolean isOK = false; /** * The selected server. */ public String serverSelected; /** * Creates an instance of <tt>JabberServerChooserDialog</tt>. */ public JabberServerChooserDialog() { this.setSize(new Dimension(550, 450)); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setTitle(Resources.getString( "plugin.jabberaccregwizz.CHOOSE_SERVER_TITLE")); this.setModal(true); // Place the window in the center Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(screenSize.width / 2 - this.getWidth() / 2, screenSize.height / 2 - this.getHeight() / 2); this.init(); } /** * Initializes all panels, buttons, etc. */ private void init() { chooseArea.setEditable(false); chooseArea.setOpaque(false); chooseArea.setLineWrap(true); chooseArea.setWrapStyleWord(true); chooseAreaPanel .setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 10)); chooseAreaPanel.add(chooseArea, BorderLayout.NORTH); eastPanel.add(chooseAreaPanel, BorderLayout.NORTH); // West Jabber icon westIconLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(20, 20, 20, 20), BorderFactory .createTitledBorder(""))); try { westIconLabel.setIcon(new ImageIcon(ImageIO .read(new ByteArrayInputStream(Resources .getImage(Resources.PAGE_IMAGE))))); } catch (IOException e) { logger.error("Could not read image.", e); } this.westPanel.add(westIconLabel, BorderLayout.NORTH); this.mainPanel.add(westPanel, BorderLayout.WEST); // Table with servers and comments serversTable = new JTable(new ServerChooserTableModel()); serversTable.setRowHeight(22); serversTable.getSelectionModel().addListSelectionListener(this); serversTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); serversTable.setPreferredScrollableViewportSize(new Dimension(500, 70)); // Fill the servers array with servers from servers.xml fillTable(); JScrollPane scrollPane = new JScrollPane(serversTable); eastPanel.add(scrollPane, BorderLayout.CENTER); // Ok button okButton.setMnemonic(Resources.getMnemonic("service.gui.OK")); okButton.setEnabled(false); // Cancel button cancelButton.setMnemonic(Resources.getMnemonic("service.gui.CANCEL")); // Box with Ok and Cancel buttonBox.setBorder(new EmptyBorder(new Insets(5, 10, 5, 10))); buttonBox.add(okButton); buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(cancelButton); buttonPanel.add(buttonBox); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { isOK = true; dispose(); } }); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dispose(); } }); this.mainPanel.add(eastPanel, BorderLayout.CENTER); this.mainPanel.add(buttonPanel, BorderLayout.SOUTH); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); this.getContentPane().add(mainPanel, BorderLayout.CENTER); this.setVisible(true); } /** * Fill the servers array variable with data from the remote servers.xml */ public void fillTable() { BundleContext bc = JabberAccRegWizzActivator.bundleContext; ServiceReference faServiceReference = bc .getServiceReference(FileAccessService.class.getName()); faService = (FileAccessService) bc.getService(faServiceReference); File localServersListFile = null; try { localServersListFile = faService.getTemporaryFile(); URL file = new URL("http://xmpp.net/services.xml"); InputStream stream = file.openStream(); try { // Copy the remote file to the disk byte[] buf = new byte[2048]; int len; if (stream.available() > 0) { FileOutputStream fos = new FileOutputStream(localServersListFile); while ((len = stream.read(buf)) > 0) { fos.write(buf, 0, len); } fos.close(); } } finally { stream.close(); } FileInputStream fis = new FileInputStream(localServersListFile); DocumentBuilder constructor = XMLUtils.newDocumentBuilderFactory().newDocumentBuilder(); Document document = constructor.parse(fis); Element root = document.getDocumentElement(); NodeList list = root.getElementsByTagName("item"); // Read the xml and fill servers variable for the JTable for (int i = 0; i < list.getLength(); i++) { Element e = (Element) list.item(i); servers.add(new String(e.getAttribute("jid"))); } fis.close(); } catch (Exception e) { logger.error( "Failed to get a reference to the Jabber servers list file.", e); } finally { if (localServersListFile != null) { localServersListFile.delete(); } } } /** * When a table row is selected enable the "Ok" button, otherwise disable it. */ public void valueChanged(ListSelectionEvent e) { int row = serversTable.getSelectedRow(); if (row != -1) { okButton.setEnabled(true); serverSelected = (String) serversTable.getValueAt(row, 0); } else { okButton.setEnabled(false); } } @Override protected void close(boolean isEscaped) { cancelButton.doClick(); } /** * The table model used for the table containing all servers. */ private class ServerChooserTableModel extends AbstractTableModel { /** * Serial version UID. */ private static final long serialVersionUID = 0L; private Document serverComments; private NodeList commentsList; public ServerChooserTableModel() { try { // Create the builder and parse the file serverComments = XMLUtils.newDocumentBuilderFactory().newDocumentBuilder() .parse(Resources.getPropertyInputStream( "plugin.jabberaccregwizz.SERVER_COMMENTS")); } catch (SAXException e) { logger.error("Failed to parse server comments.", e); } catch (ParserConfigurationException e) { logger.error("Failed to parse server comments.", e); } catch (IOException e) { logger.error("Failed to parse server comments.", e); } Element root = serverComments.getDocumentElement(); commentsList = root.getElementsByTagName("item"); } public int getColumnCount() { return 2; } public int getRowCount() { return servers.size(); } @Override public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { String commentString = new String(""); if (col == 0) // Column 1 (Server name) { return servers.get(row); } else { // Column 2 (Comment) int i = 0; Element e = (Element) commentsList.item(i); while ((i < commentsList.getLength()) && (e.getAttribute("jid").equals(servers.get(row)) == false)) { e = (Element) commentsList.item(i); i++; } if (e.getAttribute("jid").equals(servers.get(row))) { commentString = e.getAttribute("comment"); } return commentString; } } } }
Update URL for XMPP server list
src/net/java/sip/communicator/plugin/jabberaccregwizz/JabberServerChooserDialog.java
Update URL for XMPP server list
Java
apache-2.0
88217f99962aa4ca8408acad32cc0735e89fdcfc
0
andy2palantir/atlasdb,j-baker/atlasdb,palantir/atlasdb,sh4nth/atlasdb-1,j-baker/atlasdb,andy2palantir/atlasdb,EvilMcJerkface/atlasdb,j-baker/atlasdb,palantir/atlasdb,sh4nth/atlasdb-1,EvilMcJerkface/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb
/** * Copyright 2015 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.keyvalue.rdbms.utils; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import java.util.SortedMap; import javax.annotation.Nullable; import org.skife.jdbi.v2.SQLStatement; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.RangeRequest; import com.palantir.atlasdb.keyvalue.api.RangeRequests; import com.palantir.atlasdb.keyvalue.api.RowResult; import com.palantir.atlasdb.keyvalue.api.Value; import com.palantir.atlasdb.keyvalue.impl.Cells; import com.palantir.util.Pair; public class AtlasSqlUtils { private AtlasSqlUtils() { } public static final String USER_TABLE_PREFIX = "atlasdb_usr_table_"; public static final String USR_TABLE(String tableName) { return USER_TABLE_PREFIX + tableName; } public static final String USR_TABLE(String tableName, String alias) { return USR_TABLE(tableName) + " " + alias; } private static final int CHUNK_SIZE = 200; public static final int MAX_TABLE_NAME_LEN = 128 + USER_TABLE_PREFIX.length(); public static <V> void batch(Iterable<V> items, Function<Collection<V>, Void> runWithBatch) { for (List<V> chunk : Iterables.partition(items, CHUNK_SIZE)) { runWithBatch.apply(chunk); } } public static int getBatchSize(RangeRequest rangeRequest) { return rangeRequest.getBatchHint() == null ? 100 : rangeRequest.getBatchHint(); } private static boolean throwableContainsMessage(Throwable e, String... messages) { for (Throwable ex = e; ex != null; ex = ex.getCause()) { for (String message : messages) { if (ex.getMessage().contains(message)) { return true; } } if (ex == ex.getCause()) { return false; } } return false; } public static boolean isKeyAlreadyExistsException(Throwable e) { return throwableContainsMessage(e, "ORA-00001", "unique constraint"); } public static <K, V> SetMultimap<K, V> listToSetMultimap(List<Pair<K, V>> list) { SetMultimap<K, V> result = HashMultimap.create(); for (Pair<K, V> p : list) { Preconditions.checkArgument(!result.containsEntry(p.lhSide, p.rhSide)); result.put(p.lhSide, p.rhSide); } return result; } public static <K, V> Map<K, V> listToMap(List<Pair<K, V>> list) { Map<K, V> result = Maps.newHashMap(); for (Pair<K, V> p : list) { Preconditions.checkArgument(!result.containsKey(p.lhSide)); result.put(p.lhSide, p.rhSide); } return result; } public static <T> Set<RowResult<Set<T>>> cellsToRows(SetMultimap<Cell, T> cells) { Set<RowResult<Set<T>>> result = Sets.newHashSet(); NavigableMap<byte[], SortedMap<byte[], Set<T>>> s = Cells.breakCellsUpByRow(Multimaps.asMap(cells)); for (Entry<byte[], SortedMap<byte[], Set<T>>> e : s.entrySet()) { result.add(RowResult.create(e.getKey(), e.getValue())); } return result; } public static <T> List<RowResult<T>> cellsToRows(Map<Cell, T> cells) { NavigableMap<byte[],SortedMap<byte[],T>> byRow = Cells.breakCellsUpByRow(cells); List<RowResult<T>> result = Lists.newArrayList(); for (Entry<byte[], SortedMap<byte[], T>> e : byRow.entrySet()) { result.add(RowResult.create(e.getKey(), e.getValue())); } return result; } @Nullable public static byte[] generateToken(RangeRequest rangeRequest, List<byte[]> rows) { Preconditions.checkArgument(!rangeRequest.isReverse()); Preconditions.checkArgument(rows.size() > 0); byte[] lastRow = rows.get(rows.size() - 1); if (RangeRequests.isLastRowName(lastRow)) { return null; } return RangeRequests.getNextStartRow(rangeRequest.isReverse(), lastRow); } public static String makeSlots(String prefix, int number) { String result = ""; for (int i=0; i<number; ++i) { result += ":" + prefix + i; if (i + 1 < number) { result += ", "; } } return result; } public static String makeSlots(String prefix, int number, int arity) { Preconditions.checkArgument(arity > 0); String result = ""; for (int i=0; i<number; ++i) { result += "("; for (int j=0; j<arity; ++j) { result += ":" + prefix + i + "_" + j; if (j + 1 < arity) { result += ", "; } } result += ")"; if (i + 1 < number) { result += ", "; } } return result; } public static <T> void bindAll(SQLStatement<?> query, Iterable<T> values) { bindAll(query, values, 0); } public static <T> void bindAll(SQLStatement<?> query, Iterable<T> values, int startPosition) { int pos = startPosition; for (T value : values) { query.bind(pos++, value); } } public static void bindCells(SQLStatement<?> query, Iterable<Cell> cells) { bindCells(query, cells, 0); } public static void bindCells(SQLStatement<?> query, Iterable<Cell> cells, int startPosition) { int pos = startPosition; for (Cell cell : cells) { query.bind(pos++, cell.getRowName()); query.bind(pos++, cell.getColumnName()); } } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, Value>> values) { bindCellsValues(query, values, 0); } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, Value>> values, int startPosition) { int pos = startPosition; for (Entry<Cell, Value> entry : values) { query.bind(pos++, entry.getKey().getRowName()); query.bind(pos++, entry.getKey().getColumnName()); query.bind(pos++, entry.getValue().getTimestamp()); query.bind(pos++, entry.getValue().getContents()); } } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, byte[]>> values, long timestamp) { bindCellsValues(query, values, timestamp, 0); } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, byte[]>> values, long timestamp, int startPosition) { int pos = startPosition; for (Entry<Cell, byte[]> entry : values) { query.bind(pos++, entry.getKey().getRowName()); query.bind(pos++, entry.getKey().getColumnName()); query.bind(pos++, timestamp); query.bind(pos++, entry.getValue()); } } public static void bindCellsTimestamps(SQLStatement<?> query, Iterable<Entry<Cell, Long>> values) { bindCellsTimestamps(query, values, 0); } public static void bindCellsTimestamps(SQLStatement<?> query, Iterable<Entry<Cell, Long>> values, int startPosition) { int pos = startPosition; for (Entry<Cell, Long> entry : values) { query.bind(pos++, entry.getKey().getRowName()); query.bind(pos++, entry.getKey().getColumnName()); query.bind(pos++, entry.getValue()); } } }
atlasdb-rdbms/src/main/java/com/palantir/atlasdb/keyvalue/rdbms/utils/AtlasSqlUtils.java
/** * Copyright 2015 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.keyvalue.rdbms.utils; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import java.util.SortedMap; import javax.annotation.Nullable; import org.skife.jdbi.v2.SQLStatement; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.RangeRequest; import com.palantir.atlasdb.keyvalue.api.RangeRequests; import com.palantir.atlasdb.keyvalue.api.RowResult; import com.palantir.atlasdb.keyvalue.api.Value; import com.palantir.atlasdb.keyvalue.impl.Cells; import com.palantir.util.Pair; public class AtlasSqlUtils { private AtlasSqlUtils() { } public static final String USER_TABLE_PREFIX = "atlasdb_usr_table_"; public static final String USR_TABLE(String tableName) { return USER_TABLE_PREFIX + tableName; } public static final String USR_TABLE(String tableName, String alias) { return USR_TABLE(tableName) + " " + alias; } private static final int CHUNK_SIZE = 200; public static final int MAX_TABLE_NAME_LEN = 128 + USER_TABLE_PREFIX.length(); public static <V> void batch(Iterable<V> items, Function<Collection<V>, Void> runWithBatch) { for (List<V> chunk : Iterables.partition(items, CHUNK_SIZE)) { runWithBatch.apply(chunk); } } public static int getBatchSize(RangeRequest rangeRequest) { return rangeRequest.getBatchHint() == null ? 100 : rangeRequest.getBatchHint(); } private static boolean throwableContainsMessage(Throwable e, String... messages) { for (Throwable ex = e; ex != null; ex = ex.getCause()) { for (String message : messages) { if (ex.getMessage().contains(message)) { return true; } } if (ex == ex.getCause()) { return false; } } return false; } public static boolean isKeyAlreadyExistsException(Throwable e) { return throwableContainsMessage(e, "ORA-00001", "unique constraint"); } public static <K, V> SetMultimap<K, V> listToSetMultimap(List<Pair<K, V>> list) { SetMultimap<K, V> result = HashMultimap.create(); for (Pair<K, V> p : list) { result.put(p.lhSide, p.rhSide); } return result; } public static <K, V> Map<K, V> listToMap(List<Pair<K, V>> list) { Map<K, V> result = Maps.newHashMap(); for (Pair<K, V> p : list) { Preconditions.checkArgument(!result.containsKey(p.lhSide)); result.put(p.lhSide, p.rhSide); } return result; } public static <T> Set<RowResult<Set<T>>> cellsToRows(SetMultimap<Cell, T> cells) { Set<RowResult<Set<T>>> result = Sets.newHashSet(); NavigableMap<byte[], SortedMap<byte[], Set<T>>> s = Cells.breakCellsUpByRow(Multimaps.asMap(cells)); for (Entry<byte[], SortedMap<byte[], Set<T>>> e : s.entrySet()) { result.add(RowResult.create(e.getKey(), e.getValue())); } return result; } public static <T> List<RowResult<T>> cellsToRows(Map<Cell, T> cells) { NavigableMap<byte[],SortedMap<byte[],T>> byRow = Cells.breakCellsUpByRow(cells); List<RowResult<T>> result = Lists.newArrayList(); for (Entry<byte[], SortedMap<byte[], T>> e : byRow.entrySet()) { result.add(RowResult.create(e.getKey(), e.getValue())); } return result; } @Nullable public static byte[] generateToken(RangeRequest rangeRequest, List<byte[]> rows) { Preconditions.checkArgument(!rangeRequest.isReverse()); Preconditions.checkArgument(rows.size() > 0); byte[] lastRow = rows.get(rows.size() - 1); if (RangeRequests.isLastRowName(lastRow)) { return null; } return RangeRequests.getNextStartRow(rangeRequest.isReverse(), lastRow); } public static String makeSlots(String prefix, int number) { String result = ""; for (int i=0; i<number; ++i) { result += ":" + prefix + i; if (i + 1 < number) { result += ", "; } } return result; } public static String makeSlots(String prefix, int number, int arity) { Preconditions.checkArgument(arity > 0); String result = ""; for (int i=0; i<number; ++i) { result += "("; for (int j=0; j<arity; ++j) { result += ":" + prefix + i + "_" + j; if (j + 1 < arity) { result += ", "; } } result += ")"; if (i + 1 < number) { result += ", "; } } return result; } public static <T> void bindAll(SQLStatement<?> query, Iterable<T> values) { bindAll(query, values, 0); } public static <T> void bindAll(SQLStatement<?> query, Iterable<T> values, int startPosition) { int pos = startPosition; for (T value : values) { query.bind(pos++, value); } } public static void bindCells(SQLStatement<?> query, Iterable<Cell> cells) { bindCells(query, cells, 0); } public static void bindCells(SQLStatement<?> query, Iterable<Cell> cells, int startPosition) { int pos = startPosition; for (Cell cell : cells) { query.bind(pos++, cell.getRowName()); query.bind(pos++, cell.getColumnName()); } } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, Value>> values) { bindCellsValues(query, values, 0); } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, Value>> values, int startPosition) { int pos = startPosition; for (Entry<Cell, Value> entry : values) { query.bind(pos++, entry.getKey().getRowName()); query.bind(pos++, entry.getKey().getColumnName()); query.bind(pos++, entry.getValue().getTimestamp()); query.bind(pos++, entry.getValue().getContents()); } } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, byte[]>> values, long timestamp) { bindCellsValues(query, values, timestamp, 0); } public static void bindCellsValues(SQLStatement<?> query, Iterable<Entry<Cell, byte[]>> values, long timestamp, int startPosition) { int pos = startPosition; for (Entry<Cell, byte[]> entry : values) { query.bind(pos++, entry.getKey().getRowName()); query.bind(pos++, entry.getKey().getColumnName()); query.bind(pos++, timestamp); query.bind(pos++, entry.getValue()); } } public static void bindCellsTimestamps(SQLStatement<?> query, Iterable<Entry<Cell, Long>> values) { bindCellsTimestamps(query, values, 0); } public static void bindCellsTimestamps(SQLStatement<?> query, Iterable<Entry<Cell, Long>> values, int startPosition) { int pos = startPosition; for (Entry<Cell, Long> entry : values) { query.bind(pos++, entry.getKey().getRowName()); query.bind(pos++, entry.getKey().getColumnName()); query.bind(pos++, entry.getValue()); } } }
Add precondition check.
atlasdb-rdbms/src/main/java/com/palantir/atlasdb/keyvalue/rdbms/utils/AtlasSqlUtils.java
Add precondition check.
Java
apache-2.0
25f12317c490bf9a1d8e431d205bb5f7db6b5e87
0
BruceZu/sawdust,BruceZu/sawdust,BruceZu/sawdust,BruceZu/sawdust
// Copyright 2021 The KeepTry Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package tree.binarytree.binary_balance_tree; import java.util.ArrayList; public class Leetcode1382BalanceaBinarySearchTree { /* Leetcode 1382. Balance a Binary Search Tree Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] see the picture in Leetcode web site Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct. Input: root = [2,1,3] Output: [2,1,3] The number of nodes in the tree is in the range [1, 10^4]. 1 <= Node.val <= 10^5 */ static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } /* inorder => array array => rebuild balanced binary tree O(N) time and space */ public TreeNode balanceBST(TreeNode root) { ArrayList<TreeNode> a = new ArrayList(); inorder(root, a); return make(0, a.size() - 1, a); } private void inorder(TreeNode n, ArrayList<TreeNode> a) { if (n == null) return; inorder(n.left, a); a.add(n); inorder(n.right, a); } private TreeNode make(int l, int r, ArrayList<TreeNode> a) { if (l > r) return null; int m = l + r >>> 1; TreeNode n = a.get(m); n.left = make(l, m - 1, a); n.right = make(m + 1, r, a); return n; } /* refer https://leetcode.com/problems/balance-a-binary-search-tree/discuss/541785/C%2B%2BJava-with-picture-DSW-O(n)orO(1) https://courses.cs.vt.edu/cs2604/spring05/mcpherson/note/BalancingTrees.pdf wiki: The Day–Stout–Warren (DSW) algorithm is a method for efficiently balancing binary search trees that is, decreasing their height to O(log n) nodes, where n is the total number of nodes. Unlike a self-balancing binary search tree, it does not do this incrementally during each operation, but periodically, so that its cost can be amortized over many operations. The algorithm requires linear O(n) time and is in-place O(1) space Steps 1> convert the tree into a vine (like linked list) using right rotations: in advance, need a dumb node, let node be the dumb right child, dumb \ cur node / \ left right / \ ll lr if node has left child, right rotations result: - dumb.right is node's left child - node becomes node's left child' right child - left child's right sub tree become node left sub-tree dumb \ left ( new cur node) / \ ll old cur node / \ lr right continue from the left child which is current node else dumb = dumb.right child. if dumb is null break the loop The head is the former leftmost node, tail is former rightmost node during the process when dumb switch to dumb.right, count the total number of nodes in variable cnt. 2> balance the list using left rotations rotation https://hyperleap.com/topic/Tree_rotation right rotation see http://web.stanford.edu/class/archive/cs/cs161/cs161.1166/lectures/lecture7.pdf left rotation is the movement of a x X L R RL RR => R X RR L RL left rotation assumes that X has a right child (or subtree). see https://web.stanford.edu/class/archive/cs/cs166/cs166.1146/lectures/02/Small02.pdf The height of a binary search tree is the length of the longest path from the root to a leaf, measured in the number of edges. - A tree with one node has height 0. A tree with no nodes has height -1, by convention high = (int)log(n) , layers = high+1 A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level. ----------------------------------------------- m high 1 0 2 3 1 4 5 6 7 2 8 9 10 11 12 13 14 15 3 ----------------------------------------------- BST value m high number of current layer 8 1 0 1 4 12 3 1 2 2 6 10 14 7 2 4 1 3 5 7 9 11 13 15 15 3 8 16 ----------------------------------------------- let m be the total nodes of the closest perfect binary tree let n is the BST nodes number relation between n and m: E.g. for n in [8,14] m=7, for n=15, m=15 m = [2^((int)log(n+1)]-1 So the node difference between the perfect tree and the tree to be balanced can be calculated by n-m In order to get away with this excess of node, not in the closest perfect tree, left rotation is performed on every SECOND node of the list(why? flat) dumb \ 1 \ 2 \ 3 \ 4 .. after 2 times of left rotation => dumb \ 2 / \ 1 4 / \ 3 5 \ 6 \ 7 \ 8 \ 9 2-4-5-6-7-8-9, 7 nodes will form the closest perfect binary tree left rotation is performed on every SECOND node of the list - while cur and cur.right is not null(x) - 7/2=3 times becomes: dumb \ 4 / \ 2 6 /\ /\ 1 3 5 8 /\ 7 9 left rotation is performed on every SECOND node of the list - while cur and cur.right is not null(x) - 3/2=1 time dumb \ 6 / \ 4 8 / \ / \ 2 5 7 9 /\ 1 3 */ public static TreeNode balanceBST_(TreeNode root) { TreeNode dumb = new TreeNode(0); // 1 <= Node.val <= 10^5 dumb.right = root; int sum = toList(dumb); // m: the number of closet perfect tree nodes number // m = [2^((int)log(n+1)]-1 int m = (int) Math.pow(2, (int) (Math.log(sum + 1) / Math.log(2))) - 1; rebuildBST(dumb, sum - m); for (m >>>= 1; m > 0; m >>>= 1) { rebuildBST(dumb, m); } return dumb.right; } // and return the number of all nodes // d will be the leaf node at last static int toList(TreeNode d) { int sum = 0; TreeNode n = d.right; while (n != null) { if (n.left != null) { TreeNode p = n; // pointer to n n = n.left; p.left = n.right; n.right = p; d.right = n; } else { // not change the tree structure, just go through along right sub-tree, so the outer // dumb.right will be // the left most node of the original tree sum++; d = n; n = n.right; } } return sum; } // left rotation with given times, performed on every second node of the list static void rebuildBST(TreeNode dumb, int times) { TreeNode n = dumb.right; while (times-- > 0) { TreeNode p = n; n = n.right; dumb.right = n; p.right = n.left; n.left = p; dumb = n; n = n.right; } } // -------------------------------------------------------------------------- public static void main(String[] args) { /* cur node4 / \ left2 right5 / \ ll1 lr3 */ TreeNode root = new TreeNode(4); root.left = new TreeNode(2); root.right = new TreeNode(5); root.left.left = new TreeNode(1); root.left.right = new TreeNode(3); TreeNode dumb = new TreeNode(0); // 1 <= Node.val <= 10^5 dumb.right = root; int sum = toList(dumb); } int toListNoDumb(TreeNode cur) { int sum = 0; while (cur != null) { if (cur.left != null) { TreeNode l = cur.left; cur.left = l.right; l.right = cur; cur = l; } else { sum++; cur = cur.right; } } return sum; } }
arrows/src/main/java/tree/binarytree/binary_balance_tree/Leetcode1382BalanceaBinarySearchTree.java
// Copyright 2021 The KeepTry Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package tree.binarytree.binary_balance_tree; import java.util.ArrayList; public class Leetcode1382BalanceaBinarySearchTree { /* Leetcode 1382. Balance a Binary Search Tree Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1. Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] see the picture in Leetcode web site Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct. Input: root = [2,1,3] Output: [2,1,3] The number of nodes in the tree is in the range [1, 10^4]. 1 <= Node.val <= 10^5 */ static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } /* inorder => array array => rebuild balanced binary tree O(N) time and space */ public TreeNode balanceBST(TreeNode root) { ArrayList<TreeNode> a = new ArrayList(); inorder(root, a); return make(0, a.size() - 1, a); } private void inorder(TreeNode n, ArrayList<TreeNode> a) { if (n == null) return; inorder(n.left, a); a.add(n); inorder(n.right, a); } private TreeNode make(int l, int r, ArrayList<TreeNode> a) { if (l > r) return null; int m = l + r >>> 1; TreeNode n = a.get(m); n.left = make(l, m - 1, a); n.right = make(m + 1, r, a); return n; } /* refer https://leetcode.com/problems/balance-a-binary-search-tree/discuss/541785/C%2B%2BJava-with-picture-DSW-O(n)orO(1) https://courses.cs.vt.edu/cs2604/spring05/mcpherson/note/BalancingTrees.pdf wiki: The Day–Stout–Warren (DSW) algorithm is a method for efficiently balancing binary search trees that is, decreasing their height to O(log n) nodes, where n is the total number of nodes. Unlike a self-balancing binary search tree, it does not do this incrementally during each operation, but periodically, so that its cost can be amortized over many operations. The algorithm requires linear O(n) time and is in-place O(1) space Steps 1> convert the tree into a vine (like linked list) using right rotations: in advance, need a dumb node, let node be the dumb right child, dumb \ cur node / \ left right / \ ll lr if node has left child, right rotations result: - dumb.right is node's left child - node becomes node's left child' right child - left child's right sub tree become node left sub-tree dumb \ left ( new cur node) / \ ll old cur node / \ lr right continue from the left child which is current node else dumb = dumb.right child. if dumb is null break the loop The head is the former leftmost node, tail is former rightmost node during the process when dumb switch to dumb.right, count the total number of nodes in variable cnt. 2> balance the list using left rotations rotation https://hyperleap.com/topic/Tree_rotation right rotation see http://web.stanford.edu/class/archive/cs/cs161/cs161.1166/lectures/lecture7.pdf left rotation is the movement of a x X L R RL RR => R X RR L RL left rotation assumes that X has a right child (or subtree). see https://web.stanford.edu/class/archive/cs/cs166/cs166.1146/lectures/02/Small02.pdf The height of a binary search tree is the length of the longest path from the root to a leaf, measured in the number of edges. - A tree with one node has height 0. A tree with no nodes has height -1, by convention high = (int)log(n) , layers = high+1 A perfect binary tree is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level. ----------------------------------------------- m high 1 0 2 3 1 4 5 6 7 2 8 9 10 11 12 13 14 15 3 ----------------------------------------------- BST value m high number of current layer 8 1 0 1 4 12 3 1 2 2 6 10 14 7 2 4 1 3 5 7 9 11 13 15 15 3 8 16 ----------------------------------------------- let m be the total nodes of the closest perfect binary tree let n is the BST nodes number relation between n and m: E.g. for n in [8,14] m=7, for n=15, m=15 m = [2^((int)log(n+1)]-1 So the node difference between the perfect tree and the tree to be balanced can be calculated by n-m In order to get away with this excess of node, not in the closest perfect tree, left rotation is performed on every SECOND node of the list(why? flat) dumb \ 1 \ 2 \ 3 \ 4 .. after 2 times of left rotation => 2 / \ 1 4 / \ 3 5 \ 6 \ 7 \ 8 \ 9 2-4-5-6-7-8-9, 7 nodes will form the closest perfect binary tree left rotation is performed on every SECOND node of the list - while cur and cur.right is not null(x) - 7/2=3 times becomes: 4 / \ 2 6 /\ /\ 1 3 5 8 /\ 7 9 left rotation is performed on every SECOND node of the list - while cur and cur.right is not null(x) - 3/2=1 time 6 / \ 4 8 / \ / \ 2 5 7 9 /\ 1 3 */ public static TreeNode balanceBST_(TreeNode root) { TreeNode dumb = new TreeNode(0); // 1 <= Node.val <= 10^5 dumb.right = root; int sum = toList(dumb); // m: the number of closet perfect tree nodes number // m = [2^((int)log(n+1)]-1 int m = (int) Math.pow(2, (int) (Math.log(sum + 1) / Math.log(2))) - 1; rebuildBST(dumb, sum - m); for (m = m / 2; m > 0; m /= 2) { rebuildBST(dumb, m); } return dumb.right; } // and return the number of all nodes // dumb is the leaf of the list tree. static int toList(TreeNode d) { int sum = 0; TreeNode cur = d.right; while (cur != null) { if (cur.left != null) { TreeNode p = cur; // pointer to n cur = cur.left; p.left = cur.right; cur.right = p; d.right = cur; } else { // not change the tree structure, just go through along right sub-tree, so the outer // dumb.right will be // the left most node of the original tree sum++; d = cur; cur = cur.right; } } return sum; } // left rotation with given times, performed on every second node of the list static void rebuildBST(TreeNode dumb, int times) { TreeNode cur = dumb.right; while (times-- > 0) { // cur!=null && cur.right!=null TreeNode p = cur; cur = cur.right; dumb.right = cur; p.right = cur.left; cur.left = p; dumb = cur; cur = cur.right; } } // -------------------------------------------------------------------------- public static void main(String[] args) { /* cur node4 / \ left2 right5 / \ ll1 lr3 */ TreeNode root = new TreeNode(4); root.left = new TreeNode(2); root.right = new TreeNode(5); root.left.left = new TreeNode(1); root.left.right = new TreeNode(3); TreeNode dumb = new TreeNode(0); // 1 <= Node.val <= 10^5 dumb.right = root; int sum = toList(dumb); } int toListNoDumb(TreeNode cur) { int sum = 0; while (cur != null) { if (cur.left != null) { TreeNode l = cur.left; cur.left = l.right; l.right = cur; cur = l; } else { sum++; cur = cur.right; } } return sum; } }
polish
arrows/src/main/java/tree/binarytree/binary_balance_tree/Leetcode1382BalanceaBinarySearchTree.java
polish
Java
apache-2.0
6a777c04255b9f1aff8445f0ebac9eacf661c43c
0
ops4j/org.ops4j.pax.cdi,ops4j/org.ops4j.pax.cdi
/* * Copyright 2016 Guillaume Nodet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.ops4j.pax.cdi.extension.impl.component2; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.felix.scr.impl.helper.ComponentMethod; import org.apache.felix.scr.impl.helper.ComponentMethods; import org.apache.felix.scr.impl.helper.ConfigAdminTracker; import org.apache.felix.scr.impl.helper.InitReferenceMethod; import org.apache.felix.scr.impl.helper.MethodResult; import org.apache.felix.scr.impl.helper.ReferenceMethod; import org.apache.felix.scr.impl.helper.ReferenceMethods; import org.apache.felix.scr.impl.helper.SimpleLogger; import org.apache.felix.scr.impl.manager.AbstractComponentManager; import org.apache.felix.scr.impl.manager.ComponentActivator; import org.apache.felix.scr.impl.manager.ComponentContainer; import org.apache.felix.scr.impl.manager.ComponentContextImpl; import org.apache.felix.scr.impl.manager.ComponentHolder; import org.apache.felix.scr.impl.manager.ConfigurableComponentHolder; import org.apache.felix.scr.impl.manager.DependencyManager; import org.apache.felix.scr.impl.manager.ExtendedServiceEvent; import org.apache.felix.scr.impl.manager.ExtendedServiceListener; import org.apache.felix.scr.impl.manager.PrototypeServiceFactoryComponentManager; import org.apache.felix.scr.impl.manager.RefPair; import org.apache.felix.scr.impl.manager.RegionConfigurationSupport; import org.apache.felix.scr.impl.manager.ScrConfiguration; import org.apache.felix.scr.impl.manager.ServiceFactoryComponentManager; import org.apache.felix.scr.impl.manager.SingleComponentManager; import org.apache.felix.scr.impl.metadata.ComponentMetadata; import org.apache.felix.scr.impl.metadata.TargetedPID; import org.ops4j.pax.cdi.extension.impl.compat.OsgiScopeUtils; import org.ops4j.pax.cdi.extension.impl.support.Consumer; import org.ops4j.pax.cdi.extension.impl.support.PrivateRegistryWrapper; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.ComponentConstants; import org.osgi.service.component.ComponentException; import org.osgi.service.log.LogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ComponentRegistry implements ComponentActivator, SimpleLogger { private static final Logger log = LoggerFactory.getLogger(ComponentRegistry.class); private final BeanManager beanManager; private final BundleContext bundleContext; private final Map<Bean<?>, AbstractDescriptor> descriptors = new HashMap<>(); private final List<ComponentHolder<?>> holders = new ArrayList<>(); private final Map<String, ComponentHolder<?>> holdersByName = new HashMap<>(); private final Map<String, Set<ComponentHolder<?>>> holdersByPid = new HashMap<>(); ConfigAdminTracker configAdminTracker; private final ScrConfiguration m_configuration = new ScrConfigurationImpl(); private final Map<String, ListenerInfo> listenerMap = new HashMap<>(); private final Map<ExtendedServiceListener, ServiceListener> privateListeners = new HashMap<>(); private final AtomicInteger componentId = new AtomicInteger(); private final Map<ServiceReference<?>, List<Entry>> m_missingDependencies = new HashMap<>(); private final ConcurrentMap<Long, RegionConfigurationSupport> bundleToRcsMap = new ConcurrentHashMap<>(); private final Executor m_componentActor = Executors.newSingleThreadExecutor(); private final AtomicBoolean started = new AtomicBoolean(); public ComponentRegistry(BeanManager beanManager, BundleContext bundleContext) { this.beanManager = beanManager; this.bundleContext = new PrivateRegistryWrapper(bundleContext); } public BeanManager getBeanManager() { return beanManager; } public void preStart(AfterBeanDiscovery event, GlobalDescriptor global) { for (AbstractDescriptor descriptor : descriptors.values()) { for (Bean<?> bean : descriptor.getProducers()) { event.addBean(bean); } } global.validate(this); global.pauseIfNeeded(); ComponentHolder<?> h; if (OsgiScopeUtils.hasPrototypeScope(bundleContext)) { h = new CdiComponentHolder6<>(this, global); } else { h = new CdiComponentHolder<>(this, global); } h.enableComponents(false); for (Bean<?> bean : global.getProducers()) { event.addBean(bean); } } private final ThreadLocal<List<ServiceReference<?>>> circularInfos = new ThreadLocal<> (); public <T> boolean enterCreate(final ServiceReference<T> serviceReference) { List<ServiceReference<?>> info = circularInfos.get(); if (info == null) { circularInfos.set(info = new ArrayList<>()); } if (info.contains(serviceReference)) { log(LogService.LOG_ERROR, "Circular reference detected trying to get service {0}: stack of references: {1}", new Object[] {serviceReference, info}, null); return true; } log(LogService.LOG_DEBUG, "getService {0}: stack of references: {1}", new Object[] {serviceReference, info}, null); info.add(serviceReference); return false; } public <T> void leaveCreate(final ServiceReference<T> serviceReference) { List<ServiceReference<?>> info = circularInfos.get(); if (info != null) { if (!info.isEmpty() && info.iterator().next().equals(serviceReference)) { circularInfos.remove(); } else { info.remove(serviceReference); } } } public void start() { if (!started.compareAndSet(false, true)) { return; } for (AbstractDescriptor d : descriptors.values()) { d.validate(this); ComponentHolder<?> h; if (OsgiScopeUtils.hasPrototypeScope(bundleContext)) { h = new CdiComponentHolder6<>(this, d); } else { h = new CdiComponentHolder<>(this, d); } holders.add(h); } for (ComponentHolder<?> h : holders) { if (holdersByName.put(h.getComponentMetadata().getName(), h) != null) { throw new ComponentException("The component name '{0}" + h.getComponentMetadata().getName() + "' has already been registered."); } } for (ComponentHolder<?> h : holders) { for (String pid : h.getComponentMetadata().getConfigurationPid()) { Set<ComponentHolder<?>> set = holdersByPid.get(pid); if (set == null) { set = new HashSet<>(); holdersByPid.put(pid, set); } set.add(h); } } ConfigAdminTracker tracker = null; for (ComponentHolder<?> holder : holders) { if (!holder.getComponentMetadata().isConfigurationIgnored()) { tracker = new ConfigAdminTracker(this); break; } } configAdminTracker = tracker; for (ComponentHolder<?> h : holders) { try { h.enableComponents(false); } catch (RuntimeException e) { h.disableComponents(false); throw e; } } } public ComponentDescriptor addComponent(Bean<Object> component) { ComponentDescriptor descriptor = new ComponentDescriptor(component, this); descriptors.put(component, descriptor); return descriptor; } public BundleContext getBundleContext() { return bundleContext; } public Set<Bean<?>> getComponents() { return descriptors.keySet(); } public ComponentDescriptor getDescriptor(Bean<?> component) { return (ComponentDescriptor) descriptors.get(component); } @Override public boolean isActive() { return true; } @Override public ScrConfiguration getConfiguration() { return m_configuration; } @Override public void schedule(Runnable runnable) { if (isActive()) { m_componentActor.execute(runnable); } } @Override public long registerComponentId(AbstractComponentManager<?> sAbstractComponentManager) { return componentId.incrementAndGet(); } @Override public void unregisterComponentId(AbstractComponentManager<?> sAbstractComponentManager) { } @Override public <S, T> void registerMissingDependency(org.apache.felix.scr.impl.manager.DependencyManager<S, T> dependencyManager, ServiceReference<T> serviceReference, int trackingCount) { //check that the service reference is from scr if (serviceReference.getProperty(ComponentConstants.COMPONENT_NAME) == null || serviceReference.getProperty(ComponentConstants.COMPONENT_ID) == null) { return; } List<Entry> dependencyManagers = m_missingDependencies.get(serviceReference); if (dependencyManagers == null) { dependencyManagers = new ArrayList<>(); m_missingDependencies.put(serviceReference, dependencyManagers); } dependencyManagers.add(new Entry(dependencyManager, trackingCount)); } @Override public <T> void missingServicePresent(final ServiceReference<T> serviceReference) { final List<Entry> dependencyManagers = m_missingDependencies.remove(serviceReference); if (dependencyManagers != null) { m_componentActor.execute(new Runnable() { public void run() { for (Entry entry : dependencyManagers) { DependencyManager<?, T> dm = entry.getDm(); dm.invokeBindMethodLate(serviceReference, entry.getTrackingCount()); } } @Override public String toString() { return "Late binding task of reference " + serviceReference + " for dependencyManagers " + dependencyManagers; } }); } } @Override public void enableComponent(String name) { final Collection<ComponentHolder<?>> holders = getComponentHoldersByName(name); for (ComponentHolder<?> holder : holders) { try { log(LogService.LOG_DEBUG, "Enabling Component", holder.getComponentMetadata(), null, null); holder.enableComponents(true); } catch (Throwable t) { log(LogService.LOG_ERROR, "Cannot enable component", holder.getComponentMetadata(), null, t); } } } @Override public void disableComponent(String name) { throw new UnsupportedOperationException(); } @Override public RegionConfigurationSupport setRegionConfigurationSupport(ServiceReference<ConfigurationAdmin> reference) { RegionConfigurationSupport trialRcs = new RegionConfigurationSupport(this, reference) { protected Collection<ComponentHolder<?>> getComponentHolders(TargetedPID pid) { return getComponentHoldersByPid(pid); } }; RegionConfigurationSupport rcs = registerRegionConfigurationSupport(trialRcs); for (ComponentHolder<?> holder : holders) { rcs.configureComponentHolder(holder); } return rcs; } public RegionConfigurationSupport registerRegionConfigurationSupport(RegionConfigurationSupport trialRcs) { Long bundleId = trialRcs.getBundleId(); RegionConfigurationSupport existing; RegionConfigurationSupport previous = null; while (true) { existing = bundleToRcsMap.putIfAbsent(bundleId, trialRcs); if (existing == null) { trialRcs.start(); return trialRcs; } if (existing == previous) { //the rcs we referenced is still current return existing; } if (existing.reference()) { //existing can still be used previous = existing; } else { //existing was discarded in another thread, start over previous = null; } } } @Override public void unsetRegionConfigurationSupport(RegionConfigurationSupport rcs) { if (rcs.dereference()) { bundleToRcsMap.remove(rcs.getBundleId()); } } public void addServiceListener(String classNameFilter, Filter eventFilter, final ExtendedServiceListener<ExtendedServiceEvent> listener) { if (eventFilter != null && eventFilter.toString().contains(PrivateRegistryWrapper.PRIVATE)) { synchronized (privateListeners) { ServiceListener l = new ServiceListener() { @Override public void serviceChanged(ServiceEvent event) { listener.serviceChanged(new ExtendedServiceEvent(event)); } }; privateListeners.put(listener, l); try { bundleContext.addServiceListener(l, "(&" + classNameFilter + eventFilter.toString() + ")"); } catch (InvalidSyntaxException e) { throw (IllegalArgumentException) new IllegalArgumentException( "invalid class name filter").initCause(e); } } return; } ListenerInfo listenerInfo; synchronized (listenerMap) { log(LogService.LOG_DEBUG, "classNameFilter: " + classNameFilter + " event filter: " + eventFilter, null, null, null); listenerInfo = listenerMap.get(classNameFilter); if (listenerInfo == null) { listenerInfo = new ListenerInfo(); listenerMap.put(classNameFilter, listenerInfo); try { bundleContext.addServiceListener(listenerInfo, classNameFilter); } catch (InvalidSyntaxException e) { throw (IllegalArgumentException) new IllegalArgumentException( "invalid class name filter").initCause(e); } } } listenerInfo.add(eventFilter, listener); } public void removeServiceListener(String className, Filter filter, ExtendedServiceListener<ExtendedServiceEvent> listener) { if (filter != null && filter.toString().contains(PrivateRegistryWrapper.PRIVATE)) { synchronized (privateListeners) { ServiceListener l = privateListeners.remove(listener); bundleContext.removeServiceListener(l); } } synchronized (listenerMap) { ListenerInfo listenerInfo = listenerMap.get(className); if (listenerInfo != null) { if (listenerInfo.remove(filter, listener)) { listenerMap.remove(className); bundleContext.removeServiceListener(listenerInfo); } } } } public Collection<ComponentHolder<?>> getComponentHoldersByPid(TargetedPID targetedPid) { String pid = targetedPid.getServicePid(); Set<ComponentHolder<?>> componentHoldersUsingPid = new HashSet<>(); synchronized (holdersByPid) { Set<ComponentHolder<?>> set = holdersByPid.get(pid); // only return the entry if non-null and not a reservation if (set != null) { for (ComponentHolder<?> holder : set) { if (targetedPid.matchesTarget(holder.getActivator().getBundleContext().getBundle())) { componentHoldersUsingPid.add(holder); } } } } return componentHoldersUsingPid; } public Collection<ComponentHolder<?>> getComponentHoldersByName(String name) { if (name == null) { return holders; } ComponentHolder<?> componentHolder = holdersByName.get(name); if (componentHolder != null) { return Collections.<ComponentHolder<?>>singletonList(componentHolder); } return Collections.emptyList(); } @Override public boolean isLogEnabled(int level) { if (level >= LogService.LOG_DEBUG) { return log.isDebugEnabled(); } else if (level >= LogService.LOG_INFO) { return log.isInfoEnabled(); } else if (level >= LogService.LOG_WARNING) { return log.isWarnEnabled(); } else { return log.isErrorEnabled(); } } @Override public void log(int level, String pattern, Object[] arguments, ComponentMetadata metadata, Long componentId, Throwable ex) { if (isLogEnabled(level)) { final String message = MessageFormat.format(pattern, arguments); log(level, message, metadata, componentId, ex); } } @Override public void log(int level, String message, ComponentMetadata metadata, Long componentId, Throwable ex) { if (isLogEnabled(level)) { if (metadata != null) { if (componentId != null) { message = "[" + metadata.getName() + "(" + componentId + ")] " + message; } else { message = "[" + metadata.getName() + "] " + message; } } if (level >= LogService.LOG_DEBUG) { log.debug(message, ex); } else if (level >= LogService.LOG_INFO) { log.info(message, ex); } else if (level >= LogService.LOG_WARNING) { log.warn(message, ex); } else { log.error(message, ex); } } } @Override public void log(int level, String message, Throwable ex) { log(level, message, null, ex); } @Override public void log(int level, String message, Object[] arguments, Throwable ex) { log(level, message, arguments, null, 0L, ex); } private static class ListenerInfo implements ServiceListener { private Map<Filter, List<ExtendedServiceListener<ExtendedServiceEvent>>> filterMap = new HashMap<>(); public void serviceChanged(ServiceEvent event) { ServiceReference<?> ref = event.getServiceReference(); ExtendedServiceEvent extEvent = null; ExtendedServiceEvent endMatchEvent = null; Map<Filter, List<ExtendedServiceListener<ExtendedServiceEvent>>> filterMap; synchronized (this) { filterMap = this.filterMap; } for (Map.Entry<Filter, List<ExtendedServiceListener<ExtendedServiceEvent>>> entry : filterMap.entrySet()) { Filter filter = entry.getKey(); if (filter == null || filter.match(ref)) { if (extEvent == null) { extEvent = new ExtendedServiceEvent(event); } for (ExtendedServiceListener<ExtendedServiceEvent> forwardTo : entry.getValue()) { forwardTo.serviceChanged(extEvent); } } else if (event.getType() == ServiceEvent.MODIFIED) { if (endMatchEvent == null) { endMatchEvent = new ExtendedServiceEvent(ServiceEvent.MODIFIED_ENDMATCH, ref); } for (ExtendedServiceListener<ExtendedServiceEvent> forwardTo : entry.getValue()) { forwardTo.serviceChanged(endMatchEvent); } } } if (extEvent != null) { extEvent.activateManagers(); } if (endMatchEvent != null) { endMatchEvent.activateManagers(); } } public synchronized void add(Filter filter, ExtendedServiceListener<ExtendedServiceEvent> listener) { filterMap = new HashMap<>(filterMap); List<ExtendedServiceListener<ExtendedServiceEvent>> listeners = filterMap.get(filter); if (listeners == null) { listeners = Collections.singletonList(listener); } else { listeners = new ArrayList<>(listeners); listeners.add(listener); } filterMap.put(filter, listeners); } public synchronized boolean remove(Filter filter, ExtendedServiceListener<ExtendedServiceEvent> listener) { List<ExtendedServiceListener<ExtendedServiceEvent>> listeners = filterMap.get(filter); if (listeners != null) { filterMap = new HashMap<>(filterMap); listeners = new ArrayList<>(listeners); listeners.remove(listener); if (listeners.isEmpty()) { filterMap.remove(filter); } else { filterMap.put(filter, listeners); } } return filterMap.isEmpty(); } } private static class Entry { private final DependencyManager<?, ?> dm; private final int trackingCount; private Entry(DependencyManager<?, ?> dm, int trackingCount) { this.dm = dm; this.trackingCount = trackingCount; } @SuppressWarnings("unchecked") public <S, T> DependencyManager<S, T> getDm() { return (DependencyManager<S, T>) dm; } public int getTrackingCount() { return trackingCount; } } private static class CdiComponentHolder<S> extends ConfigurableComponentHolder<S> { public CdiComponentHolder(ComponentActivator activator, ComponentMetadata metadata) { super(activator, metadata); } @Override protected ComponentMethods createComponentMethods() { return new EmptyMethods(); } @Override protected AbstractComponentManager<S> createComponentManager(boolean factoryConfiguration) { ComponentMetadata metadata = getComponentMetadata(); ComponentMethods componentMethods = getComponentMethods(); switch (metadata.getServiceScope()) { case singleton: return new CdiSingletonComponentManager<>(this, componentMethods); case bundle: return new CdiBundleComponentManager<>(this, componentMethods); case prototype: return createPrototypeComponentManager(componentMethods); default: throw new IllegalStateException(); } } protected AbstractComponentManager<S> createPrototypeComponentManager(ComponentMethods componentMethods) { throw new IllegalStateException("prototype scope not supported"); } } private static class CdiComponentHolder6<S> extends CdiComponentHolder<S> { public CdiComponentHolder6(ComponentActivator activator, ComponentMetadata metadata) { super(activator, metadata); } @Override protected AbstractComponentManager<S> createPrototypeComponentManager(ComponentMethods componentMethods) { return new CdiPrototypeComponentManager<>(this, componentMethods); } } private static class EmptyMethods implements ComponentMethods, ReferenceMethods, ReferenceMethod { @Override public void initComponentMethods(ComponentMetadata componentMetadata, Class<?> implementationObjectClass) { } @Override public ComponentMethod getActivateMethod() { return null; } @Override public ComponentMethod getDeactivateMethod() { return null; } @Override public ComponentMethod getModifiedMethod() { return null; } @Override public ReferenceMethods getBindMethods(String refName) { return this; } @Override public ReferenceMethod getBind() { return this; } @Override public ReferenceMethod getUnbind() { return null; } @Override public ReferenceMethod getUpdated() { return null; } @Override public InitReferenceMethod getInit() { return null; } @Override public MethodResult invoke(Object componentInstance, ComponentContextImpl<?> componentContext, RefPair<?, ?> refPair, MethodResult methodCallFailureResult, SimpleLogger logger) { return null; } @Override public <S, T> boolean getServiceObject(ComponentContextImpl<S> key, RefPair<S, T> refPair, BundleContext context, SimpleLogger logger) { return true; } } private static class CdiPrototypeComponentManager<S> extends PrototypeServiceFactoryComponentManager<S> { public CdiPrototypeComponentManager(ComponentContainer<S> container, ComponentMethods componentMethods) { super(container, componentMethods); } protected S createImplementationObject(Bundle usingBundle, final SetImplementationObject<S> setter, ComponentContextImpl<S> componentContext) { return doCreate(this, componentContext, new Consumer<ComponentContextImpl<S>>() { @Override public void accept(ComponentContextImpl<S> cc) { setter.presetComponentContext(cc); } }); } protected void disposeImplementationObject(ComponentContextImpl<S> componentContext, int reason) { doDestroy(this, componentContext); } } private static class CdiBundleComponentManager<S> extends ServiceFactoryComponentManager<S> { public CdiBundleComponentManager(ComponentContainer<S> container, ComponentMethods componentMethods) { super(container, componentMethods); } protected S createImplementationObject(Bundle usingBundle, final SetImplementationObject<S> setter, ComponentContextImpl<S> componentContext) { return doCreate(this, componentContext, new Consumer<ComponentContextImpl<S>>() { @Override public void accept(ComponentContextImpl<S> cc) { setter.presetComponentContext(cc); } }); } protected void disposeImplementationObject(ComponentContextImpl<S> componentContext, int reason) { doDestroy(this, componentContext); } } private static class CdiSingletonComponentManager<S> extends SingleComponentManager<S> { public CdiSingletonComponentManager(ComponentContainer<S> container, ComponentMethods componentMethods) { super(container, componentMethods); } protected S createImplementationObject(Bundle usingBundle, final SetImplementationObject<S> setter, ComponentContextImpl<S> componentContext) { return doCreate(this, componentContext, new Consumer<ComponentContextImpl<S>>() { @Override public void accept(ComponentContextImpl<S> cc) { setter.presetComponentContext(cc); } }); } protected void disposeImplementationObject(ComponentContextImpl<S> componentContext, int reason) { doDestroy(this, componentContext); } } private static <S> S doCreate(AbstractComponentManager<S> manager, ComponentContextImpl<S> componentContext, Consumer<ComponentContextImpl<S>> setter) { AbstractDescriptor descriptor = (AbstractDescriptor) manager.getComponentMetadata(); S s = (S) descriptor.activate(componentContext); componentContext.setImplementationObject( s ); setter.accept(componentContext); componentContext.setImplementationAccessible( true ); return s; } private static <S> void doDestroy(AbstractComponentManager<S> manager, ComponentContextImpl<S> componentContext) { AbstractDescriptor descriptor = (AbstractDescriptor) manager.getComponentMetadata(); descriptor.deactivate(componentContext); } static class ScrConfigurationImpl implements ScrConfiguration { @Override public int getLogLevel() { return 0; } @Override public boolean isFactoryEnabled() { return false; } @Override public boolean keepInstances() { return false; } @Override public boolean infoAsService() { return false; } @Override public long lockTimeout() { return DEFAULT_LOCK_TIMEOUT_MILLISECONDS; } @Override public long stopTimeout() { return DEFAULT_STOP_TIMEOUT_MILLISECONDS; } } }
pax-cdi-extension/src/main/java/org/ops4j/pax/cdi/extension/impl/component2/ComponentRegistry.java
/* * Copyright 2016 Guillaume Nodet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.ops4j.pax.cdi.extension.impl.component2; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.felix.scr.impl.helper.ComponentMethod; import org.apache.felix.scr.impl.helper.ComponentMethods; import org.apache.felix.scr.impl.helper.ConfigAdminTracker; import org.apache.felix.scr.impl.helper.InitReferenceMethod; import org.apache.felix.scr.impl.helper.MethodResult; import org.apache.felix.scr.impl.helper.ReferenceMethod; import org.apache.felix.scr.impl.helper.ReferenceMethods; import org.apache.felix.scr.impl.helper.SimpleLogger; import org.apache.felix.scr.impl.manager.AbstractComponentManager; import org.apache.felix.scr.impl.manager.ComponentActivator; import org.apache.felix.scr.impl.manager.ComponentContainer; import org.apache.felix.scr.impl.manager.ComponentContextImpl; import org.apache.felix.scr.impl.manager.ComponentHolder; import org.apache.felix.scr.impl.manager.ConfigurableComponentHolder; import org.apache.felix.scr.impl.manager.DependencyManager; import org.apache.felix.scr.impl.manager.ExtendedServiceEvent; import org.apache.felix.scr.impl.manager.ExtendedServiceListener; import org.apache.felix.scr.impl.manager.PrototypeServiceFactoryComponentManager; import org.apache.felix.scr.impl.manager.RefPair; import org.apache.felix.scr.impl.manager.RegionConfigurationSupport; import org.apache.felix.scr.impl.manager.ScrConfiguration; import org.apache.felix.scr.impl.manager.ServiceFactoryComponentManager; import org.apache.felix.scr.impl.manager.SingleComponentManager; import org.apache.felix.scr.impl.metadata.ComponentMetadata; import org.apache.felix.scr.impl.metadata.TargetedPID; import org.ops4j.pax.cdi.extension.impl.compat.OsgiScopeUtils; import org.ops4j.pax.cdi.extension.impl.support.Consumer; import org.ops4j.pax.cdi.extension.impl.support.PrivateRegistryWrapper; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.ComponentConstants; import org.osgi.service.component.ComponentException; import org.osgi.service.log.LogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ComponentRegistry implements ComponentActivator, SimpleLogger { private static final Logger log = LoggerFactory.getLogger(ComponentRegistry.class); private final BeanManager beanManager; private final BundleContext bundleContext; private final Map<Bean<?>, AbstractDescriptor> descriptors = new HashMap<>(); private final List<ComponentHolder<?>> holders = new ArrayList<>(); private final Map<String, ComponentHolder<?>> holdersByName = new HashMap<>(); private final Map<String, Set<ComponentHolder<?>>> holdersByPid = new HashMap<>(); ConfigAdminTracker configAdminTracker; private final ScrConfiguration m_configuration = new ScrConfigurationImpl(); private final Map<String, ListenerInfo> listenerMap = new HashMap<>(); private final Map<ExtendedServiceListener, ServiceListener> privateListeners = new HashMap<>(); private final AtomicInteger componentId = new AtomicInteger(); private final Map<ServiceReference<?>, List<Entry>> m_missingDependencies = new HashMap<>(); private final ConcurrentMap<Long, RegionConfigurationSupport> bundleToRcsMap = new ConcurrentHashMap<>(); private final Executor m_componentActor = Executors.newSingleThreadExecutor(); private final AtomicBoolean started = new AtomicBoolean(); public ComponentRegistry(BeanManager beanManager, BundleContext bundleContext) { this.beanManager = beanManager; this.bundleContext = new PrivateRegistryWrapper(bundleContext); } public BeanManager getBeanManager() { return beanManager; } public void preStart(AfterBeanDiscovery event, GlobalDescriptor global) { for (AbstractDescriptor descriptor : descriptors.values()) { for (Bean<?> bean : descriptor.getProducers()) { event.addBean(bean); } } global.validate(this); global.pauseIfNeeded(); ComponentHolder<?> h; if (OsgiScopeUtils.hasPrototypeScope(bundleContext)) { h = new CdiComponentHolder6<>(this, global); } else { h = new CdiComponentHolder<>(this, global); } h.enableComponents(false); for (Bean<?> bean : global.getProducers()) { event.addBean(bean); } } private final ThreadLocal<List<ServiceReference<?>>> circularInfos = new ThreadLocal<> (); public <T> boolean enterCreate(final ServiceReference<T> serviceReference) { List<ServiceReference<?>> info = circularInfos.get(); if (info == null) { circularInfos.set(info = new ArrayList<>()); } if (info.contains(serviceReference)) { log(LogService.LOG_ERROR, "Circular reference detected trying to get service {0}: stack of references: {1}", new Object[] {serviceReference, info}, null); return true; } log(LogService.LOG_DEBUG, "getService {0}: stack of references: {1}", new Object[] {serviceReference, info}, null); info.add(serviceReference); return false; } public <T> void leaveCreate(final ServiceReference<T> serviceReference) { List<ServiceReference<?>> info = circularInfos.get(); if (info != null) { if (!info.isEmpty() && info.iterator().next().equals(serviceReference)) { circularInfos.remove(); } else { info.remove(serviceReference); } } } public void start() { if (!started.compareAndSet(false, true)) { return; } for (AbstractDescriptor d : descriptors.values()) { d.validate(this); ComponentHolder<?> h = new CdiComponentHolder<>(this, d); holders.add(h); } for (ComponentHolder<?> h : holders) { if (holdersByName.put(h.getComponentMetadata().getName(), h) != null) { throw new ComponentException("The component name '{0}" + h.getComponentMetadata().getName() + "' has already been registered."); } } for (ComponentHolder<?> h : holders) { for (String pid : h.getComponentMetadata().getConfigurationPid()) { Set<ComponentHolder<?>> set = holdersByPid.get(pid); if (set == null) { set = new HashSet<>(); holdersByPid.put(pid, set); } set.add(h); } } ConfigAdminTracker tracker = null; for (ComponentHolder<?> holder : holders) { if (!holder.getComponentMetadata().isConfigurationIgnored()) { tracker = new ConfigAdminTracker(this); break; } } configAdminTracker = tracker; for (ComponentHolder<?> h : holders) { try { h.enableComponents(false); } catch (RuntimeException e) { h.disableComponents(false); throw e; } } } public ComponentDescriptor addComponent(Bean<Object> component) { ComponentDescriptor descriptor = new ComponentDescriptor(component, this); descriptors.put(component, descriptor); return descriptor; } public BundleContext getBundleContext() { return bundleContext; } public Set<Bean<?>> getComponents() { return descriptors.keySet(); } public ComponentDescriptor getDescriptor(Bean<?> component) { return (ComponentDescriptor) descriptors.get(component); } @Override public boolean isActive() { return true; } @Override public ScrConfiguration getConfiguration() { return m_configuration; } @Override public void schedule(Runnable runnable) { if (isActive()) { m_componentActor.execute(runnable); } } @Override public long registerComponentId(AbstractComponentManager<?> sAbstractComponentManager) { return componentId.incrementAndGet(); } @Override public void unregisterComponentId(AbstractComponentManager<?> sAbstractComponentManager) { } @Override public <S, T> void registerMissingDependency(org.apache.felix.scr.impl.manager.DependencyManager<S, T> dependencyManager, ServiceReference<T> serviceReference, int trackingCount) { //check that the service reference is from scr if (serviceReference.getProperty(ComponentConstants.COMPONENT_NAME) == null || serviceReference.getProperty(ComponentConstants.COMPONENT_ID) == null) { return; } List<Entry> dependencyManagers = m_missingDependencies.get(serviceReference); if (dependencyManagers == null) { dependencyManagers = new ArrayList<>(); m_missingDependencies.put(serviceReference, dependencyManagers); } dependencyManagers.add(new Entry(dependencyManager, trackingCount)); } @Override public <T> void missingServicePresent(final ServiceReference<T> serviceReference) { final List<Entry> dependencyManagers = m_missingDependencies.remove(serviceReference); if (dependencyManagers != null) { m_componentActor.execute(new Runnable() { public void run() { for (Entry entry : dependencyManagers) { DependencyManager<?, T> dm = entry.getDm(); dm.invokeBindMethodLate(serviceReference, entry.getTrackingCount()); } } @Override public String toString() { return "Late binding task of reference " + serviceReference + " for dependencyManagers " + dependencyManagers; } }); } } @Override public void enableComponent(String name) { final Collection<ComponentHolder<?>> holders = getComponentHoldersByName(name); for (ComponentHolder<?> holder : holders) { try { log(LogService.LOG_DEBUG, "Enabling Component", holder.getComponentMetadata(), null, null); holder.enableComponents(true); } catch (Throwable t) { log(LogService.LOG_ERROR, "Cannot enable component", holder.getComponentMetadata(), null, t); } } } @Override public void disableComponent(String name) { throw new UnsupportedOperationException(); } @Override public RegionConfigurationSupport setRegionConfigurationSupport(ServiceReference<ConfigurationAdmin> reference) { RegionConfigurationSupport trialRcs = new RegionConfigurationSupport(this, reference) { protected Collection<ComponentHolder<?>> getComponentHolders(TargetedPID pid) { return getComponentHoldersByPid(pid); } }; RegionConfigurationSupport rcs = registerRegionConfigurationSupport(trialRcs); for (ComponentHolder<?> holder : holders) { rcs.configureComponentHolder(holder); } return rcs; } public RegionConfigurationSupport registerRegionConfigurationSupport(RegionConfigurationSupport trialRcs) { Long bundleId = trialRcs.getBundleId(); RegionConfigurationSupport existing; RegionConfigurationSupport previous = null; while (true) { existing = bundleToRcsMap.putIfAbsent(bundleId, trialRcs); if (existing == null) { trialRcs.start(); return trialRcs; } if (existing == previous) { //the rcs we referenced is still current return existing; } if (existing.reference()) { //existing can still be used previous = existing; } else { //existing was discarded in another thread, start over previous = null; } } } @Override public void unsetRegionConfigurationSupport(RegionConfigurationSupport rcs) { if (rcs.dereference()) { bundleToRcsMap.remove(rcs.getBundleId()); } } public void addServiceListener(String classNameFilter, Filter eventFilter, final ExtendedServiceListener<ExtendedServiceEvent> listener) { if (eventFilter != null && eventFilter.toString().contains(PrivateRegistryWrapper.PRIVATE)) { synchronized (privateListeners) { ServiceListener l = new ServiceListener() { @Override public void serviceChanged(ServiceEvent event) { listener.serviceChanged(new ExtendedServiceEvent(event)); } }; privateListeners.put(listener, l); try { bundleContext.addServiceListener(l, "(&" + classNameFilter + eventFilter.toString() + ")"); } catch (InvalidSyntaxException e) { throw (IllegalArgumentException) new IllegalArgumentException( "invalid class name filter").initCause(e); } } return; } ListenerInfo listenerInfo; synchronized (listenerMap) { log(LogService.LOG_DEBUG, "classNameFilter: " + classNameFilter + " event filter: " + eventFilter, null, null, null); listenerInfo = listenerMap.get(classNameFilter); if (listenerInfo == null) { listenerInfo = new ListenerInfo(); listenerMap.put(classNameFilter, listenerInfo); try { bundleContext.addServiceListener(listenerInfo, classNameFilter); } catch (InvalidSyntaxException e) { throw (IllegalArgumentException) new IllegalArgumentException( "invalid class name filter").initCause(e); } } } listenerInfo.add(eventFilter, listener); } public void removeServiceListener(String className, Filter filter, ExtendedServiceListener<ExtendedServiceEvent> listener) { if (filter != null && filter.toString().contains(PrivateRegistryWrapper.PRIVATE)) { synchronized (privateListeners) { ServiceListener l = privateListeners.remove(listener); bundleContext.removeServiceListener(l); } } synchronized (listenerMap) { ListenerInfo listenerInfo = listenerMap.get(className); if (listenerInfo != null) { if (listenerInfo.remove(filter, listener)) { listenerMap.remove(className); bundleContext.removeServiceListener(listenerInfo); } } } } public Collection<ComponentHolder<?>> getComponentHoldersByPid(TargetedPID targetedPid) { String pid = targetedPid.getServicePid(); Set<ComponentHolder<?>> componentHoldersUsingPid = new HashSet<>(); synchronized (holdersByPid) { Set<ComponentHolder<?>> set = holdersByPid.get(pid); // only return the entry if non-null and not a reservation if (set != null) { for (ComponentHolder<?> holder : set) { if (targetedPid.matchesTarget(holder.getActivator().getBundleContext().getBundle())) { componentHoldersUsingPid.add(holder); } } } } return componentHoldersUsingPid; } public Collection<ComponentHolder<?>> getComponentHoldersByName(String name) { if (name == null) { return holders; } ComponentHolder<?> componentHolder = holdersByName.get(name); if (componentHolder != null) { return Collections.<ComponentHolder<?>>singletonList(componentHolder); } return Collections.emptyList(); } @Override public boolean isLogEnabled(int level) { if (level >= LogService.LOG_DEBUG) { return log.isDebugEnabled(); } else if (level >= LogService.LOG_INFO) { return log.isInfoEnabled(); } else if (level >= LogService.LOG_WARNING) { return log.isWarnEnabled(); } else { return log.isErrorEnabled(); } } @Override public void log(int level, String pattern, Object[] arguments, ComponentMetadata metadata, Long componentId, Throwable ex) { if (isLogEnabled(level)) { final String message = MessageFormat.format(pattern, arguments); log(level, message, metadata, componentId, ex); } } @Override public void log(int level, String message, ComponentMetadata metadata, Long componentId, Throwable ex) { if (isLogEnabled(level)) { if (metadata != null) { if (componentId != null) { message = "[" + metadata.getName() + "(" + componentId + ")] " + message; } else { message = "[" + metadata.getName() + "] " + message; } } if (level >= LogService.LOG_DEBUG) { log.debug(message, ex); } else if (level >= LogService.LOG_INFO) { log.info(message, ex); } else if (level >= LogService.LOG_WARNING) { log.warn(message, ex); } else { log.error(message, ex); } } } @Override public void log(int level, String message, Throwable ex) { log(level, message, null, ex); } @Override public void log(int level, String message, Object[] arguments, Throwable ex) { log(level, message, arguments, null, 0L, ex); } private static class ListenerInfo implements ServiceListener { private Map<Filter, List<ExtendedServiceListener<ExtendedServiceEvent>>> filterMap = new HashMap<>(); public void serviceChanged(ServiceEvent event) { ServiceReference<?> ref = event.getServiceReference(); ExtendedServiceEvent extEvent = null; ExtendedServiceEvent endMatchEvent = null; Map<Filter, List<ExtendedServiceListener<ExtendedServiceEvent>>> filterMap; synchronized (this) { filterMap = this.filterMap; } for (Map.Entry<Filter, List<ExtendedServiceListener<ExtendedServiceEvent>>> entry : filterMap.entrySet()) { Filter filter = entry.getKey(); if (filter == null || filter.match(ref)) { if (extEvent == null) { extEvent = new ExtendedServiceEvent(event); } for (ExtendedServiceListener<ExtendedServiceEvent> forwardTo : entry.getValue()) { forwardTo.serviceChanged(extEvent); } } else if (event.getType() == ServiceEvent.MODIFIED) { if (endMatchEvent == null) { endMatchEvent = new ExtendedServiceEvent(ServiceEvent.MODIFIED_ENDMATCH, ref); } for (ExtendedServiceListener<ExtendedServiceEvent> forwardTo : entry.getValue()) { forwardTo.serviceChanged(endMatchEvent); } } } if (extEvent != null) { extEvent.activateManagers(); } if (endMatchEvent != null) { endMatchEvent.activateManagers(); } } public synchronized void add(Filter filter, ExtendedServiceListener<ExtendedServiceEvent> listener) { filterMap = new HashMap<>(filterMap); List<ExtendedServiceListener<ExtendedServiceEvent>> listeners = filterMap.get(filter); if (listeners == null) { listeners = Collections.singletonList(listener); } else { listeners = new ArrayList<>(listeners); listeners.add(listener); } filterMap.put(filter, listeners); } public synchronized boolean remove(Filter filter, ExtendedServiceListener<ExtendedServiceEvent> listener) { List<ExtendedServiceListener<ExtendedServiceEvent>> listeners = filterMap.get(filter); if (listeners != null) { filterMap = new HashMap<>(filterMap); listeners = new ArrayList<>(listeners); listeners.remove(listener); if (listeners.isEmpty()) { filterMap.remove(filter); } else { filterMap.put(filter, listeners); } } return filterMap.isEmpty(); } } private static class Entry { private final DependencyManager<?, ?> dm; private final int trackingCount; private Entry(DependencyManager<?, ?> dm, int trackingCount) { this.dm = dm; this.trackingCount = trackingCount; } @SuppressWarnings("unchecked") public <S, T> DependencyManager<S, T> getDm() { return (DependencyManager<S, T>) dm; } public int getTrackingCount() { return trackingCount; } } private static class CdiComponentHolder<S> extends ConfigurableComponentHolder<S> { public CdiComponentHolder(ComponentActivator activator, ComponentMetadata metadata) { super(activator, metadata); } @Override protected ComponentMethods createComponentMethods() { return new EmptyMethods(); } @Override protected AbstractComponentManager<S> createComponentManager(boolean factoryConfiguration) { ComponentMetadata metadata = getComponentMetadata(); ComponentMethods componentMethods = getComponentMethods(); switch (metadata.getServiceScope()) { case singleton: return new CdiSingletonComponentManager<>(this, componentMethods); case bundle: return new CdiBundleComponentManager<>(this, componentMethods); case prototype: return createPrototypeComponentManager(componentMethods); default: throw new IllegalStateException(); } } protected AbstractComponentManager<S> createPrototypeComponentManager(ComponentMethods componentMethods) { throw new IllegalStateException("prototype scope not supported"); } } private static class CdiComponentHolder6<S> extends CdiComponentHolder<S> { public CdiComponentHolder6(ComponentActivator activator, ComponentMetadata metadata) { super(activator, metadata); } @Override protected AbstractComponentManager<S> createPrototypeComponentManager(ComponentMethods componentMethods) { return new CdiPrototypeComponentManager<>(this, componentMethods); } } private static class EmptyMethods implements ComponentMethods, ReferenceMethods, ReferenceMethod { @Override public void initComponentMethods(ComponentMetadata componentMetadata, Class<?> implementationObjectClass) { } @Override public ComponentMethod getActivateMethod() { return null; } @Override public ComponentMethod getDeactivateMethod() { return null; } @Override public ComponentMethod getModifiedMethod() { return null; } @Override public ReferenceMethods getBindMethods(String refName) { return this; } @Override public ReferenceMethod getBind() { return this; } @Override public ReferenceMethod getUnbind() { return null; } @Override public ReferenceMethod getUpdated() { return null; } @Override public InitReferenceMethod getInit() { return null; } @Override public MethodResult invoke(Object componentInstance, ComponentContextImpl<?> componentContext, RefPair<?, ?> refPair, MethodResult methodCallFailureResult, SimpleLogger logger) { return null; } @Override public <S, T> boolean getServiceObject(ComponentContextImpl<S> key, RefPair<S, T> refPair, BundleContext context, SimpleLogger logger) { return true; } } private static class CdiPrototypeComponentManager<S> extends PrototypeServiceFactoryComponentManager<S> { public CdiPrototypeComponentManager(ComponentContainer<S> container, ComponentMethods componentMethods) { super(container, componentMethods); } protected S createImplementationObject(Bundle usingBundle, final SetImplementationObject<S> setter, ComponentContextImpl<S> componentContext) { return doCreate(this, componentContext, new Consumer<ComponentContextImpl<S>>() { @Override public void accept(ComponentContextImpl<S> cc) { setter.presetComponentContext(cc); } }); } protected void disposeImplementationObject(ComponentContextImpl<S> componentContext, int reason) { doDestroy(this, componentContext); } } private static class CdiBundleComponentManager<S> extends ServiceFactoryComponentManager<S> { public CdiBundleComponentManager(ComponentContainer<S> container, ComponentMethods componentMethods) { super(container, componentMethods); } protected S createImplementationObject(Bundle usingBundle, final SetImplementationObject<S> setter, ComponentContextImpl<S> componentContext) { return doCreate(this, componentContext, new Consumer<ComponentContextImpl<S>>() { @Override public void accept(ComponentContextImpl<S> cc) { setter.presetComponentContext(cc); } }); } protected void disposeImplementationObject(ComponentContextImpl<S> componentContext, int reason) { doDestroy(this, componentContext); } } private static class CdiSingletonComponentManager<S> extends SingleComponentManager<S> { public CdiSingletonComponentManager(ComponentContainer<S> container, ComponentMethods componentMethods) { super(container, componentMethods); } protected S createImplementationObject(Bundle usingBundle, final SetImplementationObject<S> setter, ComponentContextImpl<S> componentContext) { return doCreate(this, componentContext, new Consumer<ComponentContextImpl<S>>() { @Override public void accept(ComponentContextImpl<S> cc) { setter.presetComponentContext(cc); } }); } protected void disposeImplementationObject(ComponentContextImpl<S> componentContext, int reason) { doDestroy(this, componentContext); } } private static <S> S doCreate(AbstractComponentManager<S> manager, ComponentContextImpl<S> componentContext, Consumer<ComponentContextImpl<S>> setter) { AbstractDescriptor descriptor = (AbstractDescriptor) manager.getComponentMetadata(); S s = (S) descriptor.activate(componentContext); componentContext.setImplementationObject( s ); setter.accept(componentContext); componentContext.setImplementationAccessible( true ); return s; } private static <S> void doDestroy(AbstractComponentManager<S> manager, ComponentContextImpl<S> componentContext) { AbstractDescriptor descriptor = (AbstractDescriptor) manager.getComponentMetadata(); descriptor.deactivate(componentContext); } static class ScrConfigurationImpl implements ScrConfiguration { @Override public int getLogLevel() { return 0; } @Override public boolean isFactoryEnabled() { return false; } @Override public boolean keepInstances() { return false; } @Override public boolean infoAsService() { return false; } @Override public long lockTimeout() { return DEFAULT_LOCK_TIMEOUT_MILLISECONDS; } @Override public long stopTimeout() { return DEFAULT_STOP_TIMEOUT_MILLISECONDS; } } }
Fix prototype scope on OSGi r5
pax-cdi-extension/src/main/java/org/ops4j/pax/cdi/extension/impl/component2/ComponentRegistry.java
Fix prototype scope on OSGi r5
Java
apache-2.0
944bd71795aac39b37e816e7490dac504417f341
0
naikmpn/woodland
public static void main(string args[]); { int=a; getch(); }
login.java
public static void main(string args[]); { int=a; getch(); } }
modification
login.java
modification
Java
apache-2.0
cb768c694c7211f1c8da5a89bff441edd168b542
0
vibe-project/vibe-java-server,vibe-project/vibe-java-server
/* * Copyright 2014 The Vibe Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.atmosphere.vibe; import java.io.IOException; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.vibe.ServerSocket.Reply; import org.atmosphere.vibe.platform.action.Action; import org.atmosphere.vibe.platform.action.VoidAction; import org.atmosphere.vibe.platform.bridge.atmosphere2.VibeAtmosphereServlet; import org.atmosphere.vibe.platform.http.ServerHttpExchange; import org.atmosphere.vibe.platform.ws.ServerWebSocket; import org.atmosphere.vibe.transport.http.HttpTransportServer; import org.atmosphere.vibe.transport.ws.WebSocketTransportServer; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.junit.Test; public class ProtocolTest { @Test public void protocol() throws Exception { final DefaultServer server = new DefaultServer(); server.socketAction(new Action<ServerSocket>() { @Override public void on(final ServerSocket socket) { socket.on("abort", new VoidAction() { @Override public void on() { socket.close(); } }) .on("echo", new Action<Object>() { @Override public void on(Object data) { socket.send("echo", data); } }) .on("/reply/inbound", new Action<Reply<Map<String, Object>>>() { @Override public void on(Reply<Map<String, Object>> reply) { Map<String, Object> data = reply.data(); switch ((String) data.get("type")) { case "resolved": reply.resolve(data.get("data")); break; case "rejected": reply.reject(data.get("data")); break; } } }) .on("/reply/outbound", new Action<Map<String, Object>>() { @Override public void on(Map<String, Object> data) { switch ((String) data.get("type")) { case "resolved": socket.send("test", data.get("data"), new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; case "rejected": socket.send("test", data.get("data"), null, new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; } } }); } }); final HttpTransportServer httpTransportServer = new HttpTransportServer().transportAction(server); final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().transportAction(server); org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(jetty); connector.setPort(8000); jetty.addConnector(connector); ServletContextHandler handler = new ServletContextHandler(); handler.addEventListener(new ServletContextListener() { @Override @SuppressWarnings("serial") public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); // /setup ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Map<String, String[]> params = req.getParameterMap(); if (params.containsKey("heartbeat")) { server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0])); } if (params.containsKey("_heartbeat")) { server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0])); } } }); regSetup.addMapping("/setup"); // /vibe ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(), new VibeAtmosphereServlet() { @Override protected Action<ServerHttpExchange> httpAction() { return httpTransportServer; } @Override protected Action<ServerWebSocket> wsAction() { return wsTransportServer; } }); reg.setAsyncSupported(true); reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString()); reg.addMapping("/vibe"); } @Override public void contextDestroyed(ServletContextEvent sce) {} }); jetty.setHandler(handler); jetty.start(); CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node") .addArgument("./src/test/resources/runner") .addArgument("--vibe.transports") .addArgument("ws,stream,longpoll"); DefaultExecutor executor = new DefaultExecutor(); // The exit value of mocha is the number of failed tests. executor.execute(cmdLine); jetty.stop(); } }
server/src/test/java/org/atmosphere/vibe/ProtocolTest.java
/* * Copyright 2014 The Vibe Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.atmosphere.vibe; import java.io.IOException; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.vibe.ServerSocket.Reply; import org.atmosphere.vibe.platform.action.Action; import org.atmosphere.vibe.platform.action.VoidAction; import org.atmosphere.vibe.platform.bridge.atmosphere2.VibeAtmosphereServlet; import org.atmosphere.vibe.platform.http.ServerHttpExchange; import org.atmosphere.vibe.platform.ws.ServerWebSocket; import org.atmosphere.vibe.transport.http.HttpTransportServer; import org.atmosphere.vibe.transport.ws.WebSocketTransportServer; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.junit.Test; public class ProtocolTest { @Test public void protocol() throws Exception { final DefaultServer server = new DefaultServer(); server.socketAction(new Action<ServerSocket>() { @Override public void on(final ServerSocket socket) { socket.on("abort", new VoidAction() { @Override public void on() { socket.close(); } }) .on("echo", new Action<Object>() { @Override public void on(Object data) { socket.send("echo", data); } }) .on("/reply/inbound", new Action<Reply<Map<String, Object>>>() { @Override public void on(Reply<Map<String, Object>> reply) { Map<String, Object> data = reply.data(); switch ((String) data.get("type")) { case "resolved": reply.resolve(data.get("data")); break; case "rejected": reply.reject(data.get("data")); break; } } }) .on("/reply/outbound", new Action<Map<String, Object>>() { @Override public void on(Map<String, Object> data) { switch ((String) data.get("type")) { case "resolved": socket.send("test", data.get("data"), new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; case "rejected": socket.send("test", data.get("data"), null, new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; } } }); } }); final HttpTransportServer httpTransportServer = new HttpTransportServer().transportAction(server); final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().transportAction(server); org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(jetty); connector.setPort(8000); jetty.addConnector(connector); ServletContextHandler handler = new ServletContextHandler(); handler.addEventListener(new ServletContextListener() { @Override @SuppressWarnings("serial") public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); // /setup ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Map<String, String[]> params = req.getParameterMap(); if (params.containsKey("heartbeat")) { server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0])); } if (params.containsKey("_heartbeat")) { server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0])); } } }); regSetup.addMapping("/setup"); // /vibe ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(), new VibeAtmosphereServlet() { @Override protected Action<ServerHttpExchange> httpAction() { return httpTransportServer; } @Override protected Action<ServerWebSocket> wsAction() { return wsTransportServer; } }); reg.setAsyncSupported(true); reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString()); reg.addMapping("/vibe"); } @Override public void contextDestroyed(ServletContextEvent sce) {} }); jetty.setHandler(handler); jetty.start(); CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node") .addArgument("./src/test/resources/runner") .addArgument("--vibe.transports") .addArgument("ws,stream,longpoll") .addArgument("--vibe.extension") .addArgument("reply"); DefaultExecutor executor = new DefaultExecutor(); // The exit value of mocha is the number of failed tests. executor.execute(cmdLine); jetty.stop(); } }
Fixes #72 remove vibe.extension arg
server/src/test/java/org/atmosphere/vibe/ProtocolTest.java
Fixes #72 remove vibe.extension arg
Java
apache-2.0
0bc09e87c4ce05009c0ea018986558647f0f4d1d
0
snowflakedb/snowflake-jdbc,snowflakedb/snowflake-jdbc,snowflakedb/snowflake-jdbc
/* * Copyright (c) 2012-2018 Snowflake Computing Inc. All rights reserved. */ package net.snowflake.client.core; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import net.snowflake.client.core.BasicEvent.QueryState; import net.snowflake.client.jdbc.ErrorCode; import net.snowflake.client.jdbc.SnowflakeSQLException; import net.snowflake.client.jdbc.SnowflakeUtil; import net.snowflake.client.log.SFLogger; import net.snowflake.client.log.SFLoggerFactory; import net.snowflake.common.api.QueryInProgressResponse; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPOutputStream; /** * Created by jhuang on 1/28/16. */ public class StmtUtil { static final EventHandler eventHandler = EventUtil.getEventHandlerInstance(); static final ObjectMapper mapper = new ObjectMapper(); static final String SF_PATH_QUERY_V1 = "/queries/v1/query-request"; private static final String SF_PATH_ABORT_REQUEST_V1 = "/queries/v1/abort-request"; private static final String SF_PATH_QUERY_RESULT = "/queries/%s/result"; static final String SF_QUERY_REQUEST_ID = "requestId"; private static final String SF_QUERY_COMBINE_DESCRIBE_EXECUTE = "combinedDescribe"; private static final String SF_HEADER_AUTHORIZATION = HttpHeaders.AUTHORIZATION; private static final String SF_HEADER_SNOWFLAKE_AUTHTYPE = "Snowflake"; private static final String SF_HEADER_TOKEN_TAG = "Token"; private static final String SF_MEDIA_TYPE = "application/snowflake"; // we don't want to retry canceling forever so put a limit which is // twice as much as our default socket timeout static final int SF_CANCELING_RETRY_TIMEOUT_IN_MILLIS = 600000; // 10 min static final SFLogger logger = SFLoggerFactory.getLogger(StmtUtil.class); /** * Input for executing a statement on server */ static class StmtInput { String sql; // default to snowflake (a special json format for snowflake query result String mediaType = SF_MEDIA_TYPE; Map<String, ParameterBindingDTO> bindValues; String bindStage; boolean describeOnly; String serverUrl; String requestId; int sequenceId = -1; boolean internal = false; Map<String, Object> parametersMap; String sessionToken; int networkTimeoutInMillis; int injectSocketTimeout; // seconds int injectClientPause; // seconds AtomicBoolean canceling = null; // canceling flag boolean retry; String prevGetResultURL = null; // previous get result URL from ping pong boolean combineDescribe = false; String describedJobId; long querySubmissionTime; // millis since epoch public StmtInput() {}; public StmtInput setSql(String sql) { this.sql = sql; return this; } public StmtInput setMediaType(String mediaType) { this.mediaType = mediaType; return this; } public StmtInput setParametersMap(Map<String, Object> parametersMap) { this.parametersMap = parametersMap; return this; } public StmtInput setBindValues(Map<String, ParameterBindingDTO> bindValues) { this.bindValues = bindValues; return this; } public StmtInput setBindStage(String bindStage) { this.bindStage = bindStage; return this; } public StmtInput setDescribeOnly(boolean describeOnly) { this.describeOnly = describeOnly; return this; } public StmtInput setInternal(boolean internal) { this.internal = internal; return this; } public StmtInput setServerUrl(String serverUrl) { this.serverUrl = serverUrl; return this; } public StmtInput setRequestId(String requestId) { this.requestId = requestId; return this; } public StmtInput setSequenceId(int sequenceId) { this.sequenceId = sequenceId; return this; } public StmtInput parametersMap(Map<String, Object> parametersMap) { this.parametersMap = parametersMap; return this; } public StmtInput setSessionToken(String sessionToken) { this.sessionToken = sessionToken; return this; } public StmtInput setNetworkTimeoutInMillis(int networkTimeoutInMillis) { this.networkTimeoutInMillis = networkTimeoutInMillis; return this; } public StmtInput setInjectSocketTimeout(int injectSocketTimeout) { this.injectSocketTimeout = injectSocketTimeout; return this; } public StmtInput setInjectClientPause(int injectClientPause) { this.injectClientPause = injectClientPause; return this; } public StmtInput setCanceling(AtomicBoolean canceling) { this.canceling = canceling; return this; } public StmtInput setRetry(boolean retry) { this.retry = retry; return this; } public StmtInput setCombineDescribe(boolean combineDescribe) { this.combineDescribe = combineDescribe; return this; } public StmtInput setDescribedJobId(String describedJobId) { this.describedJobId = describedJobId; return this; } public StmtInput setQuerySubmissionTime(long querySubmissionTime) { this.querySubmissionTime = querySubmissionTime; return this; } } /** * Output for running a statement on server */ static public class StmtOutput { JsonNode result; public StmtOutput(JsonNode result) { this.result = result; } public JsonNode getResult() { return result; } } /** * Execute a statement * * side effect: stmtInput.prevGetResultURL is set if we have started ping * pong and receives an exception from session token expiration so that * during retry we don't retry the query submission, but continue the * ping pong process. * * @param stmtInput input statement * @return StmtOutput output statement * * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ public static StmtOutput execute(StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpPost httpRequest = null; AssertUtil.assertTrue(stmtInput.serverUrl != null, "Missing server url for statement execution"); AssertUtil.assertTrue(stmtInput.sql != null, "Missing sql for statement execution"); AssertUtil.assertTrue(stmtInput.requestId != null, "Missing request id for statement execution"); AssertUtil.assertTrue(stmtInput.sequenceId >=0, "Negative sequence id for statement execution"); AssertUtil.assertTrue(stmtInput.mediaType != null, "Missing media type for statement execution"); try { String resultAsString = null; // SNOW-20443: if we are retrying and there is get result URL, we // don't need to execute the query again if (stmtInput.retry && stmtInput.prevGetResultURL != null) { logger.debug( "retrying statement execution with get result URL: {}", stmtInput.prevGetResultURL); } else { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); uriBuilder.setPath(SF_PATH_QUERY_V1); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, stmtInput.requestId); if (stmtInput.combineDescribe) { uriBuilder.addParameter(SF_QUERY_COMBINE_DESCRIBE_EXECUTE, "true"); } httpRequest = new HttpPost(uriBuilder.build()); /** * sequence id is only needed for old query API, when old query API * is deprecated, we can remove sequence id. */ QueryExecDTO sqlJsonBody = new QueryExecDTO( stmtInput.sql, stmtInput.describeOnly, stmtInput.sequenceId, stmtInput.bindValues, stmtInput.bindStage, stmtInput.parametersMap, stmtInput.querySubmissionTime, stmtInput.describeOnly || stmtInput.internal); if (stmtInput.combineDescribe && !stmtInput.describeOnly) { sqlJsonBody.setDescribedJobId(stmtInput.describedJobId); } String json = mapper.writeValueAsString(sqlJsonBody); if (logger.isDebugEnabled()) { logger.debug("JSON: {}", json); } // SNOW-18057: compress the post body in gzip ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); byte[] bytes = json.getBytes("UTF-8"); gzos.write(bytes); gzos.finish(); ByteArrayEntity input = new ByteArrayEntity(baos.toByteArray()); input.setContentType("application/json"); httpRequest.setEntity(input); httpRequest.addHeader("content-encoding", "gzip"); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); eventHandler.triggerStateTransition(BasicEvent.QueryState.SENDING_QUERY, String.format(QueryState.SENDING_QUERY.getArgString(), stmtInput.requestId)); resultAsString = HttpUtil.executeRequest(httpRequest, stmtInput.networkTimeoutInMillis / 1000, stmtInput.injectSocketTimeout, stmtInput.canceling, true // include retry parameters ); } return pollForOutput(resultAsString, stmtInput, httpRequest); } catch (Exception ex) { if (!(ex instanceof SnowflakeSQLException)) { if (ex instanceof IOException) { logger.error("IOException encountered", ex); // network error throw new SFException(ex, ErrorCode.NETWORK_ERROR, "Exception encountered when executing statement: " + ex.getLocalizedMessage()); } else { logger.error("Exception encountered", ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } } else { throw (SnowflakeSQLException) ex; } } finally { // we can release the http connection now if (httpRequest != null) { httpRequest.releaseConnection(); } } } private static StmtOutput pollForOutput(String resultAsString, StmtInput stmtInput, HttpPost httpRequest) throws SFException, SnowflakeSQLException { /** * Check response for error or for ping pong response * * For ping-pong: want to make sure our connection is not silently dropped * by middle players (e.g load balancer/VPN timeout) between client and GS */ JsonNode pingPongResponseJson; boolean queryInProgress; boolean firstResponse = !stmtInput.retry; String previousGetResultPath = (stmtInput.retry ? stmtInput.prevGetResultURL : null); int retries = 0; final int MAX_RETRIES = 3; do { pingPongResponseJson = null; if (resultAsString != null) { try { pingPongResponseJson = mapper.readTree(resultAsString); } catch (Exception ex) { logger.error("Bad result json: {}, " + "JSON parsing exception: {}, http request: {}", resultAsString, ex.getLocalizedMessage(), httpRequest); logger.error("Exception stack trace", ex); } } eventHandler.triggerStateTransition(BasicEvent.QueryState.WAITING_FOR_RESULT, "{requestId: " + stmtInput.requestId + "," + "pingNumber: " + retries + "}"); if (pingPongResponseJson == null) { /** * Retry for bad response for server. * But we don't want to retry too many times */ if (retries >= MAX_RETRIES) { throw IncidentUtil.generateIncidentWithException( stmtInput.sessionToken, stmtInput.serverUrl, stmtInput.requestId, null, ErrorCode.BAD_RESPONSE, resultAsString); } else { logger.info("Will retry get result. Retry count: {}", retries); retries++; } } else retries = 0; // reset retry counter after a successful response // trace the response if requested logger.debug("Json response: {}", resultAsString); if (pingPongResponseJson != null) // raise server side error as an exception if any { SnowflakeUtil.checkErrorAndThrowException(pingPongResponseJson); } // check the response code to see if it is a progress report response if (pingPongResponseJson != null && !QueryInProgressResponse.QUERY_IN_PROGRESS_CODE.equals( pingPongResponseJson.path("code").asText()) && !QueryInProgressResponse.QUERY_IN_PROGRESS_ASYNC_CODE.equals( pingPongResponseJson.path("code").asText())) { queryInProgress = false; } else { queryInProgress = true; if (firstResponse) { // sleep some time to simulate client pause. The purpose is to // simulate client pause before trying to fetch result so that // we can test query behavior related to disconnected client if (stmtInput.injectClientPause != 0) { logger.debug( "inject client pause for {} seconds", stmtInput.injectClientPause); try { Thread.sleep(stmtInput.injectClientPause * 1000); } catch (InterruptedException ex) { logger.warn("exception encountered while injecting pause"); } } } resultAsString = getQueryResult(pingPongResponseJson, previousGetResultPath, stmtInput); // save the previous get result path in case we run into session // expiration if (pingPongResponseJson != null) { previousGetResultPath = pingPongResponseJson.path("data"). path("getResultUrl").asText(); stmtInput.prevGetResultURL = previousGetResultPath; } } // not first response any more if (firstResponse) firstResponse = false; } while (queryInProgress); logger.debug("Returning result"); eventHandler.triggerStateTransition(BasicEvent.QueryState.PROCESSING_RESULT, String.format(QueryState.PROCESSING_RESULT.getArgString(), stmtInput.requestId)); return new StmtOutput(pingPongResponseJson); } /** * Issue get-result call to get query result given an in-progress response. * <p> * @param inProgressResponse In progress response in JSON form * @param previousGetResultPath previous get results path * @param stmtInput input statement * @return results in string form * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ static protected String getQueryResult(JsonNode inProgressResponse, String previousGetResultPath, StmtInput stmtInput) throws SFException, SnowflakeSQLException { String getResultPath = null; // get result url better not be empty if (inProgressResponse == null || inProgressResponse.path("data").path("getResultUrl").isMissingNode()) { if (previousGetResultPath == null) { throw new SFException(ErrorCode.INTERNAL_ERROR, "No query response or missing get result URL"); } else { logger.debug("No query response or missing get result URL, " + "use previous get result URL: {}", previousGetResultPath); getResultPath = previousGetResultPath; } } else { getResultPath = inProgressResponse.path("data").path("getResultUrl"). asText(); } return getQueryResult( getResultPath, stmtInput ); } /** * Issue get-result call to get query result given an in-progress response. * <p> * @param getResultPath path to results * @param stmtInput object with context information * @return results in string form * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ static protected String getQueryResult(String getResultPath, StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpGet httpRequest = null; logger.debug("get query result: {}", getResultPath); try { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); uriBuilder.setPath(getResultPath); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, UUID.randomUUID().toString()); httpRequest = new HttpGet(uriBuilder.build()); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); return HttpUtil.executeRequest(httpRequest, stmtInput.networkTimeoutInMillis/1000, 0, stmtInput.canceling); } catch (URISyntaxException | IOException ex) { logger.error("Exception encountered when getting result for " + httpRequest, ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } } /** * Issue get-result call to get query result given an in progress response. * <p> * @param queryId id of query to get results for * @param session the current session * @return results in JSON * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ static protected JsonNode getQueryResultJSON(String queryId, SFSession session) throws SFException, SnowflakeSQLException { String getResultPath = String.format(SF_PATH_QUERY_RESULT, queryId); StmtInput stmtInput = new StmtInput() .setServerUrl(session.getServerUrl()) .setSessionToken(session.getSessionToken()) .setNetworkTimeoutInMillis(session.getNetworkTimeoutInMilli()) .setMediaType(SF_MEDIA_TYPE); String resultAsString = getQueryResult(getResultPath, stmtInput); StmtOutput stmtOutput = pollForOutput(resultAsString, stmtInput, null); return stmtOutput.getResult(); } /** * Cancel a statement identifiable by a request id * * @param stmtInput input statement * @throws SFException if there is an internal exception * @throws SnowflakeSQLException if failed to cancel the statement */ public static void cancel(StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpPost httpRequest = null; AssertUtil.assertTrue(stmtInput.serverUrl != null, "Missing server url for statement execution"); AssertUtil.assertTrue(stmtInput.sql != null, "Missing sql for statement execution"); AssertUtil.assertTrue(stmtInput.mediaType != null, "Missing media type for statement execution"); AssertUtil.assertTrue(stmtInput.requestId != null, "Missing request id for statement execution"); AssertUtil.assertTrue(stmtInput.sessionToken != null, "Missing session token for statement execution"); try { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); logger.debug("Aborting query: {}", stmtInput.sql); uriBuilder.setPath(SF_PATH_ABORT_REQUEST_V1); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, UUID.randomUUID().toString()); httpRequest = new HttpPost(uriBuilder.build()); /** * The JSON input has two fields: sqlText and requestId */ Map sqlJsonBody = new HashMap<String, Object>(); sqlJsonBody.put("sqlText", stmtInput.sql); sqlJsonBody.put("requestId", stmtInput.requestId); String json = mapper.writeValueAsString(sqlJsonBody); logger.debug("JSON for cancel request: {}", json); StringEntity input = new StringEntity(json, Charset.forName("UTF-8")); input.setContentType("application/json"); httpRequest.setEntity(input); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); HttpResponse response; String jsonString = HttpUtil.executeRequest(httpRequest, SF_CANCELING_RETRY_TIMEOUT_IN_MILLIS, 0, null); // trace the response if requested logger.debug("Json response: {}", jsonString); JsonNode rootNode = null; rootNode = mapper.readTree(jsonString); // raise server side error as an exception if any SnowflakeUtil.checkErrorAndThrowException(rootNode); } catch (URISyntaxException | IOException ex) { logger.error( "Exception encountered when canceling " + httpRequest, ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } } /** * A simple function to check if the statement is related to manipulate stage. * * @param sql a SQL statement/command * @return PUT/GET/LIST/RM if statment belongs to one of them, otherwise * return NULL */ static public SFStatementType checkStageManageCommand(String sql) { if (sql == null) { return null; } String trimmedSql = sql.trim(); // skip commenting prefixed with // while (trimmedSql.startsWith("//")) { logger.debug("skipping // comments in: \n{}", trimmedSql); if (trimmedSql.indexOf('\n') > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf('\n')); trimmedSql = trimmedSql.trim(); } else { break; } logger.debug( "New sql after skipping // comments: \n{}", trimmedSql); } // skip commenting enclosed with /* */ while (trimmedSql.startsWith("/*")) { logger.debug( "skipping /* */ comments in: \n{}", trimmedSql); if (trimmedSql.indexOf("*/") > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf("*/") + 2); trimmedSql = trimmedSql.trim(); } else { break; } logger.debug( "New sql after skipping /* */ comments: \n{}", trimmedSql); } trimmedSql = trimmedSql.toLowerCase(); if (trimmedSql.startsWith("put ")) { return SFStatementType.PUT; } else if (trimmedSql.startsWith("get ")) { return SFStatementType.GET; } else if (trimmedSql.startsWith("ls ") || trimmedSql.startsWith("list ")) { return SFStatementType.LIST; } else if (trimmedSql.startsWith("rm ") || trimmedSql.startsWith("remove ")) { return SFStatementType.REMOVE; } else { return null; } } }
src/main/java/net/snowflake/client/core/StmtUtil.java
/* * Copyright (c) 2012-2018 Snowflake Computing Inc. All rights reserved. */ package net.snowflake.client.core; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import net.snowflake.client.core.BasicEvent.QueryState; import net.snowflake.client.jdbc.ErrorCode; import net.snowflake.client.jdbc.SnowflakeSQLException; import net.snowflake.client.jdbc.SnowflakeUtil; import net.snowflake.client.log.SFLogger; import net.snowflake.client.log.SFLoggerFactory; import net.snowflake.common.api.QueryInProgressResponse; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPOutputStream; /** * Created by jhuang on 1/28/16. */ public class StmtUtil { static final EventHandler eventHandler = EventUtil.getEventHandlerInstance(); static final ObjectMapper mapper = new ObjectMapper(); static final String SF_PATH_QUERY_V1 = "/queries/v1/query-request"; private static final String SF_PATH_ABORT_REQUEST_V1 = "/queries/v1/abort-request"; private static final String SF_PATH_QUERY_RESULT = "/queries/%s/result"; static final String SF_QUERY_REQUEST_ID = "requestId"; private static final String SF_QUERY_COMBINE_DESCRIBE_EXECUTE = "combinedDescribe"; private static final String SF_HEADER_AUTHORIZATION = HttpHeaders.AUTHORIZATION; private static final String SF_HEADER_SNOWFLAKE_AUTHTYPE = "Snowflake"; private static final String SF_HEADER_TOKEN_TAG = "Token"; private static final String SF_MEDIA_TYPE = "application/snowflake"; // we don't want to retry canceling forever so put a limit which is // twice as much as our default socket timeout static final int SF_CANCELING_RETRY_TIMEOUT_IN_MILLIS = 600000; // 10 min static final SFLogger logger = SFLoggerFactory.getLogger(StmtUtil.class); /** * Input for executing a statement on server */ static class StmtInput { String sql; // default to snowflake (a special json format for snowflake query result String mediaType = SF_MEDIA_TYPE; Map<String, ParameterBindingDTO> bindValues; String bindStage; boolean describeOnly; String serverUrl; String requestId; int sequenceId = -1; boolean internal = false; Map<String, Object> parametersMap; String sessionToken; int networkTimeoutInMillis; int injectSocketTimeout; // seconds int injectClientPause; // seconds AtomicBoolean canceling = null; // canceling flag boolean retry; String prevGetResultURL = null; // previous get result URL from ping pong boolean combineDescribe = false; String describedJobId; long querySubmissionTime; // millis since epoch public StmtInput() {}; public StmtInput setSql(String sql) { this.sql = sql; return this; } public StmtInput setMediaType(String mediaType) { this.mediaType = mediaType; return this; } public StmtInput setParametersMap(Map<String, Object> parametersMap) { this.parametersMap = parametersMap; return this; } public StmtInput setBindValues(Map<String, ParameterBindingDTO> bindValues) { this.bindValues = bindValues; return this; } public StmtInput setBindStage(String bindStage) { this.bindStage = bindStage; return this; } public StmtInput setDescribeOnly(boolean describeOnly) { this.describeOnly = describeOnly; return this; } public StmtInput setInternal(boolean internal) { this.internal = internal; return this; } public StmtInput setServerUrl(String serverUrl) { this.serverUrl = serverUrl; return this; } public StmtInput setRequestId(String requestId) { this.requestId = requestId; return this; } public StmtInput setSequenceId(int sequenceId) { this.sequenceId = sequenceId; return this; } public StmtInput parametersMap(Map<String, Object> parametersMap) { this.parametersMap = parametersMap; return this; } public StmtInput setSessionToken(String sessionToken) { this.sessionToken = sessionToken; return this; } public StmtInput setNetworkTimeoutInMillis(int networkTimeoutInMillis) { this.networkTimeoutInMillis = networkTimeoutInMillis; return this; } public StmtInput setInjectSocketTimeout(int injectSocketTimeout) { this.injectSocketTimeout = injectSocketTimeout; return this; } public StmtInput setInjectClientPause(int injectClientPause) { this.injectClientPause = injectClientPause; return this; } public StmtInput setCanceling(AtomicBoolean canceling) { this.canceling = canceling; return this; } public StmtInput setRetry(boolean retry) { this.retry = retry; return this; } public StmtInput setCombineDescribe(boolean combineDescribe) { this.combineDescribe = combineDescribe; return this; } public StmtInput setDescribedJobId(String describedJobId) { this.describedJobId = describedJobId; return this; } public StmtInput setQuerySubmissionTime(long querySubmissionTime) { this.querySubmissionTime = querySubmissionTime; return this; } } /** * Output for running a statement on server */ static public class StmtOutput { JsonNode result; public StmtOutput(JsonNode result) { this.result = result; } public JsonNode getResult() { return result; } } /** * Execute a statement * * side effect: stmtInput.prevGetResultURL is set if we have started ping * pong and receives an exception from session token expiration so that * during retry we don't retry the query submission, but continue the * ping pong process. * * @param stmtInput input statement * @return StmtOutput output statement * * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ public static StmtOutput execute(StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpPost httpRequest = null; AssertUtil.assertTrue(stmtInput.serverUrl != null, "Missing server url for statement execution"); AssertUtil.assertTrue(stmtInput.sql != null, "Missing sql for statement execution"); AssertUtil.assertTrue(stmtInput.requestId != null, "Missing request id for statement execution"); AssertUtil.assertTrue(stmtInput.sequenceId >=0, "Negative sequence id for statement execution"); AssertUtil.assertTrue(stmtInput.mediaType != null, "Missing media type for statement execution"); try { String resultAsString = null; // SNOW-20443: if we are retrying and there is get result URL, we // don't need to execute the query again if (stmtInput.retry && stmtInput.prevGetResultURL != null) { logger.debug( "retrying statement execution with get result URL: {}", stmtInput.prevGetResultURL); } else { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); uriBuilder.setPath(SF_PATH_QUERY_V1); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, stmtInput.requestId); if (stmtInput.combineDescribe) { uriBuilder.addParameter(SF_QUERY_COMBINE_DESCRIBE_EXECUTE, "true"); } httpRequest = new HttpPost(uriBuilder.build()); /** * sequence id is only needed for old query API, when old query API * is deprecated, we can remove sequence id. */ QueryExecDTO sqlJsonBody = new QueryExecDTO( stmtInput.sql, stmtInput.describeOnly, stmtInput.sequenceId, stmtInput.bindValues, stmtInput.bindStage, stmtInput.parametersMap, stmtInput.querySubmissionTime, stmtInput.describeOnly || stmtInput.internal); if (stmtInput.combineDescribe && !stmtInput.describeOnly) { sqlJsonBody.setDescribedJobId(stmtInput.describedJobId); } String json = mapper.writeValueAsString(sqlJsonBody); if (logger.isDebugEnabled()) { logger.debug("JSON: {}", json); } // SNOW-18057: compress the post body in gzip ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); byte[] bytes = json.getBytes("UTF-8"); gzos.write(bytes); gzos.finish(); ByteArrayEntity input = new ByteArrayEntity(baos.toByteArray()); input.setContentType("application/json"); httpRequest.setEntity(input); httpRequest.addHeader("content-encoding", "gzip"); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); eventHandler.triggerStateTransition(BasicEvent.QueryState.SENDING_QUERY, String.format(QueryState.SENDING_QUERY.getArgString(), stmtInput.requestId)); resultAsString = HttpUtil.executeRequest(httpRequest, stmtInput.networkTimeoutInMillis / 1000, stmtInput.injectSocketTimeout, stmtInput.canceling); } return pollForOutput(resultAsString, stmtInput, httpRequest); } catch (Exception ex) { if (!(ex instanceof SnowflakeSQLException)) { if (ex instanceof IOException) { logger.error("IOException encountered", ex); // network error throw new SFException(ex, ErrorCode.NETWORK_ERROR, "Exception encountered when executing statement: " + ex.getLocalizedMessage()); } else { logger.error("Exception encountered", ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } } else { throw (SnowflakeSQLException) ex; } } finally { // we can release the http connection now if (httpRequest != null) { httpRequest.releaseConnection(); } } } private static StmtOutput pollForOutput(String resultAsString, StmtInput stmtInput, HttpPost httpRequest) throws SFException, SnowflakeSQLException { /** * Check response for error or for ping pong response * * For ping-pong: want to make sure our connection is not silently dropped * by middle players (e.g load balancer/VPN timeout) between client and GS */ JsonNode pingPongResponseJson; boolean queryInProgress; boolean firstResponse = !stmtInput.retry; String previousGetResultPath = (stmtInput.retry ? stmtInput.prevGetResultURL : null); int retries = 0; final int MAX_RETRIES = 3; do { pingPongResponseJson = null; if (resultAsString != null) { try { pingPongResponseJson = mapper.readTree(resultAsString); } catch (Exception ex) { logger.error("Bad result json: {}, " + "JSON parsing exception: {}, http request: {}", resultAsString, ex.getLocalizedMessage(), httpRequest); logger.error("Exception stack trace", ex); } } eventHandler.triggerStateTransition(BasicEvent.QueryState.WAITING_FOR_RESULT, "{requestId: " + stmtInput.requestId + "," + "pingNumber: " + retries + "}"); if (pingPongResponseJson == null) { /** * Retry for bad response for server. * But we don't want to retry too many times */ if (retries >= MAX_RETRIES) { throw IncidentUtil.generateIncidentWithException( stmtInput.sessionToken, stmtInput.serverUrl, stmtInput.requestId, null, ErrorCode.BAD_RESPONSE, resultAsString); } else { logger.info("Will retry get result. Retry count: {}", retries); retries++; } } else retries = 0; // reset retry counter after a successful response // trace the response if requested logger.debug("Json response: {}", resultAsString); if (pingPongResponseJson != null) // raise server side error as an exception if any { SnowflakeUtil.checkErrorAndThrowException(pingPongResponseJson); } // check the response code to see if it is a progress report response if (pingPongResponseJson != null && !QueryInProgressResponse.QUERY_IN_PROGRESS_CODE.equals( pingPongResponseJson.path("code").asText()) && !QueryInProgressResponse.QUERY_IN_PROGRESS_ASYNC_CODE.equals( pingPongResponseJson.path("code").asText())) { queryInProgress = false; } else { queryInProgress = true; if (firstResponse) { // sleep some time to simulate client pause. The purpose is to // simulate client pause before trying to fetch result so that // we can test query behavior related to disconnected client if (stmtInput.injectClientPause != 0) { logger.debug( "inject client pause for {} seconds", stmtInput.injectClientPause); try { Thread.sleep(stmtInput.injectClientPause * 1000); } catch (InterruptedException ex) { logger.warn("exception encountered while injecting pause"); } } } resultAsString = getQueryResult(pingPongResponseJson, previousGetResultPath, stmtInput); // save the previous get result path in case we run into session // expiration if (pingPongResponseJson != null) { previousGetResultPath = pingPongResponseJson.path("data"). path("getResultUrl").asText(); stmtInput.prevGetResultURL = previousGetResultPath; } } // not first response any more if (firstResponse) firstResponse = false; } while (queryInProgress); logger.debug("Returning result"); eventHandler.triggerStateTransition(BasicEvent.QueryState.PROCESSING_RESULT, String.format(QueryState.PROCESSING_RESULT.getArgString(), stmtInput.requestId)); return new StmtOutput(pingPongResponseJson); } /** * Issue get-result call to get query result given an in-progress response. * <p> * @param inProgressResponse In progress response in JSON form * @param previousGetResultPath previous get results path * @param stmtInput input statement * @return results in string form * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ static protected String getQueryResult(JsonNode inProgressResponse, String previousGetResultPath, StmtInput stmtInput) throws SFException, SnowflakeSQLException { String getResultPath = null; // get result url better not be empty if (inProgressResponse == null || inProgressResponse.path("data").path("getResultUrl").isMissingNode()) { if (previousGetResultPath == null) { throw new SFException(ErrorCode.INTERNAL_ERROR, "No query response or missing get result URL"); } else { logger.debug("No query response or missing get result URL, " + "use previous get result URL: {}", previousGetResultPath); getResultPath = previousGetResultPath; } } else { getResultPath = inProgressResponse.path("data").path("getResultUrl"). asText(); } return getQueryResult( getResultPath, stmtInput ); } /** * Issue get-result call to get query result given an in-progress response. * <p> * @param getResultPath path to results * @param stmtInput object with context information * @return results in string form * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ static protected String getQueryResult(String getResultPath, StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpGet httpRequest = null; logger.debug("get query result: {}", getResultPath); try { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); uriBuilder.setPath(getResultPath); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, UUID.randomUUID().toString()); httpRequest = new HttpGet(uriBuilder.build()); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); return HttpUtil.executeRequest(httpRequest, stmtInput.networkTimeoutInMillis/1000, 0, stmtInput.canceling); } catch (URISyntaxException | IOException ex) { logger.error("Exception encountered when getting result for " + httpRequest, ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } } /** * Issue get-result call to get query result given an in progress response. * <p> * @param queryId id of query to get results for * @param session the current session * @return results in JSON * @throws SFException exception raised from Snowflake components * @throws SnowflakeSQLException exception raised from Snowflake components */ static protected JsonNode getQueryResultJSON(String queryId, SFSession session) throws SFException, SnowflakeSQLException { String getResultPath = String.format(SF_PATH_QUERY_RESULT, queryId); StmtInput stmtInput = new StmtInput() .setServerUrl(session.getServerUrl()) .setSessionToken(session.getSessionToken()) .setNetworkTimeoutInMillis(session.getNetworkTimeoutInMilli()) .setMediaType(SF_MEDIA_TYPE); String resultAsString = getQueryResult(getResultPath, stmtInput); StmtOutput stmtOutput = pollForOutput(resultAsString, stmtInput, null); return stmtOutput.getResult(); } /** * Cancel a statement identifiable by a request id * * @param stmtInput input statement * @throws SFException if there is an internal exception * @throws SnowflakeSQLException if failed to cancel the statement */ public static void cancel(StmtInput stmtInput) throws SFException, SnowflakeSQLException { HttpPost httpRequest = null; AssertUtil.assertTrue(stmtInput.serverUrl != null, "Missing server url for statement execution"); AssertUtil.assertTrue(stmtInput.sql != null, "Missing sql for statement execution"); AssertUtil.assertTrue(stmtInput.mediaType != null, "Missing media type for statement execution"); AssertUtil.assertTrue(stmtInput.requestId != null, "Missing request id for statement execution"); AssertUtil.assertTrue(stmtInput.sessionToken != null, "Missing session token for statement execution"); try { URIBuilder uriBuilder = new URIBuilder(stmtInput.serverUrl); logger.debug("Aborting query: {}", stmtInput.sql); uriBuilder.setPath(SF_PATH_ABORT_REQUEST_V1); uriBuilder.addParameter(SF_QUERY_REQUEST_ID, UUID.randomUUID().toString()); httpRequest = new HttpPost(uriBuilder.build()); /** * The JSON input has two fields: sqlText and requestId */ Map sqlJsonBody = new HashMap<String, Object>(); sqlJsonBody.put("sqlText", stmtInput.sql); sqlJsonBody.put("requestId", stmtInput.requestId); String json = mapper.writeValueAsString(sqlJsonBody); logger.debug("JSON for cancel request: {}", json); StringEntity input = new StringEntity(json, Charset.forName("UTF-8")); input.setContentType("application/json"); httpRequest.setEntity(input); httpRequest.addHeader("accept", stmtInput.mediaType); httpRequest.setHeader(SF_HEADER_AUTHORIZATION, SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput.sessionToken + "\""); HttpResponse response; String jsonString = HttpUtil.executeRequest(httpRequest, SF_CANCELING_RETRY_TIMEOUT_IN_MILLIS, 0, null); // trace the response if requested logger.debug("Json response: {}", jsonString); JsonNode rootNode = null; rootNode = mapper.readTree(jsonString); // raise server side error as an exception if any SnowflakeUtil.checkErrorAndThrowException(rootNode); } catch (URISyntaxException | IOException ex) { logger.error( "Exception encountered when canceling " + httpRequest, ex); // raise internal exception if this is not a snowflake exception throw new SFException(ex, ErrorCode.INTERNAL_ERROR, ex.getLocalizedMessage()); } } /** * A simple function to check if the statement is related to manipulate stage. * * @param sql a SQL statement/command * @return PUT/GET/LIST/RM if statment belongs to one of them, otherwise * return NULL */ static public SFStatementType checkStageManageCommand(String sql) { if (sql == null) { return null; } String trimmedSql = sql.trim(); // skip commenting prefixed with // while (trimmedSql.startsWith("//")) { logger.debug("skipping // comments in: \n{}", trimmedSql); if (trimmedSql.indexOf('\n') > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf('\n')); trimmedSql = trimmedSql.trim(); } else { break; } logger.debug( "New sql after skipping // comments: \n{}", trimmedSql); } // skip commenting enclosed with /* */ while (trimmedSql.startsWith("/*")) { logger.debug( "skipping /* */ comments in: \n{}", trimmedSql); if (trimmedSql.indexOf("*/") > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf("*/") + 2); trimmedSql = trimmedSql.trim(); } else { break; } logger.debug( "New sql after skipping /* */ comments: \n{}", trimmedSql); } trimmedSql = trimmedSql.toLowerCase(); if (trimmedSql.startsWith("put ")) { return SFStatementType.PUT; } else if (trimmedSql.startsWith("get ")) { return SFStatementType.GET; } else if (trimmedSql.startsWith("ls ") || trimmedSql.startsWith("list ")) { return SFStatementType.LIST; } else if (trimmedSql.startsWith("rm ") || trimmedSql.startsWith("remove ")) { return SFStatementType.REMOVE; } else { return null; } } }
SNOW-52486 Fix JDBC driver to use retry parameters for query-request calls
src/main/java/net/snowflake/client/core/StmtUtil.java
SNOW-52486 Fix JDBC driver to use retry parameters for query-request calls
Java
apache-2.0
9cb6e62a08a93ecab22c357d69d43c6c2fab6d09
0
da1z/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,kool79/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,caot/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,signed/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,slisson/intellij-community,supersven/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,asedunov/intellij-community,supersven/intellij-community,petteyg/intellij-community,adedayo/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,caot/intellij-community,jagguli/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,allotria/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ryano144/intellij-community,signed/intellij-community,vladmm/intellij-community,amith01994/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,vladmm/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,kdwink/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,signed/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vladmm/intellij-community,amith01994/intellij-community,da1z/intellij-community,wreckJ/intellij-community,signed/intellij-community,samthor/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,izonder/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vladmm/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,samthor/intellij-community,retomerz/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,kool79/intellij-community,clumsy/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,kool79/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,amith01994/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,amith01994/intellij-community,dslomov/intellij-community,xfournet/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,clumsy/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,ibinti/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,vladmm/intellij-community,supersven/intellij-community,semonte/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,caot/intellij-community,supersven/intellij-community,hurricup/intellij-community,kdwink/intellij-community,samthor/intellij-community,nicolargo/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,caot/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,holmes/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,ryano144/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,da1z/intellij-community,fnouama/intellij-community,izonder/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,apixandru/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,da1z/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,supersven/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,asedunov/intellij-community,fnouama/intellij-community,signed/intellij-community,holmes/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,da1z/intellij-community,izonder/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,clumsy/intellij-community,samthor/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,adedayo/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,izonder/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,jagguli/intellij-community,holmes/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,asedunov/intellij-community,caot/intellij-community,clumsy/intellij-community,ibinti/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,caot/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,supersven/intellij-community,diorcety/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,robovm/robovm-studio,robovm/robovm-studio,amith01994/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,allotria/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,holmes/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,FHannes/intellij-community,xfournet/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,semonte/intellij-community,signed/intellij-community,ahb0327/intellij-community,caot/intellij-community,kdwink/intellij-community,da1z/intellij-community,orekyuu/intellij-community,signed/intellij-community,TangHao1987/intellij-community,signed/intellij-community,slisson/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,robovm/robovm-studio,retomerz/intellij-community,adedayo/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,supersven/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,FHannes/intellij-community,allotria/intellij-community,izonder/intellij-community,allotria/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,asedunov/intellij-community,allotria/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,caot/intellij-community,fitermay/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,semonte/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,supersven/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,blademainer/intellij-community,apixandru/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,allotria/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,signed/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,da1z/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,gnuhub/intellij-community,signed/intellij-community,petteyg/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,supersven/intellij-community,diorcety/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,orekyuu/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,slisson/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,samthor/intellij-community,ahb0327/intellij-community,caot/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,semonte/intellij-community,holmes/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,holmes/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,samthor/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,clumsy/intellij-community,apixandru/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,supersven/intellij-community,blademainer/intellij-community,samthor/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,samthor/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,izonder/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,kdwink/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,holmes/intellij-community,dslomov/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,jagguli/intellij-community,kdwink/intellij-community,fitermay/intellij-community,diorcety/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,izonder/intellij-community,apixandru/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,retomerz/intellij-community,dslomov/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,orekyuu/intellij-community,holmes/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.ui.configuration.projectRoot; import com.intellij.facet.Facet; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.TreeExpander; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureDaemonAnalyzerListener; import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureElement; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.openapi.ui.MasterDetailsState; import com.intellij.openapi.ui.MasterDetailsStateService; import com.intellij.openapi.ui.NamedConfigurable; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.packaging.artifacts.Artifact; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.navigation.Place; import com.intellij.util.Function; import com.intellij.util.IconUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.*; import java.util.*; import java.util.List; public abstract class BaseStructureConfigurable extends MasterDetailsComponent implements SearchableConfigurable, Disposable, Place.Navigator { protected StructureConfigurableContext myContext; protected final Project myProject; protected boolean myUiDisposed = true; private boolean myWasTreeInitialized; protected boolean myAutoScrollEnabled = true; protected BaseStructureConfigurable(Project project, MasterDetailsState state) { super(state); myProject = project; } protected BaseStructureConfigurable(final Project project) { myProject = project; } public void init(StructureConfigurableContext context) { myContext = context; myContext.getDaemonAnalyzer().addListener(new ProjectStructureDaemonAnalyzerListener() { @Override public void problemsChanged(@NotNull ProjectStructureElement element) { if (!myTree.isShowing()) return; myTree.revalidate(); myTree.repaint(); } }); } @Override protected MasterDetailsStateService getStateService() { return MasterDetailsStateService.getInstance(myProject); } @Override public ActionCallback navigateTo(@Nullable final Place place, final boolean requestFocus) { if (place == null) return new ActionCallback.Done(); final Object object = place.getPath(TREE_OBJECT); final String byName = (String)place.getPath(TREE_NAME); if (object == null && byName == null) return new ActionCallback.Done(); final MyNode node = object == null ? null : findNodeByObject(myRoot, object); final MyNode nodeByName = byName == null ? null : findNodeByName(myRoot, byName); if (node == null && nodeByName == null) return new ActionCallback.Done(); final NamedConfigurable config; if (node != null) { config = node.getConfigurable(); } else { config = nodeByName.getConfigurable(); } final ActionCallback result = new ActionCallback().doWhenDone(new Runnable() { @Override public void run() { myAutoScrollEnabled = true; } }); myAutoScrollEnabled = false; myAutoScrollHandler.cancelAllRequests(); final MyNode nodeToSelect = node != null ? node : nodeByName; selectNodeInTree(nodeToSelect, requestFocus).doWhenDone(new Runnable() { @Override public void run() { setSelectedNode(nodeToSelect); Place.goFurther(config, place, requestFocus).notifyWhenDone(result); } }); return result; } @Override public void queryPlace(@NotNull final Place place) { if (myCurrentConfigurable != null) { place.putPath(TREE_OBJECT, myCurrentConfigurable.getEditableObject()); Place.queryFurther(myCurrentConfigurable, place); } } @Override protected void initTree() { if (myWasTreeInitialized) return; myWasTreeInitialized = true; super.initTree(); new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() { @Override public String convert(final TreePath treePath) { return ((MyNode)treePath.getLastPathComponent()).getDisplayName(); } }, true); ToolTipManager.sharedInstance().registerComponent(myTree); myTree.setCellRenderer(new ProjectStructureElementRenderer(myContext)); } @Override public void disposeUIResources() { if (myUiDisposed) return; super.disposeUIResources(); myUiDisposed = true; myAutoScrollHandler.cancelAllRequests(); myContext.getDaemonAnalyzer().clear(); Disposer.dispose(this); } public void checkCanApply() throws ConfigurationException { } protected void addCollapseExpandActions(final List<AnAction> result) { final TreeExpander expander = new TreeExpander() { @Override public void expandAll() { TreeUtil.expandAll(myTree); } @Override public boolean canExpand() { return true; } @Override public void collapseAll() { TreeUtil.collapseAll(myTree, 0); } @Override public boolean canCollapse() { return true; } }; final CommonActionsManager actionsManager = CommonActionsManager.getInstance(); result.add(actionsManager.createExpandAllAction(expander, myTree)); result.add(actionsManager.createCollapseAllAction(expander, myTree)); } @Nullable public ProjectStructureElement getSelectedElement() { final TreePath selectionPath = myTree.getSelectionPath(); if (selectionPath != null && selectionPath.getLastPathComponent() instanceof MyNode) { MyNode node = (MyNode)selectionPath.getLastPathComponent(); final NamedConfigurable configurable = node.getConfigurable(); if (configurable instanceof ProjectStructureElementConfigurable) { return ((ProjectStructureElementConfigurable)configurable).getProjectStructureElement(); } } return null; } private class MyFindUsagesAction extends FindUsagesInProjectStructureActionBase { public MyFindUsagesAction(JComponent parentComponent) { super(parentComponent, myProject); } @Override protected boolean isEnabled() { final TreePath selectionPath = myTree.getSelectionPath(); if (selectionPath != null){ final MyNode node = (MyNode)selectionPath.getLastPathComponent(); return !node.isDisplayInBold(); } else { return false; } } @Override protected StructureConfigurableContext getContext() { return myContext; } @Override protected ProjectStructureElement getSelectedElement() { return BaseStructureConfigurable.this.getSelectedElement(); } @Override protected RelativePoint getPointToShowResults() { final int selectedRow = myTree.getSelectionRows()[0]; final Rectangle rowBounds = myTree.getRowBounds(selectedRow); final Point location = rowBounds.getLocation(); location.x += rowBounds.width; return new RelativePoint(myTree, location); } } @Override public void reset() { myUiDisposed = false; if (!myWasTreeInitialized) { initTree(); myTree.setShowsRootHandles(false); loadTree(); } else { super.disposeUIResources(); myTree.setShowsRootHandles(false); loadTree(); } for (ProjectStructureElement element : getProjectStructureElements()) { myContext.getDaemonAnalyzer().queueUpdate(element); } super.reset(); } @NotNull protected Collection<? extends ProjectStructureElement> getProjectStructureElements() { return Collections.emptyList(); } protected abstract void loadTree(); @Override @NotNull protected ArrayList<AnAction> createActions(final boolean fromPopup) { final ArrayList<AnAction> result = new ArrayList<AnAction>(); AbstractAddGroup addAction = createAddAction(); if (addAction != null) { result.add(addAction); } result.add(new MyRemoveAction()); final List<? extends AnAction> copyActions = createCopyActions(fromPopup); result.addAll(copyActions); result.add(Separator.getInstance()); if (fromPopup || !(SystemInfo.isMac && Registry.is("ide.new.project.settings"))) { result.add(new MyFindUsagesAction(myTree)); } return result; } @NotNull protected List<? extends AnAction> createCopyActions(boolean fromPopup) { return Collections.emptyList(); } public void onStructureUnselected() { } public void onStructureSelected() { } @Nullable protected abstract AbstractAddGroup createAddAction(); protected class MyRemoveAction extends MyDeleteAction { public MyRemoveAction() { super(new Condition<Object[]>() { @Override public boolean value(final Object[] objects) { Object[] editableObjects = ContainerUtil.mapNotNull(objects, new Function<Object, Object>() { @Override public Object fun(Object object) { if (object instanceof MyNode) { final NamedConfigurable namedConfigurable = ((MyNode)object).getConfigurable(); if (namedConfigurable != null) { return namedConfigurable.getEditableObject(); } } return null; } }, new Object[0]); return editableObjects.length == objects.length && canBeRemoved(editableObjects); } }); } @Override public void actionPerformed(AnActionEvent e) { final TreePath[] paths = myTree.getSelectionPaths(); if (paths == null) return; final Set<TreePath> pathsToRemove = new HashSet<TreePath>(); for (TreePath path : paths) { if (removeFromModel(path)) { pathsToRemove.add(path); } } removePaths(pathsToRemove.toArray(new TreePath[pathsToRemove.size()])); } private boolean removeFromModel(final TreePath selectionPath) { final Object last = selectionPath.getLastPathComponent(); if (!(last instanceof MyNode)) return false; final MyNode node = (MyNode)last; final NamedConfigurable configurable = node.getConfigurable(); if (configurable == null) return false; final Object editableObject = configurable.getEditableObject(); return removeObject(editableObject); } } protected boolean canBeRemoved(final Object[] editableObjects) { for (Object editableObject : editableObjects) { if (!canObjectBeRemoved(editableObject)) return false; } return true; } private static boolean canObjectBeRemoved(Object editableObject) { if (editableObject instanceof Sdk || editableObject instanceof Module || editableObject instanceof Facet || editableObject instanceof Artifact) { return true; } if (editableObject instanceof Library) { final LibraryTable table = ((Library)editableObject).getTable(); return table == null || table.isEditable(); } return false; } protected boolean removeObject(final Object editableObject) { // todo keep only removeModule() and removeFacet() here because other removeXXX() are empty here and overridden in subclasses? Override removeObject() instead? if (editableObject instanceof Sdk) { removeJdk((Sdk)editableObject); } else if (editableObject instanceof Module) { if (!removeModule((Module)editableObject)) return false; } else if (editableObject instanceof Facet) { if (removeFacet((Facet)editableObject).isEmpty()) return false; } else if (editableObject instanceof Library) { if (!removeLibrary((Library)editableObject)) return false; } else if (editableObject instanceof Artifact) { removeArtifact((Artifact)editableObject); } return true; } protected void removeArtifact(Artifact artifact) { } protected boolean removeLibrary(Library library) { return false; } protected void removeFacetNodes(@NotNull List<Facet> facets) { for (Facet facet : facets) { MyNode node = findNodeByObject(myRoot, facet); if (node != null) { removePaths(TreeUtil.getPathFromRoot(node)); } } } protected List<Facet> removeFacet(final Facet facet) { return myContext.myModulesConfigurator.getFacetsConfigurator().removeFacet(facet); } protected boolean removeModule(final Module module) { return true; } protected void removeJdk(final Sdk editableObject) { } protected abstract static class AbstractAddGroup extends ActionGroup implements ActionGroupWithPreselection { protected AbstractAddGroup(String text, Icon icon) { super(text, true); final Presentation presentation = getTemplatePresentation(); presentation.setIcon(icon); final Keymap active = KeymapManager.getInstance().getActiveKeymap(); if (active != null) { final Shortcut[] shortcuts = active.getShortcuts("NewElement"); setShortcutSet(new CustomShortcutSet(shortcuts)); } } public AbstractAddGroup(String text) { this(text, IconUtil.getAddIcon()); } @Override public ActionGroup getActionGroup() { return this; } @Override public int getDefaultIndex() { return 0; } } }
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.ui.configuration.projectRoot; import com.intellij.facet.Facet; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.TreeExpander; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureDaemonAnalyzerListener; import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureElement; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.openapi.ui.MasterDetailsState; import com.intellij.openapi.ui.MasterDetailsStateService; import com.intellij.openapi.ui.NamedConfigurable; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.packaging.artifacts.Artifact; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.navigation.Place; import com.intellij.util.Function; import com.intellij.util.IconUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.*; import java.util.*; import java.util.List; public abstract class BaseStructureConfigurable extends MasterDetailsComponent implements SearchableConfigurable, Disposable, Place.Navigator { protected StructureConfigurableContext myContext; protected final Project myProject; protected boolean myUiDisposed = true; private boolean myWasTreeInitialized; protected boolean myAutoScrollEnabled = true; protected BaseStructureConfigurable(Project project, MasterDetailsState state) { super(state); myProject = project; } protected BaseStructureConfigurable(final Project project) { myProject = project; } public void init(StructureConfigurableContext context) { myContext = context; myContext.getDaemonAnalyzer().addListener(new ProjectStructureDaemonAnalyzerListener() { @Override public void problemsChanged(@NotNull ProjectStructureElement element) { if (!myTree.isShowing()) return; myTree.revalidate(); myTree.repaint(); } }); } @Override protected MasterDetailsStateService getStateService() { return MasterDetailsStateService.getInstance(myProject); } @Override public ActionCallback navigateTo(@Nullable final Place place, final boolean requestFocus) { if (place == null) return new ActionCallback.Done(); final Object object = place.getPath(TREE_OBJECT); final String byName = (String)place.getPath(TREE_NAME); if (object == null && byName == null) return new ActionCallback.Done(); final MyNode node = object == null ? null : findNodeByObject(myRoot, object); final MyNode nodeByName = byName == null ? null : findNodeByName(myRoot, byName); if (node == null && nodeByName == null) return new ActionCallback.Done(); final NamedConfigurable config; if (node != null) { config = node.getConfigurable(); } else { config = nodeByName.getConfigurable(); } final ActionCallback result = new ActionCallback().doWhenDone(new Runnable() { @Override public void run() { myAutoScrollEnabled = true; } }); myAutoScrollEnabled = false; myAutoScrollHandler.cancelAllRequests(); final MyNode nodeToSelect = node != null ? node : nodeByName; selectNodeInTree(nodeToSelect, requestFocus).doWhenDone(new Runnable() { @Override public void run() { setSelectedNode(nodeToSelect); Place.goFurther(config, place, requestFocus).notifyWhenDone(result); } }); return result; } @Override public void queryPlace(@NotNull final Place place) { if (myCurrentConfigurable != null) { place.putPath(TREE_OBJECT, myCurrentConfigurable.getEditableObject()); Place.queryFurther(myCurrentConfigurable, place); } } @Override protected void initTree() { if (myWasTreeInitialized) return; myWasTreeInitialized = true; super.initTree(); new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() { @Override public String convert(final TreePath treePath) { return ((MyNode)treePath.getLastPathComponent()).getDisplayName(); } }, true); ToolTipManager.sharedInstance().registerComponent(myTree); myTree.setCellRenderer(new ProjectStructureElementRenderer(myContext)); } @Override public void disposeUIResources() { if (myUiDisposed) return; super.disposeUIResources(); myUiDisposed = true; myAutoScrollHandler.cancelAllRequests(); myContext.getDaemonAnalyzer().clear(); Disposer.dispose(this); } public void checkCanApply() throws ConfigurationException { } protected void addCollapseExpandActions(final List<AnAction> result) { final TreeExpander expander = new TreeExpander() { @Override public void expandAll() { TreeUtil.expandAll(myTree); } @Override public boolean canExpand() { return true; } @Override public void collapseAll() { TreeUtil.collapseAll(myTree, 0); } @Override public boolean canCollapse() { return true; } }; final CommonActionsManager actionsManager = CommonActionsManager.getInstance(); result.add(actionsManager.createExpandAllAction(expander, myTree)); result.add(actionsManager.createCollapseAllAction(expander, myTree)); } @Nullable public ProjectStructureElement getSelectedElement() { final TreePath selectionPath = myTree.getSelectionPath(); if (selectionPath != null && selectionPath.getLastPathComponent() instanceof MyNode) { MyNode node = (MyNode)selectionPath.getLastPathComponent(); final NamedConfigurable configurable = node.getConfigurable(); if (configurable instanceof ProjectStructureElementConfigurable) { return ((ProjectStructureElementConfigurable)configurable).getProjectStructureElement(); } } return null; } private class MyFindUsagesAction extends FindUsagesInProjectStructureActionBase { public MyFindUsagesAction(JComponent parentComponent) { super(parentComponent, myProject); } @Override protected boolean isEnabled() { final TreePath selectionPath = myTree.getSelectionPath(); if (selectionPath != null){ final MyNode node = (MyNode)selectionPath.getLastPathComponent(); return !node.isDisplayInBold(); } else { return false; } } @Override protected StructureConfigurableContext getContext() { return myContext; } @Override protected ProjectStructureElement getSelectedElement() { return BaseStructureConfigurable.this.getSelectedElement(); } @Override protected RelativePoint getPointToShowResults() { final int selectedRow = myTree.getSelectionRows()[0]; final Rectangle rowBounds = myTree.getRowBounds(selectedRow); final Point location = rowBounds.getLocation(); location.x += rowBounds.width; return new RelativePoint(myTree, location); } } @Override public void reset() { myUiDisposed = false; if (!myWasTreeInitialized) { initTree(); myTree.setShowsRootHandles(false); loadTree(); } else { super.disposeUIResources(); myTree.setShowsRootHandles(false); loadTree(); } for (ProjectStructureElement element : getProjectStructureElements()) { myContext.getDaemonAnalyzer().queueUpdate(element); } super.reset(); } @NotNull protected Collection<? extends ProjectStructureElement> getProjectStructureElements() { return Collections.emptyList(); } protected abstract void loadTree(); @Override @NotNull protected ArrayList<AnAction> createActions(final boolean fromPopup) { final ArrayList<AnAction> result = new ArrayList<AnAction>(); AbstractAddGroup addAction = createAddAction(); if (addAction != null) { result.add(addAction); } result.add(new MyRemoveAction()); final List<? extends AnAction> copyActions = createCopyActions(fromPopup); result.addAll(copyActions); result.add(Separator.getInstance()); result.add(new MyFindUsagesAction(myTree)); return result; } @NotNull protected List<? extends AnAction> createCopyActions(boolean fromPopup) { return Collections.emptyList(); } public void onStructureUnselected() { } public void onStructureSelected() { } @Nullable protected abstract AbstractAddGroup createAddAction(); protected class MyRemoveAction extends MyDeleteAction { public MyRemoveAction() { super(new Condition<Object[]>() { @Override public boolean value(final Object[] objects) { Object[] editableObjects = ContainerUtil.mapNotNull(objects, new Function<Object, Object>() { @Override public Object fun(Object object) { if (object instanceof MyNode) { final NamedConfigurable namedConfigurable = ((MyNode)object).getConfigurable(); if (namedConfigurable != null) { return namedConfigurable.getEditableObject(); } } return null; } }, new Object[0]); return editableObjects.length == objects.length && canBeRemoved(editableObjects); } }); } @Override public void actionPerformed(AnActionEvent e) { final TreePath[] paths = myTree.getSelectionPaths(); if (paths == null) return; final Set<TreePath> pathsToRemove = new HashSet<TreePath>(); for (TreePath path : paths) { if (removeFromModel(path)) { pathsToRemove.add(path); } } removePaths(pathsToRemove.toArray(new TreePath[pathsToRemove.size()])); } private boolean removeFromModel(final TreePath selectionPath) { final Object last = selectionPath.getLastPathComponent(); if (!(last instanceof MyNode)) return false; final MyNode node = (MyNode)last; final NamedConfigurable configurable = node.getConfigurable(); if (configurable == null) return false; final Object editableObject = configurable.getEditableObject(); return removeObject(editableObject); } } protected boolean canBeRemoved(final Object[] editableObjects) { for (Object editableObject : editableObjects) { if (!canObjectBeRemoved(editableObject)) return false; } return true; } private static boolean canObjectBeRemoved(Object editableObject) { if (editableObject instanceof Sdk || editableObject instanceof Module || editableObject instanceof Facet || editableObject instanceof Artifact) { return true; } if (editableObject instanceof Library) { final LibraryTable table = ((Library)editableObject).getTable(); return table == null || table.isEditable(); } return false; } protected boolean removeObject(final Object editableObject) { // todo keep only removeModule() and removeFacet() here because other removeXXX() are empty here and overridden in subclasses? Override removeObject() instead? if (editableObject instanceof Sdk) { removeJdk((Sdk)editableObject); } else if (editableObject instanceof Module) { if (!removeModule((Module)editableObject)) return false; } else if (editableObject instanceof Facet) { if (removeFacet((Facet)editableObject).isEmpty()) return false; } else if (editableObject instanceof Library) { if (!removeLibrary((Library)editableObject)) return false; } else if (editableObject instanceof Artifact) { removeArtifact((Artifact)editableObject); } return true; } protected void removeArtifact(Artifact artifact) { } protected boolean removeLibrary(Library library) { return false; } protected void removeFacetNodes(@NotNull List<Facet> facets) { for (Facet facet : facets) { MyNode node = findNodeByObject(myRoot, facet); if (node != null) { removePaths(TreeUtil.getPathFromRoot(node)); } } } protected List<Facet> removeFacet(final Facet facet) { return myContext.myModulesConfigurator.getFacetsConfigurator().removeFacet(facet); } protected boolean removeModule(final Module module) { return true; } protected void removeJdk(final Sdk editableObject) { } protected abstract static class AbstractAddGroup extends ActionGroup implements ActionGroupWithPreselection { protected AbstractAddGroup(String text, Icon icon) { super(text, true); final Presentation presentation = getTemplatePresentation(); presentation.setIcon(icon); final Keymap active = KeymapManager.getInstance().getActiveKeymap(); if (active != null) { final Shortcut[] shortcuts = active.getShortcuts("NewElement"); setShortcutSet(new CustomShortcutSet(shortcuts)); } } public AbstractAddGroup(String text) { this(text, IconUtil.getAddIcon()); } @Override public ActionGroup getActionGroup() { return this; } @Override public int getDefaultIndex() { return 0; } } }
don't show find usages on toolbar in new project settings dialog
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java
don't show find usages on toolbar in new project settings dialog
Java
apache-2.0
79a7aa09d4bf89308053bd3e5717ebd2b2d561ec
0
holmes/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,petteyg/intellij-community,xfournet/intellij-community,samthor/intellij-community,hurricup/intellij-community,amith01994/intellij-community,samthor/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,dslomov/intellij-community,semonte/intellij-community,hurricup/intellij-community,caot/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,wreckJ/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,asedunov/intellij-community,jagguli/intellij-community,semonte/intellij-community,da1z/intellij-community,asedunov/intellij-community,adedayo/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,caot/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,signed/intellij-community,Lekanich/intellij-community,supersven/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ryano144/intellij-community,dslomov/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,samthor/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,signed/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,vladmm/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,clumsy/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,samthor/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,supersven/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,samthor/intellij-community,ibinti/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,caot/intellij-community,slisson/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,slisson/intellij-community,fitermay/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,ryano144/intellij-community,fnouama/intellij-community,kool79/intellij-community,retomerz/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,da1z/intellij-community,kdwink/intellij-community,retomerz/intellij-community,fitermay/intellij-community,da1z/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,fitermay/intellij-community,izonder/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,diorcety/intellij-community,holmes/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,signed/intellij-community,allotria/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,FHannes/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,izonder/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ibinti/intellij-community,xfournet/intellij-community,retomerz/intellij-community,slisson/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,izonder/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,holmes/intellij-community,semonte/intellij-community,fnouama/intellij-community,vladmm/intellij-community,asedunov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,signed/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,robovm/robovm-studio,semonte/intellij-community,vladmm/intellij-community,asedunov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,adedayo/intellij-community,dslomov/intellij-community,jagguli/intellij-community,clumsy/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,fitermay/intellij-community,fitermay/intellij-community,caot/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,fnouama/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,jagguli/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,akosyakov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,jagguli/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,allotria/intellij-community,amith01994/intellij-community,amith01994/intellij-community,diorcety/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,caot/intellij-community,semonte/intellij-community,hurricup/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,asedunov/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,adedayo/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,robovm/robovm-studio,FHannes/intellij-community,kdwink/intellij-community,slisson/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,blademainer/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,clumsy/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,signed/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,FHannes/intellij-community,robovm/robovm-studio,holmes/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,supersven/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,diorcety/intellij-community,holmes/intellij-community,caot/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,holmes/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,slisson/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,semonte/intellij-community,gnuhub/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,caot/intellij-community,da1z/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,supersven/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,xfournet/intellij-community,retomerz/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,slisson/intellij-community,slisson/intellij-community,jagguli/intellij-community,kool79/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,allotria/intellij-community,petteyg/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,petteyg/intellij-community,adedayo/intellij-community,supersven/intellij-community,diorcety/intellij-community,vladmm/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,semonte/intellij-community,blademainer/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,semonte/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,signed/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,petteyg/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,caot/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,fnouama/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,xfournet/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,signed/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,da1z/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,Distrotech/intellij-community,allotria/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,apixandru/intellij-community,orekyuu/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.fileEditor.impl; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.ArrayUtilRt; import com.intellij.util.messages.MessageBusConnection; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public final class EditorHistoryManager extends AbstractProjectComponent implements JDOMExternalizable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.EditorHistoryManager"); private Element myElement; public static EditorHistoryManager getInstance(final Project project){ return project.getComponent(EditorHistoryManager.class); } /** * State corresponding to the most recent file is the last */ private final ArrayList<HistoryEntry> myEntriesList = new ArrayList<HistoryEntry>(); /** Invoked by reflection */ EditorHistoryManager(final Project project, final UISettings uiSettings){ super(project); uiSettings.addUISettingsListener(new MyUISettingsListener(), project); } @Override public void projectOpened(){ MessageBusConnection connection = myProject.getMessageBus().connect(); connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, new MyEditorManagerBeforeListener()); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MyEditorManagerListener()); StartupManager.getInstance(myProject).runWhenProjectIsInitialized( new DumbAwareRunnable() { @Override public void run() { // myElement may be null if node that corresponds to this manager does not exist if (myElement != null) { final List children = myElement.getChildren(HistoryEntry.TAG); myElement = null; //noinspection unchecked for (final Element e : (Iterable<Element>)children) { try { myEntriesList.add(new HistoryEntry(myProject, e)); } catch (InvalidDataException e1) { // OK here } catch (ProcessCanceledException e1) { // OK here } catch (Exception anyException) { LOG.error(anyException); } } trimToSize(); } } } ); } @Override @NotNull public String getComponentName(){ return "editorHistoryManager"; } private void fileOpenedImpl(@NotNull final VirtualFile file) { fileOpenedImpl(file, null, null); } /** * Makes file most recent one */ private void fileOpenedImpl(@NotNull final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider) { ApplicationManager.getApplication().assertIsDispatchThread(); // don't add files that cannot be found via VFM (light & etc.) if (VirtualFileManager.getInstance().findFileByUrl(file.getUrl()) == null) return; final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file); FileEditor[] editors = editorsWithProviders.getFirst(); FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); if (editors.length <= 0 && fallbackEditor != null) { editors = new FileEditor[] { fallbackEditor }; } if (oldProviders.length <= 0 && fallbackProvider != null) { oldProviders = new FileEditorProvider[] { fallbackProvider }; } if (editors.length <= 0) { LOG.error("No editors for file " + file.getPresentableUrl()); } FileEditor selectedEditor = editorManager.getSelectedEditor(file); if (selectedEditor == null) { selectedEditor = fallbackEditor; } LOG.assertTrue(selectedEditor != null); final int selectedProviderIndex = ArrayUtilRt.find(editors, selectedEditor); LOG.assertTrue(selectedProviderIndex != -1); final HistoryEntry entry = getEntry(file); if(entry != null){ myEntriesList.remove(entry); myEntriesList.add(entry); } else { final FileEditorState[] states=new FileEditorState[editors.length]; final FileEditorProvider[] providers=new FileEditorProvider[editors.length]; for (int i = states.length - 1; i >= 0; i--) { final FileEditorProvider provider = oldProviders [i]; LOG.assertTrue(provider != null); providers[i] = provider; states[i] = editors[i].getState(FileEditorStateLevel.FULL); } myEntriesList.add(new HistoryEntry(file, providers, states, providers[selectedProviderIndex])); trimToSize(); } } public void updateHistoryEntry(@Nullable final VirtualFile file, final boolean changeEntryOrderOnly) { updateHistoryEntry(file, null, null, changeEntryOrderOnly); } private void updateHistoryEntry(@Nullable final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider, final boolean changeEntryOrderOnly) { if (file == null) { return; } final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file); FileEditor[] editors = editorsWithProviders.getFirst(); FileEditorProvider[] providers = editorsWithProviders.getSecond(); if (editors.length <= 0 && fallbackEditor != null) { editors = new FileEditor[] {fallbackEditor}; providers = new FileEditorProvider[] {fallbackProvider}; } if (editors.length == 0) { // obviously not opened in any editor at the moment, // makes no sense to put the file in the history return; } final HistoryEntry entry = getEntry(file); if(entry == null){ // Size of entry list can be less than number of opened editors (some entries can be removed) if (file.isValid()) { // the file could have been deleted, so the isValid() check is essential fileOpenedImpl(file, fallbackEditor, fallbackProvider); } return; } if (!changeEntryOrderOnly) { // update entry state //LOG.assertTrue(editors.length > 0); for (int i = editors.length - 1; i >= 0; i--) { final FileEditor editor = editors [i]; final FileEditorProvider provider = providers [i]; if (!editor.isValid()) { // this can happen for example if file extension was changed // and this method was called during corresponding myEditor close up continue; } final FileEditorState oldState = entry.getState(provider); final FileEditorState newState = editor.getState(FileEditorStateLevel.FULL); if (!newState.equals(oldState)) { entry.putState(provider, newState); } } } final Pair <FileEditor, FileEditorProvider> selectedEditorWithProvider = editorManager.getSelectedEditorWithProvider(file); if (selectedEditorWithProvider != null) { //LOG.assertTrue(selectedEditorWithProvider != null); entry.mySelectedProvider = selectedEditorWithProvider.getSecond (); LOG.assertTrue(entry.mySelectedProvider != null); if(changeEntryOrderOnly){ myEntriesList.remove(entry); myEntriesList.add(entry); } } } /** * Removes all entries that correspond to invalid files */ private void validateEntries(){ for(int i=myEntriesList.size()-1; i>=0; i--){ final HistoryEntry entry = myEntriesList.get(i); if(!entry.myFile.isValid()){ myEntriesList.remove(i); } } } /** * @return array of valid files that are in the history. The greater is index the more recent the file is. */ public VirtualFile[] getFiles(){ validateEntries(); final VirtualFile[] result = new VirtualFile[myEntriesList.size()]; for(int i=myEntriesList.size()-1; i>=0 ;i--){ result[i] = myEntriesList.get(i).myFile; } return result; } public boolean hasBeenOpen(@NotNull VirtualFile f) { for (HistoryEntry each : myEntriesList) { if (Comparing.equal(each.myFile, f)) return true; } return false; } /** * Removes specified <code>file</code> from history. The method does * nothing if <code>file</code> is not in the history. * * @exception java.lang.IllegalArgumentException if <code>file</code> * is <code>null</code> */ public void removeFile(@NotNull final VirtualFile file){ final HistoryEntry entry = getEntry(file); if(entry != null){ myEntriesList.remove(entry); } } public FileEditorState getState(final VirtualFile file, final FileEditorProvider provider) { validateEntries(); final HistoryEntry entry = getEntry(file); return entry != null ? entry.getState(provider) : null; } /** * @return may be null */ public FileEditorProvider getSelectedProvider(final VirtualFile file) { validateEntries(); final HistoryEntry entry = getEntry(file); return entry != null ? entry.mySelectedProvider : null; } private HistoryEntry getEntry(final VirtualFile file){ validateEntries(); for (int i = myEntriesList.size() - 1; i >= 0; i--) { final HistoryEntry entry = myEntriesList.get(i); if(file.equals(entry.myFile)){ return entry; } } return null; } /** * If total number of files in history more then <code>UISettings.RECENT_FILES_LIMIT</code> * then removes the oldest ones to fit the history to new size. */ private void trimToSize(){ final int limit = UISettings.getInstance().RECENT_FILES_LIMIT + 1; while(myEntriesList.size()>limit){ myEntriesList.remove(0); } } @Override public void readExternal(final Element element) { // we have to delay xml processing because history entries require EditorStates to be created // which is done via corresponding EditorProviders, those are not accessible before their // is initComponent() called myElement = element.clone(); } @Override public void writeExternal(final Element element){ // update history before saving final VirtualFile[] openFiles = FileEditorManager.getInstance(myProject).getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { final VirtualFile file = openFiles[i]; if(getEntry(file) != null){ // we have to update only files that are in history updateHistoryEntry(file, false); } } for (final HistoryEntry entry : myEntriesList) { entry.writeExternal(element, myProject); } } /** * Updates history */ private final class MyEditorManagerListener extends FileEditorManagerAdapter{ @Override public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file){ fileOpenedImpl(file); } @Override public void selectionChanged(@NotNull final FileEditorManagerEvent event){ // updateHistoryEntry does commitDocument which is 1) very expensive and 2) cannot be performed from within PSI change listener // so defer updating history entry until documents committed to improve responsiveness PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(new Runnable() { @Override public void run() { updateHistoryEntry(event.getOldFile(), event.getOldEditor(), event.getOldProvider(), false); updateHistoryEntry(event.getNewFile(), true); } }); } } private final class MyEditorManagerBeforeListener extends FileEditorManagerListener.Before.Adapter { @Override public void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { updateHistoryEntry(file, false); } } /** * Cuts/extends history length */ private final class MyUISettingsListener implements UISettingsListener{ @Override public void uiSettingsChanged(final UISettings source) { trimToSize(); } } }
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.fileEditor.impl; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.ArrayUtilRt; import com.intellij.util.messages.MessageBusConnection; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public final class EditorHistoryManager extends AbstractProjectComponent implements JDOMExternalizable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.EditorHistoryManager"); private Element myElement; public static EditorHistoryManager getInstance(final Project project){ return project.getComponent(EditorHistoryManager.class); } /** * State corresponding to the most recent file is the last */ private final ArrayList<HistoryEntry> myEntriesList = new ArrayList<HistoryEntry>(); /** Invoked by reflection */ EditorHistoryManager(final Project project, final UISettings uiSettings){ super(project); uiSettings.addUISettingsListener(new MyUISettingsListener(), project); } @Override public void projectOpened(){ MessageBusConnection connection = myProject.getMessageBus().connect(); connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, new MyEditorManagerBeforeListener()); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MyEditorManagerListener()); StartupManager.getInstance(myProject).runWhenProjectIsInitialized( new DumbAwareRunnable() { @Override public void run() { // myElement may be null if node that corresponds to this manager does not exist if (myElement != null) { final List children = myElement.getChildren(HistoryEntry.TAG); myElement = null; //noinspection unchecked for (final Element e : (Iterable<Element>)children) { try { myEntriesList.add(new HistoryEntry(myProject, e)); } catch (InvalidDataException e1) { // OK here } catch (ProcessCanceledException e1) { // OK here } catch (Exception anyException) { LOG.error(anyException); } } trimToSize(); } } } ); } @Override @NotNull public String getComponentName(){ return "editorHistoryManager"; } private void fileOpenedImpl(@NotNull final VirtualFile file) { fileOpenedImpl(file, null, null); } /** * Makes file most recent one */ private void fileOpenedImpl(@NotNull final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider) { ApplicationManager.getApplication().assertIsDispatchThread(); // don't add files that cannot be found via VFM (light & etc.) if (VirtualFileManager.getInstance().findFileByUrl(file.getUrl()) == null) return; final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file); FileEditor[] editors = editorsWithProviders.getFirst(); FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); if (editors.length <= 0 && fallbackEditor != null) { editors = new FileEditor[] { fallbackEditor }; } if (oldProviders.length <= 0 && fallbackProvider != null) { oldProviders = new FileEditorProvider[] { fallbackProvider }; } if (editors.length <= 0) { LOG.error("No editors for file " + file.getPresentableUrl()); } FileEditor selectedEditor = editorManager.getSelectedEditor(file); if (selectedEditor == null) { selectedEditor = fallbackEditor; } LOG.assertTrue(selectedEditor != null); final int selectedProviderIndex = ArrayUtilRt.find(editors, selectedEditor); LOG.assertTrue(selectedProviderIndex != -1); final HistoryEntry entry = getEntry(file); if(entry != null){ myEntriesList.remove(entry); myEntriesList.add(entry); } else { final FileEditorState[] states=new FileEditorState[editors.length]; final FileEditorProvider[] providers=new FileEditorProvider[editors.length]; for (int i = states.length - 1; i >= 0; i--) { final FileEditorProvider provider = oldProviders [i]; LOG.assertTrue(provider != null); providers[i] = provider; states[i] = editors[i].getState(FileEditorStateLevel.FULL); } myEntriesList.add(new HistoryEntry(file, providers, states, providers[selectedProviderIndex])); trimToSize(); } } public void updateHistoryEntry(@Nullable final VirtualFile file, final boolean changeEntryOrderOnly) { updateHistoryEntry(file, null, null, changeEntryOrderOnly); } private void updateHistoryEntry(@Nullable final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider, final boolean changeEntryOrderOnly) { if (file == null) { return; } final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file); FileEditor[] editors = editorsWithProviders.getFirst(); FileEditorProvider[] providers = editorsWithProviders.getSecond(); if (editors.length <= 0 && fallbackEditor != null) { editors = new FileEditor[] {fallbackEditor}; providers = new FileEditorProvider[] {fallbackProvider}; } if (editors.length == 0) { // obviously not opened in any editor at the moment, // makes no sense to put the file in the history return; } final HistoryEntry entry = getEntry(file); if(entry == null){ // Size of entry list can be less than number of opened editors (some entries can be removed) if (file.isValid()) { // the file could have been deleted, so the isValid() check is essential fileOpenedImpl(file, fallbackEditor, fallbackProvider); } return; } if (!changeEntryOrderOnly) { // update entry state //LOG.assertTrue(editors.length > 0); for (int i = editors.length - 1; i >= 0; i--) { final FileEditor editor = editors [i]; final FileEditorProvider provider = providers [i]; if (!editor.isValid()) { // this can happen for example if file extension was changed // and this method was called during corresponding myEditor close up continue; } final FileEditorState oldState = entry.getState(provider); final FileEditorState newState = editor.getState(FileEditorStateLevel.FULL); if (!newState.equals(oldState)) { entry.putState(provider, newState); } } } final Pair <FileEditor, FileEditorProvider> selectedEditorWithProvider = editorManager.getSelectedEditorWithProvider(file); if (selectedEditorWithProvider != null) { //LOG.assertTrue(selectedEditorWithProvider != null); entry.mySelectedProvider = selectedEditorWithProvider.getSecond (); LOG.assertTrue(entry.mySelectedProvider != null); if(changeEntryOrderOnly){ myEntriesList.remove(entry); myEntriesList.add(entry); } } } /** * Removes all entries that correspond to invalid files */ private void validateEntries(){ for(int i=myEntriesList.size()-1; i>=0; i--){ final HistoryEntry entry = myEntriesList.get(i); if(!entry.myFile.isValid()){ myEntriesList.remove(i); } } } /** * @return array of valid files that are in the history. The greater is index the more recent the file is. */ public VirtualFile[] getFiles(){ validateEntries(); final VirtualFile[] result = new VirtualFile[myEntriesList.size()]; for(int i=myEntriesList.size()-1; i>=0 ;i--){ result[i] = myEntriesList.get(i).myFile; } return result; } public boolean hasBeenOpen(@NotNull VirtualFile f) { for (HistoryEntry each : myEntriesList) { if (Comparing.equal(each.myFile, f)) return true; } return false; } /** * Removes specified <code>file</code> from history. The method does * nothing if <code>file</code> is not in the history. * * @exception java.lang.IllegalArgumentException if <code>file</code> * is <code>null</code> */ public void removeFile(@NotNull final VirtualFile file){ final HistoryEntry entry = getEntry(file); if(entry != null){ myEntriesList.remove(entry); } } public FileEditorState getState(final VirtualFile file, final FileEditorProvider provider) { validateEntries(); final HistoryEntry entry = getEntry(file); return entry != null ? entry.getState(provider) : null; } /** * @return may be null */ public FileEditorProvider getSelectedProvider(final VirtualFile file) { validateEntries(); final HistoryEntry entry = getEntry(file); return entry != null ? entry.mySelectedProvider : null; } private HistoryEntry getEntry(final VirtualFile file){ validateEntries(); for (int i = myEntriesList.size() - 1; i >= 0; i--) { final HistoryEntry entry = myEntriesList.get(i); if(file.equals(entry.myFile)){ return entry; } } return null; } /** * If total number of files in history more then <code>UISettings.RECENT_FILES_LIMIT</code> * then removes the oldest ones to fit the history to new size. */ private void trimToSize(){ final int limit = UISettings.getInstance().RECENT_FILES_LIMIT + 1; while(myEntriesList.size()>limit){ myEntriesList.remove(0); } } @Override public void readExternal(final Element element) { // we have to delay xml processing because history entries require EditorStates to be created // which is done via corresponding EditorProviders, those are not accessible before their // is initComponent() called myElement = element.clone(); } @Override public void writeExternal(final Element element){ // update history before saving final VirtualFile[] openFiles = FileEditorManager.getInstance(myProject).getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { final VirtualFile file = openFiles[i]; if(getEntry(file) != null){ // we have to update only files that are in history updateHistoryEntry(file, false); } } for (final HistoryEntry entry : myEntriesList) { entry.writeExternal(element, myProject); } } /** * Updates history */ private final class MyEditorManagerListener extends FileEditorManagerAdapter{ @Override public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file){ fileOpenedImpl(file); } @Override public void selectionChanged(@NotNull final FileEditorManagerEvent event){ updateHistoryEntry(event.getOldFile(), event.getOldEditor(), event.getOldProvider(), false); updateHistoryEntry(event.getNewFile(), true); } } private final class MyEditorManagerBeforeListener extends FileEditorManagerListener.Before.Adapter { @Override public void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { updateHistoryEntry(file, false); } } /** * Cuts/extends history length */ private final class MyUISettingsListener implements UISettingsListener{ @Override public void uiSettingsChanged(final UISettings source) { trimToSize(); } } }
EA-46683 - assert: PsiDocumentManagerBase.doCommit
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java
EA-46683 - assert: PsiDocumentManagerBase.doCommit
Java
bsd-2-clause
fae0419f8eb9c633cd7a3a40db1e958755b4e0aa
0
dmilios/U-check,dmilios/U-check
package ucheck.cli; import gp.classification.ProbitRegressionPosterior; import gpoptim.GpoResult; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import com.panayotis.gnuplot.GNUPlotException; import lff.LFFOptions; import lff.LearnFromFormulae; import linalg.NonPosDefMatrixException; import modelChecking.MitlModelChecker; import priors.Prior; import smoothedMC.SmmcOptions; import smoothedMC.SmmcUtils; import smoothedMC.SmoothedModelCheker; import ucheck.UcheckPlot; import ucheck.config.UcheckConfig; public class UcheckCLI { public static void main(String[] args) throws IOException { final Log log = new PrintStreamLog(System.out); String title = "# U-check: " + "Model Checking and Parameter Synthesis under Uncertainty"; String usage = "Usage: ucheck [-h|--help|FILE]"; String optionfilehelp = " \'FILE\' the experiment configuration file"; String helpOption = " -h, --help " + "a default configuration file will be print on screen"; log.println(title); log.println(); if (args.length == 0) { log.println(usage); log.println(); log.println(optionfilehelp); log.println(helpOption); log.println(); return; } if (args[0].equals("-h") || args[0].equals("--help")) { log.println(UcheckHelp.getHelp()); return; } final String optionfile = args[0]; FileInputStream fstream = null; UcheckConfig config = null; try { fstream = new FileInputStream(optionfile); config = new UcheckConfig(log); config.load(fstream); fstream.close(); } catch (IOException e) { log.printError(e.getMessage()); } if (config != null) { // all errors should be caught by this point if (log.getErrors() > 0) return; final String mode = config.getMode(); if (mode.equals("inference")) performInference(config, log); if (mode.equals("robust")) performRobustSystemDesign(config, log); if (mode.equals("smoothedmc")) performSmoothedMC(config, log); } if (log.getWarnings() > 0) log.println("\nTotal warnings: " + log.getWarnings()); if (log.getErrors() > 0) { log.println("\nOperation could not be completed due to errors!"); log.println("Total errors: " + log.getErrors()); } } public static void performInference(UcheckConfig config, Log log) { final MitlModelChecker modelChecker = config.getModelChecker(); final boolean[][] observations = config.getObservations(); final LFFOptions lffOptions = config.getLFFOptions(); final lff.Parameter[] params = config.getLFFParameters(); final Prior[] priors = config.getLFFPriors(); LearnFromFormulae lff = new LearnFromFormulae(modelChecker); lff.setParams(params); lff.setPriors(priors); lff.setOptions(lffOptions); GpoResult result = lff.performInference(observations); printInferenceResults(log, config, result); } public static void performRobustSystemDesign(UcheckConfig config, Log log) { final MitlModelChecker modelChecker = config.getModelChecker(); final LFFOptions lffOptions = config.getLFFOptions(); final lff.Parameter[] params = config.getLFFParameters(); LearnFromFormulae lff = new LearnFromFormulae(modelChecker); lff.setParams(params); lff.setOptions(lffOptions); GpoResult result = lff.robustSystemDesign(config.getRobustnessType()); printRobustnessResults(log, config, result); } public static void performSmoothedMC(UcheckConfig config, Log log) { final File outDir = new File(config.getOutputDir()); if (!outDir.exists()) outDir.mkdirs(); if (!outDir.canWrite() || !outDir.isDirectory()) { log.printError("Cannot write into the '" + outDir + "' directory!"); return; } final MitlModelChecker check = config.getModelChecker(); final SmmcOptions options = config.getSmMCOptions(); final smoothedMC.Parameter[] params = config.getSmMCParameters(); final SmoothedModelCheker smmc = new SmoothedModelCheker(); ProbitRegressionPosterior result = null; try { result = smmc.performSmoothedModelChecking(check, params, options); } catch (NonPosDefMatrixException e) { log.printError("Non-positive definite Gram matrix; " + "try increasing 'covarianceCorrection'. " + "The current value has been: " + config.getSmMCOptions().getCovarianceCorrection()); return; } printSmmcResults(log, config, smmc, result); final UcheckPlot plot = new UcheckPlot(); try { plot.plotSmoothedMC(result, params, 2); } catch (GNUPlotException e) { log.printWarning("Gnuplot executable '/usr/bin/gnuplot' " + "was not found.\n Please install Gnuplot " + "for automatic plotting of the results"); } } private static void printInferenceResults(Log log, UcheckConfig config, GpoResult result) { final lff.Parameter[] params = config.getLFFParameters(); log.println(); log.println("# Inference from Qualitative Data"); log.println("Model file: " + config.getModelFile()); log.println("MiTL file: " + config.getMitlFile()); log.println(); log.print("Parameters explored: "); log.print(params[0].getName()); for (int i = 1; i < params.length; i++) log.print(", " + params[i].getName()); log.println(); log.println(); log.println(result.toString()); log.println("\n"); } private static void printRobustnessResults(Log log, UcheckConfig config, GpoResult result) { final lff.Parameter[] params = config.getLFFParameters(); log.println(); log.println("# Robust Parameter Synthesis"); switch (config.getRobustnessType()) { case AvgRobustness: log.println("## Average Robustness"); break; case CondAvgRobustnessTrue: log.println("## Conditional Average Robustness given the property is true"); break; case CondAvgRobustnessFalse: log.println("## Conditional Average Robustness given the property is false"); break; } log.println("Model file: " + config.getModelFile()); log.println("MiTL file: " + config.getMitlFile()); log.println(); log.print("Parameters explored: "); log.print(params[0].getName()); for (int i = 1; i < params.length; i++) log.print(", " + params[i].getName()); log.println(); log.println(); log.println(result.toString()); log.println("\n"); } private static void printSmmcResults(Log log, UcheckConfig config, SmoothedModelCheker smmc, ProbitRegressionPosterior result) { final smoothedMC.Parameter[] params = config.getSmMCParameters(); final double smcElapsed = smmc.getStatisticalMCTimeElapsed(); final double hypElapsed = smmc.getHyperparamOptimTimeElapsed(); final double smmcElapsed = smmc.getSmoothedMCTimeElapsed(); final double[] hyperparams = smmc.getHyperparamsUsed(); log.println(); log.println("# Smoothed Model Checking --- Results"); log.println("Model file: " + config.getModelFile()); log.println("MiTL file: " + config.getMitlFile()); log.println(); log.print("Parameters explored: "); log.print(params[0].getName()); for (int i = 1; i < params.length; i++) log.print(", " + params[i].getName()); log.println(); log.println("Hyperparams used: "); log.println(" amplitude: " + hyperparams[0]); for (int i = 1; i < hyperparams.length; i++) log.println(" lengthscale: " + hyperparams[i]); log.println(); log.println("Time for Statistical MC: " + smcElapsed + " sec"); log.println("Time for hyperparam opt: " + hypElapsed + " sec"); log.println("Time for Smoothed MC: " + smmcElapsed + " sec"); log.println(); final String dir = config.getOutputDir(); final String fullname = (new File(config.getModelFile())).getName(); final String name = fullname.substring(0, fullname.lastIndexOf('.')); final String csv = dir + File.separator + name + ".csv"; final String mfile = dir + File.separator + "load_" + name + ".m"; final double beta = 2; final String resultStr = SmmcUtils.results2csv(result, beta); final String matlabStr = produceMatlabScript(params, name); if (writeToFile(csv, resultStr)) log.println("Smoothed MC results have been written to '" + csv + "'"); else log.printError("Could not write to output file '" + csv + "'"); if (writeToFile(mfile, matlabStr)) log.println("A MATLAB/Octave script has been produced in '" + mfile + "'"); else log.printError("Could not write to output file '" + mfile + "'"); log.println("\n"); } static private String produceMatlabScript(smoothedMC.Parameter[] params, String name) { final int dimension = params.length; String str = ""; str += "% ===== This file has been automatically produced by the\n"; str += "% ===== U-check model checking tool for uncertain systems\n"; str += "% \n"; str += "% It loads the Smoothed Model Checking results from '" + name + ".csv'\n"; str += "% Parameters explored: " + params[0].getName(); for (int i = 1; i < params.length; i++) str += ", " + params[i].getName(); str += "\n\n"; str += "if exist('OCTAVE_VERSION', 'builtin')\n"; str += "\tdata = load('" + name + ".csv" + "');\n"; str += "else\n"; str += "\tdata = csvread('" + name + ".csv', 1);\n"; str += "end\n"; str += "\n"; str += "% 'paramValues' " + "is a Nx" + dimension + " matrix (grid of values in the parameter space)\n"; str += "% 'probabilities' " + "contains the estimated satisfaction probabilities\n"; str += "% 'lowerConfBound' " + "Lower confidence bound for the satisfaction probabilities\n"; str += "% 'upperConfBound' " + "Upper confidence bound for the satisfaction probabilities\n"; str += "\n"; str += "paramNames = {" + "'" + params[0].getName() + "'"; for (int i = 1; i < params.length; i++) str += ", '" + params[i].getName() + "'"; str += "};\n"; str += "paramValues = data(:, 1:" + dimension + ");\n"; str += "probabilities = data(:, " + (dimension + 1) + ");\n"; str += "lowerConfBound = data(:, " + (dimension + 2) + ");\n"; str += "upperConfBound = data(:, " + (dimension + 3) + ");\n"; return str; } static final private boolean writeToFile(String file, String contents) { try { FileWriter fw = new FileWriter(file); fw.write(contents); fw.close(); return true; } catch (IOException e) { return false; } } }
Ucheck/src/ucheck/cli/UcheckCLI.java
package ucheck.cli; import gp.classification.ProbitRegressionPosterior; import gpoptim.GpoResult; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import lff.LFFOptions; import lff.LearnFromFormulae; import linalg.NonPosDefMatrixException; import modelChecking.MitlModelChecker; import priors.Prior; import smoothedMC.SmmcOptions; import smoothedMC.SmmcUtils; import smoothedMC.SmoothedModelCheker; import ucheck.UcheckPlot; import ucheck.config.UcheckConfig; public class UcheckCLI { public static void main(String[] args) throws IOException { final Log log = new PrintStreamLog(System.out); String title = "# U-check: " + "Model Checking and Parameter Synthesis under Uncertainty"; String usage = "Usage: ucheck [-h|--help|FILE]"; String optionfilehelp = " \'FILE\' the experiment configuration file"; String helpOption = " -h, --help " + "a default configuration file will be print on screen"; log.println(title); log.println(); if (args.length == 0) { log.println(usage); log.println(); log.println(optionfilehelp); log.println(helpOption); log.println(); return; } if (args[0].equals("-h") || args[0].equals("--help")) { log.println(UcheckHelp.getHelp()); return; } final String optionfile = args[0]; FileInputStream fstream = null; UcheckConfig config = null; try { fstream = new FileInputStream(optionfile); config = new UcheckConfig(log); config.load(fstream); fstream.close(); } catch (IOException e) { log.printError(e.getMessage()); } if (config != null) { // all errors should be caught by this point if (log.getErrors() > 0) return; final String mode = config.getMode(); if (mode.equals("inference")) performInference(config, log); if (mode.equals("robust")) performRobustSystemDesign(config, log); if (mode.equals("smoothedmc")) performSmoothedMC(config, log); } if (log.getWarnings() > 0) log.println("\nTotal warnings: " + log.getWarnings()); if (log.getErrors() > 0) { log.println("\nOperation could not be completed due to errors!"); log.println("Total errors: " + log.getErrors()); } } public static void performInference(UcheckConfig config, Log log) { final MitlModelChecker modelChecker = config.getModelChecker(); final boolean[][] observations = config.getObservations(); final LFFOptions lffOptions = config.getLFFOptions(); final lff.Parameter[] params = config.getLFFParameters(); final Prior[] priors = config.getLFFPriors(); LearnFromFormulae lff = new LearnFromFormulae(modelChecker); lff.setParams(params); lff.setPriors(priors); lff.setOptions(lffOptions); GpoResult result = lff.performInference(observations); printInferenceResults(log, config, result); } public static void performRobustSystemDesign(UcheckConfig config, Log log) { final MitlModelChecker modelChecker = config.getModelChecker(); final LFFOptions lffOptions = config.getLFFOptions(); final lff.Parameter[] params = config.getLFFParameters(); LearnFromFormulae lff = new LearnFromFormulae(modelChecker); lff.setParams(params); lff.setOptions(lffOptions); GpoResult result = lff.robustSystemDesign(config.getRobustnessType()); printRobustnessResults(log, config, result); } public static void performSmoothedMC(UcheckConfig config, Log log) { final File outDir = new File(config.getOutputDir()); if (!outDir.exists()) outDir.mkdirs(); if (!outDir.canWrite() || !outDir.isDirectory()) { log.printError("Cannot write into the '" + outDir + "' directory!"); return; } final MitlModelChecker check = config.getModelChecker(); final SmmcOptions options = config.getSmMCOptions(); final smoothedMC.Parameter[] params = config.getSmMCParameters(); final SmoothedModelCheker smmc = new SmoothedModelCheker(); ProbitRegressionPosterior result = null; try { result = smmc.performSmoothedModelChecking(check, params, options); } catch (NonPosDefMatrixException e) { log.printError("Non-positive definite Gram matrix; " + "try increasing 'covarianceCorrection'. " + "The current value has been: " + config.getSmMCOptions().getCovarianceCorrection()); return; } printSmmcResults(log, config, smmc, result); final UcheckPlot plot = new UcheckPlot(); plot.plotSmoothedMC(result, params, 2); } private static void printInferenceResults(Log log, UcheckConfig config, GpoResult result) { final lff.Parameter[] params = config.getLFFParameters(); log.println(); log.println("# Inference from Qualitative Data"); log.println("Model file: " + config.getModelFile()); log.println("MiTL file: " + config.getMitlFile()); log.println(); log.print("Parameters explored: "); log.print(params[0].getName()); for (int i = 1; i < params.length; i++) log.print(", " + params[i].getName()); log.println(); log.println(); log.println(result.toString()); log.println("\n"); } private static void printRobustnessResults(Log log, UcheckConfig config, GpoResult result) { final lff.Parameter[] params = config.getLFFParameters(); log.println(); log.println("# Robust Parameter Synthesis"); switch (config.getRobustnessType()) { case AvgRobustness: log.println("## Average Robustness"); break; case CondAvgRobustnessTrue: log.println("## Conditional Average Robustness given the property is true"); break; case CondAvgRobustnessFalse: log.println("## Conditional Average Robustness given the property is false"); break; } log.println("Model file: " + config.getModelFile()); log.println("MiTL file: " + config.getMitlFile()); log.println(); log.print("Parameters explored: "); log.print(params[0].getName()); for (int i = 1; i < params.length; i++) log.print(", " + params[i].getName()); log.println(); log.println(); log.println(result.toString()); log.println("\n"); } private static void printSmmcResults(Log log, UcheckConfig config, SmoothedModelCheker smmc, ProbitRegressionPosterior result) { final smoothedMC.Parameter[] params = config.getSmMCParameters(); final double smcElapsed = smmc.getStatisticalMCTimeElapsed(); final double hypElapsed = smmc.getHyperparamOptimTimeElapsed(); final double smmcElapsed = smmc.getSmoothedMCTimeElapsed(); final double[] hyperparams = smmc.getHyperparamsUsed(); log.println(); log.println("# Smoothed Model Checking --- Results"); log.println("Model file: " + config.getModelFile()); log.println("MiTL file: " + config.getMitlFile()); log.println(); log.print("Parameters explored: "); log.print(params[0].getName()); for (int i = 1; i < params.length; i++) log.print(", " + params[i].getName()); log.println(); log.println("Hyperparams used: "); log.println(" amplitude: " + hyperparams[0]); for (int i = 1; i < hyperparams.length; i++) log.println(" lengthscale: " + hyperparams[i]); log.println(); log.println("Time for Statistical MC: " + smcElapsed + " sec"); log.println("Time for hyperparam opt: " + hypElapsed + " sec"); log.println("Time for Smoothed MC: " + smmcElapsed + " sec"); log.println(); final String dir = config.getOutputDir(); final String fullname = (new File(config.getModelFile())).getName(); final String name = fullname.substring(0, fullname.lastIndexOf('.')); final String csv = dir + File.separator + name + ".csv"; final String mfile = dir + File.separator + "load_" + name + ".m"; final double beta = 2; final String resultStr = SmmcUtils.results2csv(result, beta); final String matlabStr = produceMatlabScript(params, name); if (writeToFile(csv, resultStr)) log.println("Smoothed MC results have been written to '" + csv + "'"); else log.printError("Could not write to output file '" + csv + "'"); if (writeToFile(mfile, matlabStr)) log.println("A MATLAB/Octave script has been produced in '" + mfile + "'"); else log.printError("Could not write to output file '" + mfile + "'"); log.println("\n"); } static private String produceMatlabScript(smoothedMC.Parameter[] params, String name) { final int dimension = params.length; String str = ""; str += "% ===== This file has been automatically produced by the\n"; str += "% ===== U-check model checking tool for uncertain systems\n"; str += "% \n"; str += "% It loads the Smoothed Model Checking results from '" + name + ".csv'\n"; str += "% Parameters explored: " + params[0].getName(); for (int i = 1; i < params.length; i++) str += ", " + params[i].getName(); str += "\n\n"; str += "if exist('OCTAVE_VERSION', 'builtin')\n"; str += "\tdata = load('" + name + ".csv" + "');\n"; str += "else\n"; str += "\tdata = csvread('" + name + ".csv', 1);\n"; str += "end\n"; str += "\n"; str += "% 'paramValues' " + "is a Nx" + dimension + " matrix (grid of values in the parameter space)\n"; str += "% 'probabilities' " + "contains the estimated satisfaction probabilities\n"; str += "% 'lowerConfBound' " + "Lower confidence bound for the satisfaction probabilities\n"; str += "% 'upperConfBound' " + "Upper confidence bound for the satisfaction probabilities\n"; str += "\n"; str += "paramNames = {" + "'" + params[0].getName() + "'"; for (int i = 1; i < params.length; i++) str += ", '" + params[i].getName() + "'"; str += "};\n"; str += "paramValues = data(:, 1:" + dimension + ");\n"; str += "probabilities = data(:, " + (dimension + 1) + ");\n"; str += "lowerConfBound = data(:, " + (dimension + 2) + ");\n"; str += "upperConfBound = data(:, " + (dimension + 3) + ");\n"; return str; } static final private boolean writeToFile(String file, String contents) { try { FileWriter fw = new FileWriter(file); fw.write(contents); fw.close(); return true; } catch (IOException e) { return false; } } }
gnuplot installation issue
Ucheck/src/ucheck/cli/UcheckCLI.java
gnuplot installation issue
Java
bsd-3-clause
4c7ef8b022d704f119172c7030c3dd933d63c76f
0
arurke/contiki,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,bluerover/6lbr,bluerover/6lbr
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: GUI.java,v 1.148 2009/10/29 10:16:05 fros4943 Exp $ */ package se.sics.cooja; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.Dialog.ModalityType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyVetoException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Properties; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultDesktopManager; import javax.swing.InputMap; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import se.sics.cooja.MoteType.MoteTypeCreationException; import se.sics.cooja.VisPlugin.PluginRequiresVisualizationException; import se.sics.cooja.contikimote.ContikiMoteType; import se.sics.cooja.dialogs.AddMoteDialog; import se.sics.cooja.dialogs.BufferSettings; import se.sics.cooja.dialogs.ConfigurationWizard; import se.sics.cooja.dialogs.CreateSimDialog; import se.sics.cooja.dialogs.ExternalToolsDialog; import se.sics.cooja.dialogs.MessageList; import se.sics.cooja.dialogs.ProjectDirectoriesDialog; import se.sics.cooja.plugins.MoteTypeInformation; import se.sics.cooja.plugins.ScriptRunner; import se.sics.cooja.plugins.SimControl; import se.sics.cooja.plugins.SimInformation; import se.sics.cooja.util.ExecuteJAR; /** * Main file of COOJA Simulator. Typically contains a visualizer for the * simulator, but can also be started without visualizer. * * This class loads external Java classes (in project directories), and handles the * COOJA plugins as well as the configuration system. If provides a number of * help methods for the rest of the COOJA system, and is the starting point for * loading and saving simulation configs. * * @author Fredrik Osterlind */ public class GUI extends Observable { /** * External tools default Win32 settings filename. */ public static final String EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME = "/external_tools_win32.config"; /** * External tools default Mac OS X settings filename. */ public static final String EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME = "/external_tools_macosx.config"; /** * External tools default FreeBSD settings filename. */ public static final String EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME = "/external_tools_freebsd.config"; /** * External tools default Linux/Unix settings filename. */ public static final String EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME = "/external_tools_linux.config"; /** * External tools default Linux/Unix settings filename for 64 bit architectures. * Tested on Intel 64-bit Gentoo Linux. */ public static final String EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME = "/external_tools_linux_64.config"; /** * External tools user settings filename. */ public static final String EXTERNAL_TOOLS_USER_SETTINGS_FILENAME = ".cooja.user.properties"; public static File externalToolsUserSettingsFile; private static boolean externalToolsUserSettingsFileReadOnly = false; private static String specifiedContikiPath = null; /** * Logger settings filename. */ public static final String LOG_CONFIG_FILE = "log4j_config.xml"; /** * Default project configuration filename. */ public static String PROJECT_DEFAULT_CONFIG_FILENAME = null; /** * User project configuration filename. */ public static final String PROJECT_CONFIG_FILENAME = "cooja.config"; /** * File filter only showing saved simulations files (*.csc). */ public static final FileFilter SAVED_SIMULATIONS_FILES = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".csc")) { return true; } return false; } public String getDescription() { return "COOJA Configuration files"; } public String toString() { return ".csc"; } }; private static JFrame frame = null; private static JApplet applet = null; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(GUI.class); // External tools setting names public static Properties defaultExternalToolsSettings; public static Properties currentExternalToolsSettings; private static final String externalToolsSettingNames[] = new String[] { "PATH_CONTIKI", "PATH_COOJA_CORE_RELATIVE", "PATH_MAKE", "PATH_SHELL", "PATH_C_COMPILER", "COMPILER_ARGS", "PATH_LINKER", "LINK_COMMAND_1", "LINK_COMMAND_2", "PATH_AR", "AR_COMMAND_1", "AR_COMMAND_2", "PATH_OBJDUMP", "OBJDUMP_ARGS", "PATH_JAVAC", "CONTIKI_STANDARD_PROCESSES", "CONTIKI_MAIN_TEMPLATE_FILENAME", "CMD_GREP_PROCESSES", "REGEXP_PARSE_PROCESSES", "CMD_GREP_INTERFACES", "REGEXP_PARSE_INTERFACES", "CMD_GREP_SENSORS", "REGEXP_PARSE_SENSORS", "DEFAULT_PROJECTDIRS", "CORECOMM_TEMPLATE_FILENAME", "MAPFILE_DATA_START", "MAPFILE_DATA_SIZE", "MAPFILE_BSS_START", "MAPFILE_BSS_SIZE", "MAPFILE_VAR_NAME", "MAPFILE_VAR_ADDRESS_1", "MAPFILE_VAR_ADDRESS_2", "MAPFILE_VAR_SIZE_1", "MAPFILE_VAR_SIZE_2", "PARSE_WITH_COMMAND", "PARSE_COMMAND", "COMMAND_VAR_NAME_ADDRESS", "COMMAND_DATA_START", "COMMAND_DATA_END", "COMMAND_BSS_START", "COMMAND_BSS_END", }; private static final int FRAME_NEW_OFFSET = 30; private static final int FRAME_STANDARD_WIDTH = 150; private static final int FRAME_STANDARD_HEIGHT = 300; private GUI myGUI; private Simulation mySimulation; protected GUIEventHandler guiEventHandler = new GUIEventHandler(); private JMenu menuPlugins, menuMoteTypeClasses, menuMoteTypes; private JMenu menuOpenSimulation, menuConfOpenSimulation; private boolean hasFileHistoryChanged; private Vector<Class<? extends Plugin>> menuMotePluginClasses; private JDesktopPane myDesktopPane; private Vector<Plugin> startedPlugins = new Vector<Plugin>(); private ArrayList<GUIAction> guiActions = new ArrayList<GUIAction>(); // Platform configuration variables // Maintained via method reparseProjectConfig() private ProjectConfig projectConfig; private Vector<File> currentProjectDirs = new Vector<File>(); private ClassLoader projectDirClassLoader; private Vector<Class<? extends MoteType>> moteTypeClasses = new Vector<Class<? extends MoteType>>(); private Vector<Class<? extends Plugin>> pluginClasses = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends Plugin>> pluginClassesTemporary = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends RadioMedium>> radioMediumClasses = new Vector<Class<? extends RadioMedium>>(); private Vector<Class<? extends IPDistributor>> ipDistributorClasses = new Vector<Class<? extends IPDistributor>>(); private Vector<Class<? extends Positioner>> positionerClasses = new Vector<Class<? extends Positioner>>(); private class HighlightObservable extends Observable { private void setChangedAndNotify(Mote mote) { setChanged(); notifyObservers(mote); } } private HighlightObservable moteHighlightObservable = new HighlightObservable(); private class MoteRelationsObservable extends Observable { private void setChangedAndNotify() { setChanged(); notifyObservers(); } } private MoteRelationsObservable moteRelationObservable = new MoteRelationsObservable(); private JTextPane quickHelpTextPane; private JScrollPane quickHelpScroll; private Properties quickHelpProperties = null; /* quickhelp.txt */ /** * Mote relation (directed). */ public static class MoteRelation { public Mote source; public Mote dest; public MoteRelation(Mote source, Mote dest) { this.source = source; this.dest = dest; } } private ArrayList<MoteRelation> moteRelations = new ArrayList<MoteRelation>(); /** * Creates a new COOJA Simulator GUI. * * @param desktop Desktop pane */ public GUI(JDesktopPane desktop) { myGUI = this; mySimulation = null; myDesktopPane = desktop; if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } /* Help panel */ quickHelpTextPane = new JTextPane(); quickHelpTextPane.setContentType("text/html"); quickHelpTextPane.setEditable(false); quickHelpTextPane.setVisible(false); quickHelpScroll = new JScrollPane(quickHelpTextPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); quickHelpScroll.setPreferredSize(new Dimension(200, 0)); quickHelpScroll.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(0, 3, 0, 0) )); quickHelpScroll.setVisible(false); loadQuickHelp("KEYBOARD_SHORTCUTS"); // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); /* Debugging - Break on repaints outside EDT */ /*RepaintManager.setCurrentManager(new RepaintManager() { public void addDirtyRegion(JComponent comp, int a, int b, int c, int d) { if(!java.awt.EventQueue.isDispatchThread()) { throw new RuntimeException("Repainting outside EDT"); } super.addDirtyRegion(comp, a, b, c, d); } });*/ // Register default project directories String defaultProjectDirs = getExternalToolsSetting("DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null && defaultProjectDirs.length() > 0) { String[] arr = defaultProjectDirs.split(";"); for (String p : arr) { File projectDir = restorePortablePath(new File(p)); currentProjectDirs.add(projectDir); } } /* Parse current project configuration */ try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading projects: " + e.getMessage(), e); if (isVisualized()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Default projects could not load, reconfigure project directories:" + "\n\tMenu->Settings->Manage project directories" + "\n\nSee console for stack trace with more information.", "Project loading error", JOptionPane.ERROR_MESSAGE); } } // Start all standard GUI plugins for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, null, null); } } } /** * Add mote highlight observer. * * @see #deleteMoteHighlightObserver(Observer) * @param newObserver * New observer */ public void addMoteHighlightObserver(Observer newObserver) { moteHighlightObservable.addObserver(newObserver); } /** * Delete mote highlight observer. * * @see #addMoteHighlightObserver(Observer) * @param observer * Observer to delete */ public void deleteMoteHighlightObserver(Observer observer) { moteHighlightObservable.deleteObserver(observer); } /** * @return True if simulator is visualized */ public static boolean isVisualized() { return isVisualizedInFrame() || isVisualizedInApplet(); } public static Container getTopParentContainer() { if (isVisualizedInFrame()) { return frame; } if (isVisualizedInApplet()) { /* Find parent frame for applet */ Container container = applet; while((container = container.getParent()) != null){ if (container instanceof Frame) { return container; } if (container instanceof Dialog) { return container; } if (container instanceof Window) { return container; } } logger.fatal("Returning null top owner container"); } return null; } public static boolean isVisualizedInFrame() { return frame != null; } public static URL getAppletCodeBase() { return applet.getCodeBase(); } public static boolean isVisualizedInApplet() { return applet != null; } /** * Tries to create/remove simulator visualizer. * * @param visualized Visualized */ public void setVisualizedInFrame(boolean visualized) { if (visualized) { if (!isVisualizedInFrame()) { configureFrame(myGUI, false); } } else { if (frame != null) { frame.setVisible(false); frame.dispose(); frame = null; } } } public File getLastOpenedFile() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); return historyArray.length > 0 ? new File(historyArray[0]) : null; } public File[] getFileHistory() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); File[] history = new File[historyArray.length]; for (int i = 0; i < historyArray.length; i++) { history[i] = new File(historyArray[i]); } return history; } public void addToFileHistory(File file) { // Fetch current history String[] history = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); String newFile = file.getAbsolutePath(); if (history.length > 0 && history[0].equals(newFile)) { // File already added return; } // Create new history StringBuilder newHistory = new StringBuilder(); newHistory.append(newFile); for (int i = 0, count = 1; i < history.length && count < 10; i++) { String historyFile = history[i]; if (newFile.equals(historyFile) || historyFile.length() == 0) { // File already added or empty file name } else { newHistory.append(';').append(historyFile); count++; } } setExternalToolsSetting("SIMCFG_HISTORY", newHistory.toString()); saveExternalToolsUserSettings(); hasFileHistoryChanged = true; } private void updateOpenHistoryMenuItems() { if (isVisualizedInApplet()) { return; } if (!hasFileHistoryChanged) { // No need to update menu because file history has not changed return; } hasFileHistoryChanged = false; File[] openFilesHistory = getFileHistory(); updateOpenHistoryMenuItems("confopen", menuConfOpenSimulation, openFilesHistory); updateOpenHistoryMenuItems("open", menuOpenSimulation, openFilesHistory); } private void updateOpenHistoryMenuItems(String type, JMenu menu, File[] openFilesHistory) { menu.removeAll(); JMenuItem browseItem = new JMenuItem("Browse..."); browseItem.setActionCommand(type + " sim"); browseItem.addActionListener(guiEventHandler); menu.add(browseItem); menu.add(new JSeparator()); String command = type + " last sim"; int index = 0; JMenuItem lastItem; for (File file: openFilesHistory) { if (index < 10) { char mnemonic = (char) ('0' + (++index % 10)); lastItem = new JMenuItem(mnemonic + " " + file.getName()); lastItem.setMnemonic(mnemonic); } else { lastItem = new JMenuItem(file.getName()); } lastItem.setActionCommand(command); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); lastItem.addActionListener(guiEventHandler); menu.add(lastItem); } } /** * Enables/disables menues and menu items depending on whether a simulation is loaded etc. */ private void updateGUIComponentState() { if (!isVisualized()) { return; } /* Update action state */ for (GUIAction a: guiActions) { a.setEnabled(a.shouldBeEnabled()); } /* Mote and mote type menues */ if (menuMoteTypeClasses != null) { menuMoteTypeClasses.setEnabled(getSimulation() != null); } if (menuMoteTypes != null) { menuMoteTypes.setEnabled(getSimulation() != null); } } private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu; JMenuItem menuItem; /* Prepare GUI actions */ guiActions.add(newSimulationAction); guiActions.add(closeSimulationAction); guiActions.add(reloadSimulationAction); guiActions.add(reloadRandomSimulationAction); guiActions.add(saveSimulationAction); guiActions.add(closePluginsAction); guiActions.add(exportExecutableJARAction); guiActions.add(exitCoojaAction); guiActions.add(startStopSimulationAction); guiActions.add(removeAllMotesAction); guiActions.add(showBufferSettingsAction); /* File menu */ menu = new JMenu("File"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); updateOpenHistoryMenuItems(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); menu.add(new JMenuItem(newSimulationAction)); menuItem = new JMenu("Reload simulation"); menuItem.add(new JMenuItem(reloadSimulationAction)); menuItem.add(new JMenuItem(reloadRandomSimulationAction)); menu.add(menuItem); menu.add(new JMenuItem(closeSimulationAction)); menuOpenSimulation = new JMenu("Open simulation"); menuOpenSimulation.setMnemonic(KeyEvent.VK_O); menu.add(menuOpenSimulation); if (isVisualizedInApplet()) { menuOpenSimulation.setEnabled(false); menuOpenSimulation.setToolTipText("Not available in applet version"); } menuConfOpenSimulation = new JMenu("Open & Reconfigure simulation"); menuConfOpenSimulation.setMnemonic(KeyEvent.VK_R); menu.add(menuConfOpenSimulation); if (isVisualizedInApplet()) { menuConfOpenSimulation.setEnabled(false); menuConfOpenSimulation.setToolTipText("Not available in applet version"); } hasFileHistoryChanged = true; menu.add(new JMenuItem(saveSimulationAction)); menu.addSeparator(); menu.add(new JMenuItem(closePluginsAction)); menu.add(new JMenuItem(exportExecutableJARAction)); menu.addSeparator(); menu.add(new JMenuItem(exitCoojaAction)); /* Simulation menu */ menu = new JMenu("Simulation"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_S); menuBar.add(menu); menu.add(new JMenuItem(startStopSimulationAction)); GUIAction guiAction = new StartPluginGUIAction("Control panel"); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.putClientProperty("class", SimControl.class); menu.add(menuItem); guiAction = new StartPluginGUIAction("Information"); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_I); menuItem.putClientProperty("class", SimInformation.class); menu.add(menuItem); // Mote type menu menu = new JMenu("Mote Types"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_T); menuBar.add(menu); // Mote type classes sub menu menuMoteTypeClasses = new JMenu("Create mote type"); menuMoteTypeClasses.setMnemonic(KeyEvent.VK_C); menuMoteTypeClasses.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypeClasses.removeAll(); // Recreate menu items JMenuItem menuItem; for (Class<? extends MoteType> moteTypeClass : moteTypeClasses) { /* Sort mote types according to abstraction level */ String abstractionLevelDescription = GUI.getAbstractionLevelDescriptionOf(moteTypeClass); if(abstractionLevelDescription == null) { abstractionLevelDescription = "[unknown cross-level]"; } /* Check if abstraction description already exists */ JSeparator abstractionLevelSeparator = null; for (Component component: menuMoteTypeClasses.getMenuComponents()) { if (component == null || !(component instanceof JSeparator)) { continue; } JSeparator existing = (JSeparator) component; if (abstractionLevelDescription.equals(existing.getToolTipText())) { abstractionLevelSeparator = existing; break; } } if (abstractionLevelSeparator == null) { abstractionLevelSeparator = new JSeparator(); abstractionLevelSeparator.setToolTipText(abstractionLevelDescription); menuMoteTypeClasses.add(abstractionLevelSeparator); } String description = GUI.getDescriptionOf(moteTypeClass); menuItem = new JMenuItem(description); menuItem.setActionCommand("create mote type"); menuItem.putClientProperty("class", moteTypeClass); menuItem.setToolTipText(abstractionLevelDescription); menuItem.addActionListener(guiEventHandler); if (isVisualizedInApplet() && moteTypeClass.equals(ContikiMoteType.class)) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } /* Add new item directly after cross level separator */ for (int i=0; i < menuMoteTypeClasses.getMenuComponentCount(); i++) { if (menuMoteTypeClasses.getMenuComponent(i) == abstractionLevelSeparator) { menuMoteTypeClasses.add(menuItem, i+1); break; } } } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypeClasses); guiAction = new StartPluginGUIAction("Information"); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.putClientProperty("class", MoteTypeInformation.class); menu.add(menuItem); // Mote menu menu = new JMenu("Motes"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_M); menuBar.add(menu); // Mote types sub menu menuMoteTypes = new JMenu("Add motes of type"); menuMoteTypes.setMnemonic(KeyEvent.VK_A); menuMoteTypes.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypes.removeAll(); if (mySimulation == null) { return; } // Recreate menu items JMenuItem menuItem; for (MoteType moteType : mySimulation.getMoteTypes()) { menuItem = new JMenuItem(moteType.getDescription()); menuItem.setActionCommand("add motes"); menuItem.setToolTipText(getDescriptionOf(moteType.getClass())); menuItem.putClientProperty("motetype", moteType); menuItem.addActionListener(guiEventHandler); menuMoteTypes.add(menuItem); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypes); menu.add(new JMenuItem(removeAllMotesAction)); // Plugins menu if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } else { menuPlugins.setText("Plugins"); } menuPlugins.setMnemonic(KeyEvent.VK_P); menuBar.add(menuPlugins); // Settings menu menu = new JMenu("Settings"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menuBar.add(menu); menuItem = new JMenuItem("External tools paths"); menuItem.setActionCommand("edit paths"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Manage project directories"); menuItem.setActionCommand("manage projects"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Compiler configuration wizard"); menuItem.setActionCommand("configuration wizard"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menu.add(new JMenuItem(showBufferSettingsAction)); menu.addSeparator(); menuItem = new JMenuItem("Java version: " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); menuItem.setEnabled(false); menu.add(menuItem); /* Help */ menu = new JMenu("Help"); menu.setMnemonic(KeyEvent.VK_H); menu.add(new JMenuItem(showKeyboardShortcutsAction)); JCheckBoxMenuItem checkBox = new JCheckBoxMenuItem(showQuickHelpAction); showQuickHelpAction.putValue("checkbox", checkBox); menu.add(checkBox); menuBar.add(menu); // Mote plugins popup menu (not available via menu bar) if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } return menuBar; } private static void configureFrame(final GUI gui, boolean createSimDialog) { if (frame == null) { frame = new JFrame("COOJA Simulator"); } frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* Menu bar */ frame.setJMenuBar(gui.createMenuBar()); /* Scrollable desktop */ JComponent desktop = gui.getDesktopPane(); desktop.setOpaque(true); JScrollPane scroll = new JScrollPane(desktop); scroll.setBorder(null); JPanel container = new JPanel(new BorderLayout()); container.add(BorderLayout.CENTER, scroll); container.add(BorderLayout.EAST, gui.quickHelpScroll); frame.setContentPane(container); frame.setSize(700, 700); frame.setLocationRelativeTo(null); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { gui.doQuit(true); } }); frame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { updateDesktopSize(gui.getDesktopPane()); } }); /* Restore frame size and position */ int framePosX = Integer.parseInt(getExternalToolsSetting("FRAME_POS_X", "0")); int framePosY = Integer.parseInt(getExternalToolsSetting("FRAME_POS_Y", "0")); int frameWidth = Integer.parseInt(getExternalToolsSetting("FRAME_WIDTH", "0")); int frameHeight = Integer.parseInt(getExternalToolsSetting("FRAME_HEIGHT", "0")); String frameScreen = getExternalToolsSetting("FRAME_SCREEN", ""); /* Restore position to the same graphics device */ GraphicsDevice device = null; GraphicsDevice all[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (GraphicsDevice gd : all) { if (gd.getIDstring().equals(frameScreen)) { device = gd; } } /* Check if frame should be maximized */ if (device != null) { if (frameWidth == Integer.MAX_VALUE && frameHeight == Integer.MAX_VALUE) { frame.setLocation(device.getDefaultConfiguration().getBounds().getLocation()); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); } else if (frameWidth > 0 && frameHeight > 0) { /* Sanity-check: will Cooja be visible on screen? */ boolean intersects = device.getDefaultConfiguration().getBounds().intersects( new Rectangle(framePosX, framePosY, frameWidth, frameHeight)); if (intersects) { frame.setLocation(framePosX, framePosY); frame.setSize(frameWidth, frameHeight); } } } frame.setVisible(true); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } private static void configureApplet(final GUI gui, boolean createSimDialog) { applet = CoojaApplet.applet; // Add menu bar JMenuBar menuBar = gui.createMenuBar(); applet.setJMenuBar(menuBar); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); applet.setContentPane(newContentPane); applet.setSize(700, 700); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } /** * @return Current desktop pane (simulator visualizer) */ public JDesktopPane getDesktopPane() { return myDesktopPane; } public static void setLookAndFeel() { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); ToolTipManager.sharedInstance().setDismissDelay(60000); /* Nimbus */ try { String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("linux")) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } else { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } return; } catch (Exception e) { } /* System */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); return; } catch (Exception e) { } } private static void updateDesktopSize(final JDesktopPane desktop) { if (desktop == null || !desktop.isVisible() || desktop.getParent() == null) { return; } Rectangle rect = desktop.getVisibleRect(); Dimension pref = new Dimension(rect.width - 1, rect.height - 1); for (JInternalFrame frame : desktop.getAllFrames()) { if (pref.width < frame.getX() + frame.getWidth() - 20) { pref.width = frame.getX() + frame.getWidth(); } if (pref.height < frame.getY() + frame.getHeight() - 20) { pref.height = frame.getY() + frame.getHeight(); } } desktop.setPreferredSize(pref); desktop.revalidate(); } private static JDesktopPane createDesktopPane() { final JDesktopPane desktop = new JDesktopPane() { public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); updateDesktopSize(this); } public void remove(Component c) { super.remove(c); updateDesktopSize(this); } public Component add(Component comp) { Component c = super.add(comp); updateDesktopSize(this); return c; } }; desktop.setDesktopManager(new DefaultDesktopManager() { public void endResizingFrame(JComponent f) { super.endResizingFrame(f); updateDesktopSize(desktop); } public void endDraggingFrame(JComponent f) { super.endDraggingFrame(f); updateDesktopSize(desktop); } }); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); return desktop; } public static Simulation quickStartSimulationConfig(File config, boolean vis) { logger.info("> Starting COOJA"); JDesktopPane desktop = createDesktopPane(); if (vis) { frame = new JFrame("COOJA Simulator"); } GUI gui = new GUI(desktop); if (vis) { configureFrame(gui, false); } if (vis) { gui.doLoadConfig(false, true, config); return gui.getSimulation(); } else { try { Simulation newSim = gui.loadSimulationConfig(config, true); if (newSim == null) { return null; } gui.setSimulation(newSim, false); return newSim; } catch (Exception e) { logger.fatal("Exception when loading simulation: ", e); return null; } } } /** * Allows user to create a simulation with a single mote type. * * @param source Contiki application file name * @return True if simulation was created */ private static boolean quickStartSimulation(String source) { logger.info("> Starting COOJA"); JDesktopPane desktop = createDesktopPane(); frame = new JFrame("COOJA Simulator"); GUI gui = new GUI(desktop); configureFrame(gui, false); logger.info("> Creating simulation"); Simulation simulation = new Simulation(gui); simulation.setTitle("Quickstarted simulation: " + source); boolean simOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), simulation); if (!simOK) { logger.fatal("No simulation, aborting quickstart"); System.exit(1); } gui.setSimulation(simulation, true); logger.info("> Creating mote type"); ContikiMoteType moteType = new ContikiMoteType(); moteType.setContikiSourceFile(new File(source)); moteType.setDescription("Contiki Mote Type (" + source + ")"); try { boolean compileOK = moteType.configureAndInit(GUI.getTopParentContainer(), simulation, true); if (!compileOK) { logger.fatal("Mote type initialization failed, aborting quickstart"); return false; } } catch (MoteTypeCreationException e1) { logger.fatal("Mote type initialization failed, aborting quickstart"); return false; } simulation.addMoteType(moteType); logger.info("> Adding motes"); gui.doAddMotes(moteType); return true; } //// PROJECT CONFIG AND EXTENDABLE PARTS METHODS //// /** * Register new mote type class. * * @param moteTypeClass * Class to register */ public void registerMoteType(Class<? extends MoteType> moteTypeClass) { moteTypeClasses.add(moteTypeClass); } /** * Unregister all mote type classes. */ public void unregisterMoteTypes() { moteTypeClasses.clear(); } /** * @return All registered mote type classes */ public Vector<Class<? extends MoteType>> getRegisteredMoteTypes() { return moteTypeClasses; } /** * Register new IP distributor class * * @param ipDistributorClass * Class to register * @return True if class was registered */ public boolean registerIPDistributor( Class<? extends IPDistributor> ipDistributorClass) { // Check that vector constructor exists try { ipDistributorClass.getConstructor(new Class[] { Vector.class }); } catch (Exception e) { logger.fatal("No vector constructor found of IP distributor: " + ipDistributorClass); return false; } ipDistributorClasses.add(ipDistributorClass); return true; } /** * Unregister all IP distributors. */ public void unregisterIPDistributors() { ipDistributorClasses.clear(); } /** * @return All registered IP distributors */ public Vector<Class<? extends IPDistributor>> getRegisteredIPDistributors() { return ipDistributorClasses; } /** * Register new positioner class. * * @param positionerClass * Class to register * @return True if class was registered */ public boolean registerPositioner(Class<? extends Positioner> positionerClass) { // Check that interval constructor exists try { positionerClass .getConstructor(new Class[] { int.class, double.class, double.class, double.class, double.class, double.class, double.class }); } catch (Exception e) { logger.fatal("No interval constructor found of positioner: " + positionerClass); return false; } positionerClasses.add(positionerClass); return true; } /** * Unregister all positioner classes. */ public void unregisterPositioners() { positionerClasses.clear(); } /** * @return All registered positioner classes */ public Vector<Class<? extends Positioner>> getRegisteredPositioners() { return positionerClasses; } /** * Register new radio medium class. * * @param radioMediumClass * Class to register * @return True if class was registered */ public boolean registerRadioMedium( Class<? extends RadioMedium> radioMediumClass) { // Check that simulation constructor exists try { radioMediumClass.getConstructor(new Class[] { Simulation.class }); } catch (Exception e) { logger.fatal("No simulation constructor found of radio medium: " + radioMediumClass); return false; } radioMediumClasses.add(radioMediumClass); return true; } /** * Unregister all radio medium classes. */ public void unregisterRadioMediums() { radioMediumClasses.clear(); } /** * @return All registered radio medium classes */ public Vector<Class<? extends RadioMedium>> getRegisteredRadioMediums() { return radioMediumClasses; } /** * Builds new project configuration using current project directories settings. * Reregisters mote types, plugins, IP distributors, positioners and radio * mediums. This method may still return true even if all classes could not be * registered, but always returns false if all project directory configuration * files were not parsed correctly. * * Any registered temporary plugins will be saved and reregistered. */ public void reparseProjectConfig() throws ParseProjectsException { if (PROJECT_DEFAULT_CONFIG_FILENAME == null) { if (isVisualizedInApplet()) { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_applet.config"; } else { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_default.config"; } } // Backup temporary plugins Vector<Class<? extends Plugin>> oldTempPlugins = (Vector<Class<? extends Plugin>>) pluginClassesTemporary.clone(); // Reset current configuration unregisterMoteTypes(); unregisterPlugins(); unregisterIPDistributors(); unregisterPositioners(); unregisterRadioMediums(); try { // Read default configuration projectConfig = new ProjectConfig(true); } catch (FileNotFoundException e) { logger.fatal("Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } catch (IOException e) { logger.fatal("Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } if (!isVisualizedInApplet()) { // Append project directory configurations for (File projectDir : currentProjectDirs) { try { // Append config to general config projectConfig.appendProjectDir(projectDir); } catch (FileNotFoundException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when loading project: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when reading project config: " + e.getMessage()).initCause(e); } } // Create class loader try { projectDirClassLoader = createClassLoader(currentProjectDirs); } catch (ClassLoaderCreationException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when creating class loader").initCause(e); } } else { projectDirClassLoader = null; } // Register mote types String[] moteTypeClassNames = projectConfig.getStringArrayValue(GUI.class, "MOTETYPES"); if (moteTypeClassNames != null) { for (String moteTypeClassName : moteTypeClassNames) { Class<? extends MoteType> moteTypeClass = tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass != null) { registerMoteType(moteTypeClass); // logger.info("Loaded mote type class: " + moteTypeClassName); } else { logger.warn("Could not load mote type class: " + moteTypeClassName); } } } // Register plugins registerPlugin(SimControl.class, false); // Not in menu registerPlugin(SimInformation.class, false); // Not in menu registerPlugin(MoteTypeInformation.class, false); // Not in menu String[] pluginClassNames = projectConfig.getStringArrayValue(GUI.class, "PLUGINS"); if (pluginClassNames != null) { for (String pluginClassName : pluginClassNames) { Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass != null) { registerPlugin(pluginClass); // logger.info("Loaded plugin class: " + pluginClassName); } else { logger.warn("Could not load plugin class: " + pluginClassName); } } } // Reregister temporary plugins again if (oldTempPlugins != null) { for (Class<? extends Plugin> pluginClass : oldTempPlugins) { if (registerTemporaryPlugin(pluginClass)) { // logger.info("Reregistered temporary plugin class: " + // getDescriptionOf(pluginClass)); } else { logger.warn("Could not reregister temporary plugin class: " + getDescriptionOf(pluginClass)); } } } // Register IP distributors String[] ipDistClassNames = projectConfig.getStringArrayValue(GUI.class, "IP_DISTRIBUTORS"); if (ipDistClassNames != null) { for (String ipDistClassName : ipDistClassNames) { Class<? extends IPDistributor> ipDistClass = tryLoadClass(this, IPDistributor.class, ipDistClassName); if (ipDistClass != null) { registerIPDistributor(ipDistClass); // logger.info("Loaded IP distributor class: " + ipDistClassName); } else { logger .warn("Could not load IP distributor class: " + ipDistClassName); } } } // Register positioners String[] positionerClassNames = projectConfig.getStringArrayValue( GUI.class, "POSITIONERS"); if (positionerClassNames != null) { for (String positionerClassName : positionerClassNames) { Class<? extends Positioner> positionerClass = tryLoadClass(this, Positioner.class, positionerClassName); if (positionerClass != null) { registerPositioner(positionerClass); // logger.info("Loaded positioner class: " + positionerClassName); } else { logger .warn("Could not load positioner class: " + positionerClassName); } } } // Register radio mediums String[] radioMediumsClassNames = projectConfig.getStringArrayValue( GUI.class, "RADIOMEDIUMS"); if (radioMediumsClassNames != null) { for (String radioMediumClassName : radioMediumsClassNames) { Class<? extends RadioMedium> radioMediumClass = tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { registerRadioMedium(radioMediumClass); // logger.info("Loaded radio medium class: " + radioMediumClassName); } else { logger.warn("Could not load radio medium class: " + radioMediumClassName); } } } } /** * Returns the current project configuration common to the entire simulator. * * @return Current project configuration */ public ProjectConfig getProjectConfig() { return projectConfig; } /** * Returns the current project directories common to the entire simulator. * * @return Current project directories. */ public Vector<File> getProjectDirs() { return currentProjectDirs; } // // PLUGIN METHODS //// /** * Show a started plugin in working area. * * @param plugin Plugin */ public void showPlugin(final Plugin plugin) { new RunnableInEDT<Boolean>() { public Boolean work() { JInternalFrame pluginFrame = plugin.getGUI(); if (pluginFrame == null) { logger.fatal("Failed trying to show plugin without visualizer!"); return false; } int nrFrames = myDesktopPane.getAllFrames().length; myDesktopPane.add(pluginFrame); /* Set size if not already specified by plugin */ if (pluginFrame.getWidth() <= 0 || pluginFrame.getHeight() <= 0) { pluginFrame.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); } /* Set location if not already visible */ if (pluginFrame.getLocation().x <= 0 && pluginFrame.getLocation().y <= 0) { pluginFrame.setLocation( nrFrames * FRAME_NEW_OFFSET, nrFrames * FRAME_NEW_OFFSET); } pluginFrame.setVisible(true); /* Select plugin */ try { for (JInternalFrame existingPlugin : myDesktopPane.getAllFrames()) { existingPlugin.setSelected(false); } pluginFrame.setSelected(true); } catch (Exception e) { } myDesktopPane.moveToFront(pluginFrame); return true; } }.invokeAndWait(); } /** * Close all mote plugins for given mote. * * @param mote Mote */ public void closeMotePlugins(Mote mote) { Vector<Plugin> pluginsToRemove = new Vector<Plugin>(); for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); if (pluginType != PluginType.MOTE_PLUGIN) { continue; } Mote pluginMote = (Mote) startedPlugin.getTag(); if (pluginMote == mote) { pluginsToRemove.add(startedPlugin); } } for (Plugin pluginToRemove: pluginsToRemove) { removePlugin(pluginToRemove, false); } } /** * Remove a plugin from working area. * * @param plugin * Plugin to remove * @param askUser * If plugin is the last one, ask user if we should remove current * simulation also? */ public void removePlugin(final Plugin plugin, final boolean askUser) { new RunnableInEDT<Boolean>() { public Boolean work() { /* Free resources */ plugin.closePlugin(); startedPlugins.remove(plugin); updateGUIComponentState(); /* Dispose visualized components */ if (plugin.getGUI() != null) { plugin.getGUI().dispose(); } /* (OPTIONAL) Remove simulation if all plugins are closed */ if (getSimulation() != null && askUser && startedPlugins.isEmpty()) { doRemoveSimulation(true); } return true; } }.invokeAndWait(); } /** * Same as the {@link #startPlugin(Class, GUI, Simulation, Mote)} method, * but does not throw exceptions. If COOJA is visualised, an error dialog * is shown if plugin could not be started. * * @see #startPlugin(Class, GUI, Simulation, Mote) * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin */ public Plugin tryStartPlugin(final Class<? extends Plugin> pluginClass, final GUI argGUI, final Simulation argSimulation, final Mote argMote) { try { return startPlugin(pluginClass, argGUI, argSimulation, argMote); } catch (PluginConstructionException ex) { if (GUI.isVisualized()) { GUI.showErrorDialog(GUI.getTopParentContainer(), "Error when starting plugin", ex, false); } else { /* If the plugin requires visualization, inform user */ Throwable cause = ex.getCause(); do { if (cause instanceof PluginRequiresVisualizationException) { logger.info("Visualized plugin was not started: " + pluginClass); return null; } } while ((cause=cause.getCause()) != null); logger.fatal("Error when starting plugin", ex); } } return null; } /** * Starts given plugin. If visualized, the plugin is also shown. * * @see PluginType * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin * @throws PluginConstructionException At errors */ public Plugin startPlugin(final Class<? extends Plugin> pluginClass, final GUI argGUI, final Simulation argSimulation, final Mote argMote) throws PluginConstructionException { // Check that plugin class is registered if (!pluginClasses.contains(pluginClass)) { throw new PluginConstructionException("Plugin class not registered: " + pluginClass); } // Construct plugin depending on plugin type int pluginType = pluginClass.getAnnotation(PluginType.class).value(); Plugin plugin; try { if (pluginType == PluginType.MOTE_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for mote plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for mote plugin"); } if (argMote == null) { throw new PluginConstructionException("No mote argument for mote plugin"); } plugin = pluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, GUI.class }) .newInstance(argMote, argSimulation, argGUI); /* Tag plugin with mote */ plugin.tagWithObject(argMote); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for simulation plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for simulation plugin"); } plugin = pluginClass.getConstructor(new Class[] { Simulation.class, GUI.class }) .newInstance(argSimulation, argGUI); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for GUI plugin"); } plugin = pluginClass.getConstructor(new Class[] { GUI.class }) .newInstance(argGUI); } else { throw new PluginConstructionException("Bad plugin type: " + pluginType); } } catch (PluginRequiresVisualizationException e) { PluginConstructionException ex = new PluginConstructionException("Plugin class requires visualization: " + pluginClass.getName()); ex.initCause(e); throw ex; } catch (Exception e) { PluginConstructionException ex = new PluginConstructionException("Construction error for plugin of class: " + pluginClass.getName()); ex.initCause(e); throw ex; } // Add to active plugins list startedPlugins.add(plugin); updateGUIComponentState(); // Show plugin if visualizer type if (plugin.getGUI() != null) { myGUI.showPlugin(plugin); } return plugin; } /** * Register a plugin to be included in the GUI. The plugin will be visible in * the menubar. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerPlugin(Class<? extends Plugin> newPluginClass) { return registerPlugin(newPluginClass, true); } /** * Register a temporary plugin to be included in the GUI. The plugin will be * visible in the menubar. This plugin will automatically be unregistered if * the current simulation is removed. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerTemporaryPlugin(Class<? extends Plugin> newPluginClass) { if (pluginClasses.contains(newPluginClass)) { return false; } boolean returnVal = registerPlugin(newPluginClass, true); if (!returnVal) { return false; } pluginClassesTemporary.add(newPluginClass); return true; } /** * Unregister a plugin class. Removes any plugin menu items links as well. * * @param pluginClass * Plugin class to unregister */ public void unregisterPlugin(Class<? extends Plugin> pluginClass) { // Remove (if existing) plugin class menu items for (Component menuComponent : menuPlugins.getMenuComponents()) { if (menuComponent.getClass().isAssignableFrom(JMenuItem.class)) { JMenuItem menuItem = (JMenuItem) menuComponent; if (menuItem.getClientProperty("class").equals(pluginClass)) { menuPlugins.remove(menuItem); } } } if (menuMotePluginClasses.contains(pluginClass)) { menuMotePluginClasses.remove(pluginClass); } // Remove from plugin vectors (including temporary) if (pluginClasses.contains(pluginClass)) { pluginClasses.remove(pluginClass); } if (pluginClassesTemporary.contains(pluginClass)) { pluginClassesTemporary.remove(pluginClass); } } /** * Register a plugin to be included in the GUI. * * @param newPluginClass * New plugin to register * @param addToMenu * Should this plugin be added to the dedicated plugins menubar? * @return True if this plugin was registered ok, false otherwise */ private boolean registerPlugin(final Class<? extends Plugin> newPluginClass, boolean addToMenu) { // Get description annotation (if any) final String description = getDescriptionOf(newPluginClass); // Get plugin type annotation (required) final int pluginType; if (newPluginClass.isAnnotationPresent(PluginType.class)) { pluginType = newPluginClass.getAnnotation(PluginType.class).value(); } else { pluginType = PluginType.UNDEFINED_PLUGIN; } // Check that plugin type is valid and constructor exists try { if (pluginType == PluginType.MOTE_PLUGIN) { newPluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, GUI.class }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { newPluginClass.getConstructor(new Class[] { Simulation.class, GUI.class }); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { newPluginClass.getConstructor(new Class[] { GUI.class }); } else { logger.fatal("Could not find valid plugin type annotation in class " + newPluginClass); return false; } } catch (NoSuchMethodException e) { logger.fatal("Could not find valid constructor in class " + newPluginClass + ": " + e); return false; } if (addToMenu && menuPlugins != null) { new RunnableInEDT<Boolean>() { public Boolean work() { // Create 'start plugin'-menu item JMenuItem menuItem; String tooltip = "<html>"; /* Sort menu according to plugin type */ int itemIndex=0; if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { for (; itemIndex < menuPlugins.getItemCount(); itemIndex++) { if (menuPlugins.getItem(itemIndex) == null /* separator */) { break; } } tooltip += "COOJA plugin: " + newPluginClass.getName(); menuItem = new JMenuItem(description); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tryStartPlugin(newPluginClass, myGUI, null, null); } }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { for (; itemIndex < menuPlugins.getItemCount(); itemIndex++) { if (menuPlugins.getItem(itemIndex) == null /* separator */) { break; } } itemIndex++; for (; itemIndex < menuPlugins.getItemCount(); itemIndex++) { if (menuPlugins.getItem(itemIndex) == null /* separator */) { break; } } tooltip += "Simulation plugin: " + newPluginClass.getName(); GUIAction guiAction = new StartPluginGUIAction(description); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); } else if (pluginType == PluginType.MOTE_PLUGIN) { // Disable previous menu item and add new item to mote plugins menu menuItem = new JMenuItem(description); menuItem.setEnabled(false); tooltip += "Mote plugin: " + newPluginClass.getName(); tooltip += "<br>Start mote plugins by right-clicking a mote in the simulation visualizer"; menuMotePluginClasses.add(newPluginClass); itemIndex = menuPlugins.getItemCount(); } else { logger.warn("Unknown plugin type: " + pluginType); return false; } /* Check if plugin was imported by a project directory */ File project = getProjectConfig().getUserProjectDefining(GUI.class, "PLUGINS", newPluginClass.getName()); if (project != null) { tooltip += "<br>Loaded by project: " + project.getPath(); } tooltip += "</html>"; menuItem.setToolTipText(tooltip); menuItem.putClientProperty("class", newPluginClass); menuPlugins.add(menuItem, itemIndex); return true; } }.invokeAndWait(); } pluginClasses.add(newPluginClass); return true; } /** * Unregister all plugin classes, including temporary plugins. */ public void unregisterPlugins() { if (menuPlugins != null) { menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } if (menuMotePluginClasses != null) { menuMotePluginClasses.clear(); } pluginClasses.clear(); pluginClassesTemporary.clear(); } /** * Returns started plugin with given class name, if any. * * @param classname Class name * @return Plugin instance */ public Plugin getStartedPlugin(String classname) { for (Plugin p: startedPlugins) { if (p.getClass().getName().equals(classname)) { return p; } } return null; } public Plugin[] getStartedPlugins() { return startedPlugins.toArray(new Plugin[0]); } /** * Return a mote plugins submenu for given mote. * * @param mote Mote * @return Mote plugins menu */ public JMenu createMotePluginsSubmenu(Mote mote) { JMenu menuMotePlugins = new JMenu("Open mote plugin for " + mote); for (Class<? extends Plugin> motePluginClass: menuMotePluginClasses) { GUIAction guiAction = new StartPluginGUIAction(getDescriptionOf(motePluginClass)); JMenuItem menuItem = new JMenuItem(guiAction); menuItem.putClientProperty("class", motePluginClass); menuItem.putClientProperty("mote", mote); menuMotePlugins.add(menuItem); } return menuMotePlugins; } // // GUI CONTROL METHODS //// /** * @return Current simulation */ public Simulation getSimulation() { return mySimulation; } public void setSimulation(Simulation sim, boolean startPlugins) { if (sim != null) { doRemoveSimulation(false); } mySimulation = sim; updateGUIComponentState(); // Set frame title if (frame != null) { frame.setTitle("COOJA Simulator" + " - " + sim.getTitle()); } // Open standard plugins (if none opened already) if (startPlugins) { for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.SIM_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, sim, null); } } } setChanged(); notifyObservers(); } /** * Creates a new mote type of the given mote type class. * * @param moteTypeClass * Mote type class */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass) { if (mySimulation == null) { logger.fatal("Can't create mote type (no simulation)"); return; } // Stop simulation (if running) mySimulation.stopSimulation(); // Create mote type MoteType newMoteType = null; boolean moteTypeOK = false; try { newMoteType = moteTypeClass.newInstance(); moteTypeOK = newMoteType.configureAndInit(GUI.getTopParentContainer(), mySimulation, isVisualized()); } catch (Exception e) { logger.fatal("Exception when creating mote type", e); if (isVisualized()) { showErrorDialog(getTopParentContainer(), "Mote type creation error", e, false); } return; } // Add mote type to simulation if (moteTypeOK) { mySimulation.addMoteType(newMoteType); /* Allow user to immediately add motes */ doAddMotes(newMoteType); } } /** * Remove current simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? * @return True if no simulation exists when method returns */ public boolean doRemoveSimulation(boolean askForConfirmation) { if (mySimulation == null) { return true; } if (askForConfirmation) { boolean ok = new RunnableInEDT<Boolean>() { public Boolean work() { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(GUI.getTopParentContainer(), "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return false; } return true; } }.invokeAndWait(); if (!ok) { return false; } } // Close all started non-GUI plugins for (Object startedPlugin : startedPlugins.toArray()) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { removePlugin((Plugin) startedPlugin, false); } } // Delete simulation mySimulation.deleteObservers(); mySimulation.stopSimulation(); /* Clear current mote relations */ MoteRelation relations[] = getMoteRelations(); for (MoteRelation r: relations) { removeMoteRelation(r.source, r.dest); } mySimulation = null; updateGUIComponentState(); // Unregister temporary plugin classes Class<? extends Plugin>[] pluginClasses = new Class[pluginClassesTemporary.size()]; pluginClassesTemporary.toArray(pluginClasses); for (Class<? extends Plugin> pClass: pluginClasses) { unregisterPlugin(pClass); } // Reset frame title if (isVisualizedInFrame()) { frame.setTitle("COOJA Simulator"); } setChanged(); notifyObservers(); return true; } /** * Load a simulation configuration file from disk * * @param askForConfirmation Ask for confirmation before removing any current simulation * @param quick Quick-load simulation * @param configFile Configuration file to load, if null a dialog will appear */ public void doLoadConfig(boolean askForConfirmation, final boolean quick, File configFile) { if (isVisualizedInApplet()) { return; } /* Remove current simulation */ if (!doRemoveSimulation(true)) { return; } /* Use provided configuration, or open File Chooser */ if (configFile != null && !configFile.isDirectory()) { if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file: " + configFile.getAbsolutePath()); /* File does not exist, open dialog */ doLoadConfig(askForConfirmation, quick, null); return; } } else { final File suggestedFile = configFile; configFile = new RunnableInEDT<File>() { public File work() { JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); if (suggestedFile != null && suggestedFile.isDirectory()) { fc.setCurrentDirectory(suggestedFile); } else { /* Suggest file using file history */ File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } } int returnVal = fc.showOpenDialog(GUI.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { logger.info("Load command cancelled by user..."); return null; } File file = fc.getSelectedFile(); if (!file.exists()) { /* Try default file extension */ file = new File(file.getParent(), file.getName() + SAVED_SIMULATIONS_FILES); } if (!file.exists() || !file.canRead()) { logger.fatal("No read access to file"); return null; } return file; } }.invokeAndWait(); if (configFile == null) { return; } } final JDialog progressDialog; final String progressTitle = configFile == null ? "Loading" : ("Loading " + configFile.getAbsolutePath()); if (quick) { final Thread loadThread = Thread.currentThread(); progressDialog = new RunnableInEDT<JDialog>() { public JDialog work() { final JDialog progressDialog; if (GUI.getTopParentContainer() instanceof Window) { progressDialog = new JDialog((Window) GUI.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); } else if (GUI.getTopParentContainer() instanceof Frame) { progressDialog = new JDialog((Frame) GUI.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); } else if (GUI.getTopParentContainer() instanceof Dialog) { progressDialog = new JDialog((Dialog) GUI.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); } else { logger.warn("No parent container"); progressDialog = new JDialog((Frame) null, progressTitle, ModalityType.APPLICATION_MODAL); } JPanel progressPanel = new JPanel(new BorderLayout()); JProgressBar progressBar; JButton button; progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(GUI.getTopParentContainer()); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { progressDialog.setVisible(true); } }); return progressDialog; } }.invokeAndWait(); } else { progressDialog = null; } // Load simulation in this thread, while showing progress monitor final File fileToLoad = configFile; Simulation newSim = null; boolean shouldRetry = false; do { try { shouldRetry = false; myGUI.doRemoveSimulation(false); newSim = loadSimulationConfig(fileToLoad, quick); myGUI.setSimulation(newSim, false); addToFileHistory(fileToLoad); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(GUI.getTopParentContainer(), "Simulation load error", e, true); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(GUI.getTopParentContainer(), "Simulation load error", e, true); } } while (shouldRetry); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } return; } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * * @param autoStart Start executing simulation when loaded * @param newSeed Change simulation seed */ public void reloadCurrentSimulation(final boolean autoStart, final long randomSeed) { if (getSimulation() == null) { logger.fatal("No simulation to reload"); return; } final JDialog progressDialog = new JDialog(frame, "Reloading", true); final Thread loadThread = new Thread(new Runnable() { public void run() { /* Get current simulation configuration */ Element root = new Element("simconf"); Element simulationElement = new Element("simulation"); simulationElement.addContent(getSimulation().getConfigXML()); root.addContent(simulationElement); Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } /* Remove current simulation, and load config */ boolean shouldRetry = false; do { try { shouldRetry = false; myGUI.doRemoveSimulation(false); Simulation newSim = loadSimulationConfig(root, true, new Long(randomSeed)); myGUI.setSimulation(newSim, false); if (autoStart) { newSim.startSimulation(); } } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } } while (shouldRetry); if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); // Display progress dialog while reloading JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ JButton button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); progressDialog.setVisible(true); } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * The same random seed is used. * * @see #reloadCurrentSimulation(boolean, boolean) * @param autoStart Start executing simulation when loaded */ public void reloadCurrentSimulation(boolean autoStart) { reloadCurrentSimulation(autoStart, getSimulation().getRandomSeed()); } /** * Save current simulation configuration to disk * * @param askForConfirmation * Ask for confirmation before overwriting file */ public File doSaveConfig(boolean askForConfirmation) { if (isVisualizedInApplet()) { return null; } if (mySimulation == null) { return null; } mySimulation.stopSimulation(); JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); // Suggest file using history File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = fc.getSelectedFile(); if (!fc.accept(saveFile)) { saveFile = new File(saveFile.getParent(), saveFile.getName() + SAVED_SIMULATIONS_FILES); } if (saveFile.exists()) { if (askForConfirmation) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( GUI.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return null; } } } if (!saveFile.exists() || saveFile.canWrite()) { saveSimulationConfig(saveFile); addToFileHistory(saveFile); return saveFile; } else { logger.fatal("No write access to file"); } } else { logger.info("Save command cancelled by user..."); } return null; } /** * Add new mote to current simulation */ public void doAddMotes(MoteType moteType) { if (mySimulation != null) { mySimulation.stopSimulation(); Vector<Mote> newMotes = AddMoteDialog.showDialog(getTopParentContainer(), mySimulation, moteType); if (newMotes != null) { for (Mote newMote : newMotes) { mySimulation.addMote(newMote); } } } else { logger.warn("No simulation active"); } } /** * Create a new simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doCreateSimulation(boolean askForConfirmation) { /* Remove current simulation */ if (!doRemoveSimulation(askForConfirmation)) { return; } // Create new simulation Simulation newSim = new Simulation(this); boolean createdOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), newSim); if (createdOK) { myGUI.setSimulation(newSim, true); } } /** * Quit program * * @param askForConfirmation * Should we ask for confirmation before quitting? */ public void doQuit(boolean askForConfirmation) { if (isVisualizedInApplet()) { return; } if (askForConfirmation) { String s1 = "Quit"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(GUI.getTopParentContainer(), "Sure you want to quit?", "Close COOJA Simulator", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Clean up resources Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } /* Store frame size and position */ if (isVisualizedInFrame()) { setExternalToolsSetting("FRAME_SCREEN", frame.getGraphicsConfiguration().getDevice().getIDstring()); setExternalToolsSetting("FRAME_POS_X", "" + frame.getLocationOnScreen().x); setExternalToolsSetting("FRAME_POS_Y", "" + frame.getLocationOnScreen().y); if (frame.getExtendedState() == JFrame.MAXIMIZED_BOTH) { setExternalToolsSetting("FRAME_WIDTH", "" + Integer.MAX_VALUE); setExternalToolsSetting("FRAME_HEIGHT", "" + Integer.MAX_VALUE); } else { setExternalToolsSetting("FRAME_WIDTH", "" + frame.getWidth()); setExternalToolsSetting("FRAME_HEIGHT", "" + frame.getHeight()); } } saveExternalToolsUserSettings(); System.exit(0); } // // EXTERNAL TOOLS SETTINGS METHODS //// /** * @return Number of external tools settings */ public static int getExternalToolsSettingsCount() { return externalToolsSettingNames.length; } /** * Get name of external tools setting at given index. * * @param index * Setting index * @return Name */ public static String getExternalToolsSettingName(int index) { return externalToolsSettingNames[index]; } /** * @param name * Name of setting * @return Value */ public static String getExternalToolsSetting(String name) { return currentExternalToolsSettings.getProperty(name); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsSetting(String name, String defaultValue) { if (specifiedContikiPath != null && "PATH_CONTIKI".equals(name)) { return specifiedContikiPath; } return currentExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsDefaultSetting(String name, String defaultValue) { return defaultExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param newVal * New value */ public static void setExternalToolsSetting(String name, String newVal) { if (specifiedContikiPath != null && "PATH_CONTIKI".equals(name)) { specifiedContikiPath = newVal; } else { currentExternalToolsSettings.setProperty(name, newVal); } } /** * Load external tools settings from default file. */ public static void loadExternalToolsDefaultSettings() { String osName = System.getProperty("os.name").toLowerCase(); String osArch = System.getProperty("os.arch").toLowerCase(); String filename = null; if (osName.startsWith("win")) { filename = GUI.EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME; } else if (osName.startsWith("mac os x")) { filename = GUI.EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME; } else if (osName.startsWith("freebsd")) { filename = GUI.EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME; } else if (osName.startsWith("linux")) { filename = GUI.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; if (osArch.startsWith("amd64")) { filename = GUI.EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME; } } else { logger.warn("Unknown system: " + osName); logger.warn("Using default linux external tools configuration"); filename = GUI.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; } logger.info("Loading external tools user settings from: " + filename); try { InputStream in = GUI.class.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " not found"); } Properties settings = new Properties(); settings.load(in); in.close(); currentExternalToolsSettings = settings; defaultExternalToolsSettings = (Properties) currentExternalToolsSettings.clone(); } catch (IOException e) { // Error while importing default properties logger.warn( "Error when reading external tools settings from " + filename, e); } finally { if (currentExternalToolsSettings == null) { defaultExternalToolsSettings = new Properties(); currentExternalToolsSettings = new Properties(); } } } /** * Load user values from external properties file */ public static void loadExternalToolsUserSettings() { if (externalToolsUserSettingsFile == null) { return; } try { FileInputStream in = new FileInputStream(externalToolsUserSettingsFile); Properties settings = new Properties(); settings.load(in); in.close(); Enumeration en = settings.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); setExternalToolsSetting(key, settings.getProperty(key)); } } catch (FileNotFoundException e) { // No default configuration file found, using default } catch (IOException e) { // Error while importing saved properties, using default logger.warn("Error when reading default settings from " + externalToolsUserSettingsFile); } } /** * Save external tools user settings to file. */ public static void saveExternalToolsUserSettings() { if (isVisualizedInApplet()) { return; } if (externalToolsUserSettingsFileReadOnly) { return; } try { FileOutputStream out = new FileOutputStream(externalToolsUserSettingsFile); Properties differingSettings = new Properties(); Enumeration keyEnum = currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = getExternalToolsDefaultSetting(key, ""); String currentSetting = currentExternalToolsSettings.getProperty(key, ""); if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "COOJA External Tools (User specific)"); out.close(); } catch (FileNotFoundException ex) { // Could not open settings file for writing, aborting logger.warn("Could not save external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } catch (IOException ex) { // Could not open settings file for writing, aborting logger.warn("Error while saving external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } } // // GUI EVENT HANDLER //// private class GUIEventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("confopen sim")) { new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, false, null); } }).start(); } else if (e.getActionCommand().equals("confopen last sim")) { final File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, false, file); } }).start(); } else if (e.getActionCommand().equals("open sim")) { new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, true, null); } }).start(); } else if (e.getActionCommand().equals("open last sim")) { final File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, true, file); } }).start(); } else if (e.getActionCommand().equals("create mote type")) { myGUI.doCreateMoteType((Class<? extends MoteType>) ((JMenuItem) e .getSource()).getClientProperty("class")); } else if (e.getActionCommand().equals("add motes")) { myGUI.doAddMotes((MoteType) ((JMenuItem) e.getSource()) .getClientProperty("motetype")); } else if (e.getActionCommand().equals("edit paths")) { ExternalToolsDialog.showDialog(GUI.getTopParentContainer()); } else if (e.getActionCommand().equals("manage projects")) { File[] newProjects = ProjectDirectoriesDialog.showDialog( GUI.getTopParentContainer(), GUI.this, currentProjectDirs.toArray(new File[0]) ); if (newProjects != null) { currentProjectDirs.clear(); for (File p: newProjects) { currentProjectDirs.add(p); } try { reparseProjectConfig(); } catch (ParseProjectsException ex) { logger.fatal("Error when loading projects: " + ex.getMessage(), ex); if (isVisualized()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Configured projects could not load, reconfigure project directories:" + "\n\tMenu->Settings->Manage project directories" + "\n\nSee console for stack trace with more information.", "Project loading error", JOptionPane.ERROR_MESSAGE); } } } } else if (e.getActionCommand().equals("configuration wizard")) { ConfigurationWizard.startWizard(GUI.getTopParentContainer(), GUI.this); } else { logger.warn("Unhandled action: " + e.getActionCommand()); } } } // // VARIOUS HELP METHODS //// /** * Help method that tries to load and initialize a class with given name. * * @param <N> * Class extending given class type * @param classType * Class type * @param className * Class name * @return Class extending given class type or null if not found */ public <N extends Object> Class<? extends N> tryLoadClass( Object callingObject, Class<N> classType, String className) { if (callingObject != null) { try { return callingObject.getClass().getClassLoader().loadClass(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } try { return Class.forName(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } if (!isVisualizedInApplet()) { try { if (projectDirClassLoader != null) { return projectDirClassLoader.loadClass(className).asSubclass( classType); } } catch (NoClassDefFoundError e) { } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } return null; } public ClassLoader createProjectDirClassLoader(Vector<File> projectsDirs) throws ParseProjectsException, ClassLoaderCreationException { if (projectDirClassLoader == null) { reparseProjectConfig(); } return createClassLoader(projectDirClassLoader, projectsDirs); } private ClassLoader createClassLoader(Vector<File> currentProjectDirs) throws ClassLoaderCreationException { return createClassLoader(ClassLoader.getSystemClassLoader(), currentProjectDirs); } private File findJarFile(File projectDir, String jarfile) { File fp = new File(jarfile); if (!fp.exists()) { fp = new File(projectDir, jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/lib/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "lib/" + jarfile); } return fp.exists() ? fp : null; } private ClassLoader createClassLoader(ClassLoader parent, Vector<File> projectDirs) throws ClassLoaderCreationException { if (projectDirs == null || projectDirs.isEmpty()) { return parent; } // Combine class loader from all project directories (including any // specified JAR files) ArrayList<URL> urls = new ArrayList<URL>(); for (int j = projectDirs.size() - 1; j >= 0; j--) { File projectDir = projectDirs.get(j); try { urls.add((new File(projectDir, "java")).toURI().toURL()); // Read configuration to check if any JAR files should be loaded ProjectConfig projectConfig = new ProjectConfig(false); projectConfig.appendProjectDir(projectDir); String[] projectJarFiles = projectConfig.getStringArrayValue( GUI.class, "JARFILES"); if (projectJarFiles != null && projectJarFiles.length > 0) { for (String jarfile : projectJarFiles) { File jarpath = findJarFile(projectDir, jarfile); if (jarpath == null) { throw new FileNotFoundException(jarfile); } urls.add(jarpath.toURI().toURL()); } } } catch (Exception e) { logger.fatal("Error when trying to read JAR-file in " + projectDir + ": " + e); throw (ClassLoaderCreationException) new ClassLoaderCreationException( "Error when trying to read JAR-file in " + projectDir).initCause(e); } } URL[] urlsArray = urls.toArray(new URL[urls.size()]); /* TODO Load from webserver if applet */ return new URLClassLoader(urlsArray, parent); } /** * Help method that returns the description for given object. This method * reads from the object's class annotations if existing. Otherwise it returns * the simple class name of object's class. * * @param object * Object * @return Description */ public static String getDescriptionOf(Object object) { return getDescriptionOf(object.getClass()); } /** * Help method that returns the description for given class. This method reads * from class annotations if existing. Otherwise it returns the simple class * name. * * @param clazz * Class * @return Description */ public static String getDescriptionOf(Class<? extends Object> clazz) { if (clazz.isAnnotationPresent(ClassDescription.class)) { return clazz.getAnnotation(ClassDescription.class).value(); } return clazz.getSimpleName(); } /** * Help method that returns the abstraction level description for given mote type class. * * @param clazz * Class * @return Description */ public static String getAbstractionLevelDescriptionOf(Class<? extends MoteType> clazz) { if (clazz.isAnnotationPresent(AbstractionLevelDescription.class)) { return clazz.getAnnotation(AbstractionLevelDescription.class).value(); } return null; } /** * Load configurations and create a GUI. * * @param args * null */ public static void main(String[] args) { try { // Configure logger if ((new File(LOG_CONFIG_FILE)).exists()) { DOMConfigurator.configure(LOG_CONFIG_FILE); } else { // Used when starting from jar DOMConfigurator.configure(GUI.class.getResource("/" + LOG_CONFIG_FILE)); } externalToolsUserSettingsFile = new File(System.getProperty("user.home"), EXTERNAL_TOOLS_USER_SETTINGS_FILENAME); } catch (AccessControlException e) { BasicConfigurator.configure(); externalToolsUserSettingsFile = null; } /* Look and Feel: Nimbus */ setLookAndFeel(); // Parse general command arguments for (String element : args) { if (element.startsWith("-contiki=")) { String arg = element.substring("-contiki=".length()); GUI.specifiedContikiPath = arg; } if (element.startsWith("-external_tools_config=")) { String arg = element.substring("-external_tools_config=".length()); File specifiedExternalToolsConfigFile = new File(arg); if (!specifiedExternalToolsConfigFile.exists()) { logger.fatal("Specified external tools configuration not found: " + specifiedExternalToolsConfigFile); specifiedExternalToolsConfigFile = null; System.exit(1); } else { GUI.externalToolsUserSettingsFile = specifiedExternalToolsConfigFile; GUI.externalToolsUserSettingsFileReadOnly = true; } } } // Check if simulator should be quick-started if (args.length > 0 && args[0].startsWith("-quickstart=")) { String contikiApp = args[0].substring("-quickstart=".length()); /* Cygwin fix */ if (contikiApp.startsWith("/cygdrive/")) { char driveCharacter = contikiApp.charAt("/cygdrive/".length()); contikiApp = contikiApp.replace("/cygdrive/" + driveCharacter + "/", driveCharacter + ":/"); } boolean ok = false; if (contikiApp.endsWith(".csc")) { ok = quickStartSimulationConfig(new File(contikiApp), true) != null; } else { if (contikiApp.endsWith(".cooja")) { contikiApp = contikiApp.substring(0, contikiApp.length() - ".cooja".length()); } if (!contikiApp.endsWith(".c")) { contikiApp += ".c"; } ok = quickStartSimulation(contikiApp); } if (!ok) { System.exit(1); } } else if (args.length > 0 && args[0].startsWith("-nogui=")) { /* Load simulation */ String config = args[0].substring("-nogui=".length()); File configFile = new File(config); Simulation sim = quickStartSimulationConfig(configFile, false); if (sim == null) { System.exit(1); } GUI gui = sim.getGUI(); /* Make sure at least one test editor is controlling the simulation */ boolean hasEditor = false; for (Plugin startedPlugin : gui.startedPlugins) { if (startedPlugin instanceof ScriptRunner) { hasEditor = true; break; } } /* Backwards compatibility: * simulation has no test editor, but has external (old style) test script. * We will manually start a test editor from here. */ if (!hasEditor) { File scriptFile = new File(config.substring(0, config.length()-4) + ".js"); if (scriptFile.exists()) { logger.info("Detected old simulation test, starting test editor manually from: " + scriptFile); ScriptRunner plugin = (ScriptRunner) gui.tryStartPlugin(ScriptRunner.class, gui, sim, null); if (plugin == null) { System.exit(1); } plugin.updateScript(scriptFile); plugin.setScriptActive(true); sim.setDelayTime(0); sim.startSimulation(); } else { logger.fatal("No test editor controlling simulation, aborting"); System.exit(1); } } } else if (args.length > 0 && args[0].startsWith("-applet")) { String tmpWebPath=null, tmpBuildPath=null, tmpEsbFirmware=null, tmpSkyFirmware=null; for (int i = 1; i < args.length; i++) { if (args[i].startsWith("-web=")) { tmpWebPath = args[i].substring("-web=".length()); } else if (args[i].startsWith("-sky_firmware=")) { tmpSkyFirmware = args[i].substring("-sky_firmware=".length()); } else if (args[i].startsWith("-esb_firmware=")) { tmpEsbFirmware = args[i].substring("-esb_firmware=".length()); } else if (args[i].startsWith("-build=")) { tmpBuildPath = args[i].substring("-build=".length()); } } // Applet start-up final String webPath = tmpWebPath, buildPath = tmpBuildPath; final String skyFirmware = tmpSkyFirmware, esbFirmware = tmpEsbFirmware; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); applet = CoojaApplet.applet; GUI gui = new GUI(desktop); GUI.setExternalToolsSetting("PATH_CONTIKI_BUILD", buildPath); GUI.setExternalToolsSetting("PATH_CONTIKI_WEB", webPath); GUI.setExternalToolsSetting("SKY_FIRMWARE", skyFirmware); GUI.setExternalToolsSetting("ESB_FIRMWARE", esbFirmware); configureApplet(gui, false); } }); } else { // Frame start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); frame = new JFrame("COOJA Simulator"); GUI gui = new GUI(desktop); configureFrame(gui, false); } }); } } /** * Loads a simulation configuration from given file. * * When loading Contiki mote types, the libraries must be recompiled. User may * change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public Simulation loadSimulationConfig(File file, boolean quick) throws UnsatisfiedLinkError, SimulationCreationException { this.currentConfigFile = file; /* Used to generate config relative paths */ try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(file); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick, null); } catch (JDOMException e) { logger.fatal("Config not wellformed: " + e.getMessage()); return null; } catch (IOException e) { logger.fatal("Load simulation error: " + e.getMessage()); return null; } } private Simulation loadSimulationConfig(StringReader stringReader, boolean quick) throws SimulationCreationException { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(stringReader); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick, null); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "IO Exception: " + e.getMessage()).initCause(e); } } private Simulation loadSimulationConfig(Element root, boolean quick, Long manualRandomSeed) throws SimulationCreationException { Simulation newSim = null; try { // Check that config file version is correct if (!root.getName().equals("simconf")) { logger.fatal("Not a valid COOJA simulation config!"); return null; } /* Verify project directories */ boolean projectsOk = verifyProjects(root.getChildren(), !quick); /* GENERATE UNIQUE MOTE TYPE IDENTIFIERS */ root.detach(); String configString = new XMLOutputter().outputString(new Document(root)); /* Locate Contiki mote types in config */ Properties moteTypeIDMappings = new Properties(); String identifierExtraction = ContikiMoteType.class.getName() + "[\\s\\n]*<identifier>([^<]*)</identifier>"; Matcher matcher = Pattern.compile(identifierExtraction).matcher(configString); while (matcher.find()) { moteTypeIDMappings.setProperty(matcher.group(1), ""); } /* Create old to new identifier mappings */ Enumeration<Object> existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); MoteType[] existingMoteTypes = null; if (mySimulation != null) { existingMoteTypes = mySimulation.getMoteTypes(); } ArrayList<Object> reserved = new ArrayList<Object>(); reserved.addAll(moteTypeIDMappings.keySet()); reserved.addAll(moteTypeIDMappings.values()); String newID = ContikiMoteType.generateUniqueMoteTypeID(existingMoteTypes, reserved); moteTypeIDMappings.setProperty(existingIdentifier, newID); } /* Create new config */ existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); configString = configString.replaceAll( "<identifier>" + existingIdentifier + "</identifier>", "<identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</identifier>"); configString = configString.replaceAll( "<motetype_identifier>" + existingIdentifier + "</motetype_identifier>", "<motetype_identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</motetype_identifier>"); } /* Replace existing config */ root = new SAXBuilder().build(new StringReader(configString)).getRootElement(); // Create new simulation from config for (Object element : root.getChildren()) { if (((Element) element).getName().equals("simulation")) { Collection<Element> config = ((Element) element).getChildren(); newSim = new Simulation(this); System.gc(); boolean createdOK = newSim.setConfigXML(config, !quick, manualRandomSeed); if (!createdOK) { logger.info("Simulation not loaded"); return null; } } } // Restart plugins from config setPluginsConfigXML(root.getChildren(), newSim, !quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "No access to configuration file: " + e.getMessage()).initCause(e); } catch (MoteTypeCreationException e) { throw (SimulationCreationException) new SimulationCreationException( "Mote type creation error: " + e.getMessage()).initCause(e); } catch (Exception e) { throw (SimulationCreationException) new SimulationCreationException( "Unknown error: " + e.getMessage()).initCause(e); } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File, boolean) * @param file * File to write */ public void saveSimulationConfig(File file) { this.currentConfigFile = file; /* Used to generate config relative paths */ try { // Create and write to document Document doc = new Document(extractSimulationConfig()); FileOutputStream out = new FileOutputStream(file); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); e.printStackTrace(); } } public Element extractSimulationConfig() { // Create simulation config Element root = new Element("simconf"); /* Store project directories meta data */ for (File project: currentProjectDirs) { Element projectElement = new Element("project"); projectElement.addContent(createPortablePath(project).getPath().replaceAll("\\\\", "/")); root.addContent(projectElement); } Element simulationElement = new Element("simulation"); simulationElement.addContent(mySimulation.getConfigXML()); root.addContent(simulationElement); // Create started plugins config Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } return root; } /** * Returns started plugins config. * * @return Config or null */ public Collection<Element> getPluginsConfigXML() { Vector<Element> config = new Vector<Element>(); // Loop through all started plugins // (Only return config of non-GUI plugins) Element pluginElement, pluginSubElement; for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); // Ignore GUI plugins if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { continue; } pluginElement = new Element("plugin"); pluginElement.setText(startedPlugin.getClass().getName()); // Create mote argument config (if mote plugin) if (pluginType == PluginType.MOTE_PLUGIN && startedPlugin.getTag() != null) { pluginSubElement = new Element("mote_arg"); Mote taggedMote = (Mote) startedPlugin.getTag(); for (int moteNr = 0; moteNr < mySimulation.getMotesCount(); moteNr++) { if (mySimulation.getMote(moteNr) == taggedMote) { pluginSubElement.setText(Integer.toString(moteNr)); pluginElement.addContent(pluginSubElement); break; } } } // Create plugin specific configuration Collection<Element> pluginXML = startedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("plugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } // If plugin is visualizer plugin, create visualization arguments if (startedPlugin.getGUI() != null) { JInternalFrame pluginFrame = startedPlugin.getGUI(); pluginSubElement = new Element("width"); pluginSubElement.setText("" + pluginFrame.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + getDesktopPane().getComponentZOrder(pluginFrame)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + pluginFrame.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + pluginFrame.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + pluginFrame.getLocation().y); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("minimized"); pluginSubElement.setText(new Boolean(pluginFrame.isIcon()).toString()); pluginElement.addContent(pluginSubElement); } config.add(pluginElement); } return config; } public boolean verifyProjects(Collection<Element> configXML, boolean visAvailable) { boolean allOk = true; /* Match current projects against projects in simulation config */ for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("project")) { File projectFile = restorePortablePath(new File(pluginElement.getText())); try { projectFile = projectFile.getCanonicalFile(); } catch (IOException e) { } boolean found = false; for (File currentProject: currentProjectDirs) { if (projectFile.getPath().replaceAll("\\\\", "/"). equals(currentProject.getPath().replaceAll("\\\\", "/"))) { found = true; break; } } if (!found) { logger.warn("Loaded simulation may depend on not found project: '" + projectFile + "'"); allOk = false; } } } return allOk; } /** * Starts plugins with arguments in given config. * * @param configXML * Config XML elements * @param simulation * Simulation on which to start plugins * @return True if all plugins started, false otherwise */ public boolean setPluginsConfigXML(Collection<Element> configXML, Simulation simulation, boolean visAvailable) { for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("plugin")) { // Read plugin class String pluginClassName = pluginElement.getText().trim(); /* Backwards compatibility: old visualizers were replaced */ if (pluginClassName.equals("se.sics.cooja.plugins.VisUDGM") || pluginClassName.equals("se.sics.cooja.plugins.VisBattery") || pluginClassName.equals("se.sics.cooja.plugins.VisTraffic") || pluginClassName.equals("se.sics.cooja.plugins.VisState") || pluginClassName.equals("se.sics.cooja.plugins.VisUDGM")) { logger.warn("Old simulation config detected: visualizers have been remade"); pluginClassName = "se.sics.cooja.plugins.Visualizer"; } Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass == null) { logger.fatal("Could not load plugin class: " + pluginClassName); return false; } // Parse plugin mote argument (if any) Mote mote = null; for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("mote_arg")) { int moteNr = Integer.parseInt(pluginSubElement.getText()); if (moteNr >= 0 && moteNr < simulation.getMotesCount()) { mote = simulation.getMote(moteNr); } } } /* Start plugin */ final Plugin startedPlugin = tryStartPlugin(pluginClass, this, simulation, mote); if (startedPlugin == null) { continue; } /* Apply plugin specific configuration */ for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("plugin_config")) { startedPlugin.setConfigXML(pluginSubElement.getChildren(), visAvailable); } } /* If Cooja not visualized, ignore window configuration */ if (startedPlugin.getGUI() == null) { continue; } // If plugin is visualizer plugin, parse visualization arguments new RunnableInEDT<Boolean>() { public Boolean work() { Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("width")) { size.width = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); // Save z order as temporary client property startedPlugin.getGUI().putClientProperty("zorder", zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { try { startedPlugin.getGUI().setIcon(Boolean.parseBoolean(pluginSubElement.getText())); } catch (PropertyVetoException e) { } } } // For all visualized plugins, check if they have a zorder property try { for (JInternalFrame plugin : getDesktopPane().getAllFrames()) { if (plugin.getClientProperty("zorder") != null) { getDesktopPane().setComponentZOrder(plugin, ((Integer) plugin.getClientProperty("zorder")).intValue()); plugin.putClientProperty("zorder", null); } } } catch (Exception e) { } return true; } }.invokeAndWait(); } } return true; } public class ParseProjectsException extends Exception { public ParseProjectsException(String message) { super(message); } } public class ClassLoaderCreationException extends Exception { public ClassLoaderCreationException(String message) { super(message); } } public class SimulationCreationException extends Exception { public SimulationCreationException(String message) { super(message); } } public class PluginConstructionException extends Exception { public PluginConstructionException(String message) { super(message); } } /** * A simple error dialog with compilation output and stack trace. * * @param parentComponent * Parent component * @param title * Title of error window * @param exception * Exception causing window to be shown * @param retryAvailable * If true, a retry option is presented * @return Retry failed operation */ public static boolean showErrorDialog(final Component parentComponent, final String title, final Throwable exception, final boolean retryAvailable) { return new RunnableInEDT<Boolean>() { public Boolean work() { JTabbedPane tabbedPane = new JTabbedPane(); final JDialog errorDialog; if (parentComponent instanceof Dialog) { errorDialog = new JDialog((Dialog) parentComponent, title, true); } else if (parentComponent instanceof Frame) { errorDialog = new JDialog((Frame) parentComponent, title, true); } else { errorDialog = new JDialog((Frame) null, title); } Box buttonBox = Box.createHorizontalBox(); if (exception != null) { /* Compilation output */ MessageList compilationOutput = null; if (exception instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception).getCompilationOutput(); } else if (exception.getCause() != null && exception.getCause() instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception.getCause()).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception.getCause()).getCompilationOutput(); } if (compilationOutput != null) { compilationOutput.addPopupMenuItem(null, true); tabbedPane.addTab("Compilation output", null, new JScrollPane(compilationOutput), null); } /* Stack trace */ MessageList stackTrace = new MessageList(); PrintStream printStream = stackTrace.getInputStream(MessageList.NORMAL); exception.printStackTrace(printStream); stackTrace.addPopupMenuItem(null, true); tabbedPane.addTab("Java stack trace", null, new JScrollPane(stackTrace), null); /* Exception message */ buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(new JLabel(exception.getMessage())); buttonBox.add(Box.createHorizontalStrut(10)); } buttonBox.add(Box.createHorizontalGlue()); if (retryAvailable) { Action retryAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { errorDialog.setTitle("-RETRY-"); errorDialog.dispose(); } }; JButton retryButton = new JButton(retryAction); retryButton.setText("Retry Ctrl+R"); buttonBox.add(retryButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK, false), "retry"); errorDialog.getRootPane().getActionMap().put("retry", retryAction); } AbstractAction closeAction = new AbstractAction(){ public void actionPerformed(ActionEvent e) { errorDialog.dispose(); } }; JButton closeButton = new JButton(closeAction); closeButton.setText("Close"); buttonBox.add(closeButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "close"); errorDialog.getRootPane().getActionMap().put("close", closeAction); errorDialog.getRootPane().setDefaultButton(closeButton); errorDialog.getContentPane().add(BorderLayout.CENTER, tabbedPane); errorDialog.getContentPane().add(BorderLayout.SOUTH, buttonBox); errorDialog.setSize(700, 500); errorDialog.setLocationRelativeTo(parentComponent); errorDialog.setVisible(true); /* BLOCKS */ if (errorDialog.getTitle().equals("-RETRY-")) { return true; } return false; } }.invokeAndWait(); } /** * Runs work method in event dispatcher thread. * Worker method returns a value. * * @author Fredrik Osterlind */ public static abstract class RunnableInEDT<T> { private T val; /** * Work method to be implemented. * * @return Return value */ public abstract T work(); /** * Runs worker method in event dispatcher thread. * * @see #work() * @return Worker method return value */ public T invokeAndWait() { if(java.awt.EventQueue.isDispatchThread()) { return RunnableInEDT.this.work(); } try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { val = RunnableInEDT.this.work(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return val; } } /** * This method can be used by various different modules in the simulator to * indicate for example that a mote has been selected. All mote highlight * listeners will be notified. An example application of mote highlightinh is * a simulator visualizer that highlights the mote. * * @see #addMoteHighlightObserver(Observer) * @param m * Mote to highlight */ public void signalMoteHighlight(Mote m) { moteHighlightObservable.setChangedAndNotify(m); } /** * Adds directed relation between given motes. * * @param source Source mote * @param dest Destination mote */ public void addMoteRelation(Mote source, Mote dest) { if (source == null || dest == null) { return; } removeMoteRelation(source, dest); /* Unique relations */ moteRelations.add(new MoteRelation(source, dest)); moteRelationObservable.setChangedAndNotify(); } /** * Removes the relations between given motes. * * @param source Source mote * @param dest Destination mote */ public void removeMoteRelation(Mote source, Mote dest) { if (source == null || dest == null) { return; } MoteRelation[] arr = getMoteRelations(); for (MoteRelation r: arr) { if (r.source == source && r.dest == dest) { moteRelations.remove(r); } } moteRelationObservable.setChangedAndNotify(); } /** * @return All current mote relations. * * @see #addMoteRelationsObserver(Observer) */ public MoteRelation[] getMoteRelations() { MoteRelation[] arr = new MoteRelation[moteRelations.size()]; moteRelations.toArray(arr); return arr; } /** * Adds mote relation observer. * Typically used by visualizer plugins. * * @param newObserver Observer */ public void addMoteRelationsObserver(Observer newObserver) { moteRelationObservable.addObserver(newObserver); } /** * Removes mote relation observer. * Typically used by visualizer plugins. * * @param observer Observer */ public void deleteMoteRelationsObserver(Observer observer) { moteRelationObservable.deleteObserver(observer); } /** * Tries to convert given file to be "portable". * The portable path is either relative to Contiki, or to the configuration (.csc) file. * * If this method fails, it returns the original file. * * @param file Original file * @return Portable file, or original file is conversion failed */ public File createPortablePath(File file) { File portable = null; portable = createContikiRelativePath(file); if (portable != null) { /*logger.info("Generated Contiki relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } portable = createConfigRelativePath(file); if (portable != null) { /*logger.info("Generated config relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } logger.warn("Path is not portable: '" + file.getPath()); return file; } /** * Tries to restore a previously "portable" file to be "absolute". * If the given file already exists, no conversion is performed. * * @see #createPortablePath(File) * @param file Portable file * @return Absolute file */ public File restorePortablePath(File file) { if (file == null || file.exists()) { /* No conversion possible/needed */ return file; } File absolute = null; absolute = restoreContikiRelativePath(file); if (absolute != null) { /*logger.info("Restored Contiki relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } absolute = restoreConfigRelativePath(file); if (absolute != null) { /*logger.info("Restored config relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } /*logger.info("Portable path was not restored: '" + file.getPath());*/ return file; } private final static String PATH_CONTIKI_IDENTIFIER = "[CONTIKI_DIR]"; private File createContikiRelativePath(File file) { try { File contikiPath = new File(GUI.getExternalToolsSetting("PATH_CONTIKI", null)); String contikiCanonical = contikiPath.getCanonicalPath(); String fileCanonical = file.getCanonicalPath(); if (!fileCanonical.startsWith(contikiCanonical)) { /* File is not in a Contiki subdirectory */ /*logger.info("File is not in a Contiki subdirectory: " + file.getAbsolutePath());*/ return null; } /* Replace Contiki's canonical path with Contiki identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(contikiCanonical), java.util.regex.Matcher.quoteReplacement(PATH_CONTIKI_IDENTIFIER)); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreContikiRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to Contiki relative path: " + e1.getMessage());*/ return null; } } private File restoreContikiRelativePath(File portable) { try { File contikiPath = new File(GUI.getExternalToolsSetting("PATH_CONTIKI", null)); String contikiCanonical = contikiPath.getCanonicalPath(); String portablePath = portable.getPath(); if (!portablePath.startsWith(PATH_CONTIKI_IDENTIFIER)) { return null; } File absolute = new File(portablePath.replace(PATH_CONTIKI_IDENTIFIER, contikiCanonical)); return absolute; } catch (IOException e) { return null; } } private final static String PATH_CONFIG_IDENTIFIER = "[CONFIG_DIR]"; public File currentConfigFile = null; /* Used to generate config relative paths */ private File createConfigRelativePath(File file) { String id = PATH_CONFIG_IDENTIFIER; if (currentConfigFile == null) { return null; } try { File configPath = currentConfigFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String configCanonical = configPath.getCanonicalPath(); String fileCanonical = file.getCanonicalPath(); if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow one parent directory */ configCanonical = configPath.getParentFile().getCanonicalPath(); id += "/.."; } if (!fileCanonical.startsWith(configCanonical)) { /* File is not in a config subdirectory */ logger.info("File is not in a config subdirectory: " + file.getAbsolutePath()); return null; } /* Replace config's canonical path with config identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(configCanonical), java.util.regex.Matcher.quoteReplacement(id)); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreConfigRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to config relative path: " + e1.getMessage());*/ return null; } } private File restoreConfigRelativePath(File portable) { if (currentConfigFile == null) { return null; } File configPath = currentConfigFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String portablePath = portable.getPath(); if (!portablePath.startsWith(PATH_CONFIG_IDENTIFIER)) { return null; } File absolute = new File(portablePath.replace(PATH_CONFIG_IDENTIFIER, configPath.getAbsolutePath())); return absolute; } private static JProgressBar PROGRESS_BAR = null; public static void setProgressMessage(String msg) { if (PROGRESS_BAR != null && PROGRESS_BAR.isShowing()) { PROGRESS_BAR.setString(msg); PROGRESS_BAR.setStringPainted(true); } } public interface HasQuickHelp { /** * @return Quick help. May be HTML formatted, but must not include the * document html-tags. */ public String getQuickHelp(); } /** * Load quick help for given object or identifier. Note that this method does not * show the quick help pane. * * @param obj If string: help identifier. Else, the class name of the argument * is used as help identifier. */ public void loadQuickHelp(final Object obj) { if (obj == null) { return; } String key; if (obj instanceof String) { key = (String) obj; } else { key = obj.getClass().getName(); } String help = null; if (obj instanceof HasQuickHelp) { help = ((HasQuickHelp) obj).getQuickHelp(); } else { if (quickHelpProperties == null) { /* Load quickhelp.txt */ try { quickHelpProperties = new Properties(); quickHelpProperties.load(new FileReader("quickhelp.txt")); } catch (Exception e) { quickHelpProperties = null; help = "<html><b>Failed to read quickhelp.txt:</b><p>" + e.getMessage() + "</html>"; } } if (quickHelpProperties != null) { help = quickHelpProperties.getProperty(key); } } if (help != null) { quickHelpTextPane.setText("<html>" + help + "</html>"); } else { quickHelpTextPane.setText( "<html><b>" + getDescriptionOf(obj) +"</b>" + "<p>No help available</html>"); } quickHelpTextPane.setCaretPosition(0); } /* GUI actions */ abstract class GUIAction extends AbstractAction { public GUIAction(String name) { super(name); } public GUIAction(String name, int nmenomic) { this(name); putValue(Action.MNEMONIC_KEY, nmenomic); } public GUIAction(String name, KeyStroke accelerator) { this(name); putValue(Action.ACCELERATOR_KEY, accelerator); } public GUIAction(String name, int nmenomic, KeyStroke accelerator) { this(name, nmenomic); putValue(Action.ACCELERATOR_KEY, accelerator); } public abstract boolean shouldBeEnabled(); } GUIAction newSimulationAction = new GUIAction("New simulation", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { myGUI.doCreateSimulation(true); } public boolean shouldBeEnabled() { return true; } }; GUIAction closeSimulationAction = new GUIAction("Close simulation", KeyEvent.VK_C) { public void actionPerformed(ActionEvent e) { myGUI.doRemoveSimulation(true); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction reloadSimulationAction = new GUIAction("keep random seed", KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { if (getSimulation() == null) { /* Reload last opened simulation */ final File file = getLastOpenedFile(); new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, true, file); } }).start(); return; } /* Reload current simulation */ long seed = getSimulation().getRandomSeed(); reloadCurrentSimulation(getSimulation().isRunning(), seed); } public boolean shouldBeEnabled() { return true; } }; GUIAction reloadRandomSimulationAction = new GUIAction("new random seed", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)) { public void actionPerformed(ActionEvent e) { /* Replace seed before reloading */ if (getSimulation() != null) { getSimulation().setRandomSeed(getSimulation().getRandomSeed()+1); reloadSimulationAction.actionPerformed(null); } } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction saveSimulationAction = new GUIAction("Save simulation", KeyEvent.VK_S) { public void actionPerformed(ActionEvent e) { myGUI.doSaveConfig(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return getSimulation() != null; } }; GUIAction closePluginsAction = new GUIAction("Close all plugins") { public void actionPerformed(ActionEvent e) { Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } } public boolean shouldBeEnabled() { return !startedPlugins.isEmpty(); } }; GUIAction exportExecutableJARAction = new GUIAction("Export simulation as executable JAR") { public void actionPerformed(ActionEvent e) { getSimulation().stopSimulation(); /* Info message */ JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "This function attempts to build an executable COOJA JAR from the current simulation.\n" + "The JAR will contain all simulation dependencies, including project JAR files and mote firmware files.\n" + "\nExecutable simulations can be used to run already prepared simulations on several computers.\n" + "\nThis is an experimental feature!", "Export simulation to executable JAR", JOptionPane.INFORMATION_MESSAGE); /* Select output directory */ JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Select directory for " + ExecuteJAR.EXECUTABLE_JAR_FILENAME); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setAcceptAllFileFilterUsed(false); int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File dir = fc.getSelectedFile(); if (!dir.isDirectory()) { return; } try { ExecuteJAR.buildExecutableJAR(GUI.this, dir); } catch (RuntimeException ex) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), ex.getMessage(), "Mote type not supported", JOptionPane.ERROR_MESSAGE); } } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction exitCoojaAction = new GUIAction("Exit", KeyEvent.VK_X, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { myGUI.doQuit(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return true; } }; GUIAction startStopSimulationAction = new GUIAction("Start/Stop simulation", KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { /* Start/Stop current simulation */ Simulation s = getSimulation(); if (s == null) { return; } if (s.isRunning()) { s.stopSimulation(); } else { s.startSimulation(); } } public void setEnabled(boolean newValue) { if (getSimulation() == null) { putValue(NAME, "Start/Stop simulation"); } else if (getSimulation().isRunning()) { putValue(NAME, "Stop simulation"); } else { putValue(NAME, "Start simulation"); } super.setEnabled(newValue); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; class StartPluginGUIAction extends GUIAction { public StartPluginGUIAction(String name) { super(name); } public void actionPerformed(final ActionEvent e) { new Thread(new Runnable() { public void run() { Class<Plugin> pluginClass = (Class<Plugin>) ((JMenuItem) e.getSource()).getClientProperty("class"); Mote mote = (Mote) ((JMenuItem) e.getSource()).getClientProperty("mote"); tryStartPlugin(pluginClass, myGUI, mySimulation, mote); } }).start(); } public boolean shouldBeEnabled() { return getSimulation() != null; } } GUIAction removeAllMotesAction = new GUIAction("Remove all motes") { public void actionPerformed(ActionEvent e) { Simulation s = getSimulation(); if (s.isRunning()) { s.stopSimulation(); } while (s.getMotesCount() > 0) { s.removeMote(getSimulation().getMote(0)); } } public boolean shouldBeEnabled() { Simulation s = getSimulation(); return s != null && s.getMotesCount() > 0; } }; GUIAction showQuickHelpAction = new GUIAction("Quick help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { public void actionPerformed(ActionEvent e) { if (!(e.getSource() instanceof JCheckBoxMenuItem)) { return; } boolean show = ((JCheckBoxMenuItem) e.getSource()).isSelected(); quickHelpTextPane.setVisible(show); quickHelpScroll.setVisible(show); ((JPanel)frame.getContentPane()).revalidate(); updateDesktopSize(getDesktopPane()); } public boolean shouldBeEnabled() { return true; } }; GUIAction showKeyboardShortcutsAction = new GUIAction("Keyboard shortcuts") { public void actionPerformed(ActionEvent e) { loadQuickHelp("KEYBOARD_SHORTCUTS"); JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } public boolean shouldBeEnabled() { return true; } }; GUIAction showBufferSettingsAction = new GUIAction("Buffer sizes") { public void actionPerformed(ActionEvent e) { if (mySimulation == null) { return; } BufferSettings.showDialog(myDesktopPane, mySimulation); } public boolean shouldBeEnabled() { return mySimulation != null; } }; }
tools/cooja/java/se/sics/cooja/GUI.java
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: GUI.java,v 1.147 2009/10/28 13:37:29 nifi Exp $ */ package se.sics.cooja; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.Dialog.ModalityType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyVetoException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Properties; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultDesktopManager; import javax.swing.InputMap; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import se.sics.cooja.MoteType.MoteTypeCreationException; import se.sics.cooja.VisPlugin.PluginRequiresVisualizationException; import se.sics.cooja.contikimote.ContikiMoteType; import se.sics.cooja.dialogs.AddMoteDialog; import se.sics.cooja.dialogs.BufferSettings; import se.sics.cooja.dialogs.ConfigurationWizard; import se.sics.cooja.dialogs.CreateSimDialog; import se.sics.cooja.dialogs.ExternalToolsDialog; import se.sics.cooja.dialogs.MessageList; import se.sics.cooja.dialogs.ProjectDirectoriesDialog; import se.sics.cooja.plugins.MoteTypeInformation; import se.sics.cooja.plugins.ScriptRunner; import se.sics.cooja.plugins.SimControl; import se.sics.cooja.plugins.SimInformation; /** * Main file of COOJA Simulator. Typically contains a visualizer for the * simulator, but can also be started without visualizer. * * This class loads external Java classes (in project directories), and handles the * COOJA plugins as well as the configuration system. If provides a number of * help methods for the rest of the COOJA system, and is the starting point for * loading and saving simulation configs. * * @author Fredrik Osterlind */ public class GUI extends Observable { /** * External tools default Win32 settings filename. */ public static final String EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME = "/external_tools_win32.config"; /** * External tools default Mac OS X settings filename. */ public static final String EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME = "/external_tools_macosx.config"; /** * External tools default FreeBSD settings filename. */ public static final String EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME = "/external_tools_freebsd.config"; /** * External tools default Linux/Unix settings filename. */ public static final String EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME = "/external_tools_linux.config"; /** * External tools default Linux/Unix settings filename for 64 bit architectures. * Tested on Intel 64-bit Gentoo Linux. */ public static final String EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME = "/external_tools_linux_64.config"; /** * External tools user settings filename. */ public static final String EXTERNAL_TOOLS_USER_SETTINGS_FILENAME = ".cooja.user.properties"; public static File externalToolsUserSettingsFile; private static boolean externalToolsUserSettingsFileReadOnly = false; private static String specifiedContikiPath = null; /** * Logger settings filename. */ public static final String LOG_CONFIG_FILE = "log4j_config.xml"; /** * Default project configuration filename. */ public static String PROJECT_DEFAULT_CONFIG_FILENAME = null; /** * User project configuration filename. */ public static final String PROJECT_CONFIG_FILENAME = "cooja.config"; /** * File filter only showing saved simulations files (*.csc). */ public static final FileFilter SAVED_SIMULATIONS_FILES = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".csc")) { return true; } return false; } public String getDescription() { return "COOJA Configuration files"; } public String toString() { return ".csc"; } }; private static JFrame frame = null; private static JApplet applet = null; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(GUI.class); // External tools setting names private static Properties defaultExternalToolsSettings; private static Properties currentExternalToolsSettings; private static final String externalToolsSettingNames[] = new String[] { "PATH_CONTIKI", "PATH_COOJA_CORE_RELATIVE", "PATH_MAKE", "PATH_SHELL", "PATH_C_COMPILER", "COMPILER_ARGS", "PATH_LINKER", "LINK_COMMAND_1", "LINK_COMMAND_2", "PATH_AR", "AR_COMMAND_1", "AR_COMMAND_2", "PATH_OBJDUMP", "OBJDUMP_ARGS", "PATH_JAVAC", "CONTIKI_STANDARD_PROCESSES", "CONTIKI_MAIN_TEMPLATE_FILENAME", "CMD_GREP_PROCESSES", "REGEXP_PARSE_PROCESSES", "CMD_GREP_INTERFACES", "REGEXP_PARSE_INTERFACES", "CMD_GREP_SENSORS", "REGEXP_PARSE_SENSORS", "DEFAULT_PROJECTDIRS", "CORECOMM_TEMPLATE_FILENAME", "MAPFILE_DATA_START", "MAPFILE_DATA_SIZE", "MAPFILE_BSS_START", "MAPFILE_BSS_SIZE", "MAPFILE_VAR_NAME", "MAPFILE_VAR_ADDRESS_1", "MAPFILE_VAR_ADDRESS_2", "MAPFILE_VAR_SIZE_1", "MAPFILE_VAR_SIZE_2", "PARSE_WITH_COMMAND", "PARSE_COMMAND", "COMMAND_VAR_NAME_ADDRESS", "COMMAND_DATA_START", "COMMAND_DATA_END", "COMMAND_BSS_START", "COMMAND_BSS_END", }; private static final int FRAME_NEW_OFFSET = 30; private static final int FRAME_STANDARD_WIDTH = 150; private static final int FRAME_STANDARD_HEIGHT = 300; private GUI myGUI; private Simulation mySimulation; protected GUIEventHandler guiEventHandler = new GUIEventHandler(); private JMenu menuPlugins, menuMoteTypeClasses, menuMoteTypes; private JMenu menuOpenSimulation, menuConfOpenSimulation; private boolean hasFileHistoryChanged; private Vector<Class<? extends Plugin>> menuMotePluginClasses; private JDesktopPane myDesktopPane; private Vector<Plugin> startedPlugins = new Vector<Plugin>(); private ArrayList<GUIAction> guiActions = new ArrayList<GUIAction>(); // Platform configuration variables // Maintained via method reparseProjectConfig() private ProjectConfig projectConfig; private Vector<File> currentProjectDirs = new Vector<File>(); private ClassLoader projectDirClassLoader; private Vector<Class<? extends MoteType>> moteTypeClasses = new Vector<Class<? extends MoteType>>(); private Vector<Class<? extends Plugin>> pluginClasses = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends Plugin>> pluginClassesTemporary = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends RadioMedium>> radioMediumClasses = new Vector<Class<? extends RadioMedium>>(); private Vector<Class<? extends IPDistributor>> ipDistributorClasses = new Vector<Class<? extends IPDistributor>>(); private Vector<Class<? extends Positioner>> positionerClasses = new Vector<Class<? extends Positioner>>(); private class HighlightObservable extends Observable { private void setChangedAndNotify(Mote mote) { setChanged(); notifyObservers(mote); } } private HighlightObservable moteHighlightObservable = new HighlightObservable(); private class MoteRelationsObservable extends Observable { private void setChangedAndNotify() { setChanged(); notifyObservers(); } } private MoteRelationsObservable moteRelationObservable = new MoteRelationsObservable(); private JTextPane quickHelpTextPane; private JScrollPane quickHelpScroll; private Properties quickHelpProperties = null; /* quickhelp.txt */ /** * Mote relation (directed). */ public static class MoteRelation { public Mote source; public Mote dest; public MoteRelation(Mote source, Mote dest) { this.source = source; this.dest = dest; } } private ArrayList<MoteRelation> moteRelations = new ArrayList<MoteRelation>(); /** * Creates a new COOJA Simulator GUI. * * @param desktop Desktop pane */ public GUI(JDesktopPane desktop) { myGUI = this; mySimulation = null; myDesktopPane = desktop; if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } /* Help panel */ quickHelpTextPane = new JTextPane(); quickHelpTextPane.setContentType("text/html"); quickHelpTextPane.setEditable(false); quickHelpTextPane.setVisible(false); quickHelpScroll = new JScrollPane(quickHelpTextPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); quickHelpScroll.setPreferredSize(new Dimension(200, 0)); quickHelpScroll.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(0, 3, 0, 0) )); quickHelpScroll.setVisible(false); loadQuickHelp("KEYBOARD_SHORTCUTS"); // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); /* Debugging - Break on repaints outside EDT */ /*RepaintManager.setCurrentManager(new RepaintManager() { public void addDirtyRegion(JComponent comp, int a, int b, int c, int d) { if(!java.awt.EventQueue.isDispatchThread()) { throw new RuntimeException("Repainting outside EDT"); } super.addDirtyRegion(comp, a, b, c, d); } });*/ // Register default project directories String defaultProjectDirs = getExternalToolsSetting("DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null && defaultProjectDirs.length() > 0) { String[] arr = defaultProjectDirs.split(";"); for (String p : arr) { File projectDir = restorePortablePath(new File(p)); currentProjectDirs.add(projectDir); } // Load extendable parts (using current project config) try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading projects: " + e.getMessage(), e); if (isVisualized()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Default projects could not load, reconfigure project directories:" + "\n\tMenu->Settings->Manage project directories" + "\n\nSee console for stack trace with more information.", "Project loading error", JOptionPane.ERROR_MESSAGE); } } } // Start all standard GUI plugins for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, null, null); } } } /** * Add mote highlight observer. * * @see #deleteMoteHighlightObserver(Observer) * @param newObserver * New observer */ public void addMoteHighlightObserver(Observer newObserver) { moteHighlightObservable.addObserver(newObserver); } /** * Delete mote highlight observer. * * @see #addMoteHighlightObserver(Observer) * @param observer * Observer to delete */ public void deleteMoteHighlightObserver(Observer observer) { moteHighlightObservable.deleteObserver(observer); } /** * @return True if simulator is visualized */ public static boolean isVisualized() { return isVisualizedInFrame() || isVisualizedInApplet(); } public static Container getTopParentContainer() { if (isVisualizedInFrame()) { return frame; } if (isVisualizedInApplet()) { /* Find parent frame for applet */ Container container = applet; while((container = container.getParent()) != null){ if (container instanceof Frame) { return container; } if (container instanceof Dialog) { return container; } if (container instanceof Window) { return container; } } logger.fatal("Returning null top owner container"); } return null; } public static boolean isVisualizedInFrame() { return frame != null; } public static URL getAppletCodeBase() { return applet.getCodeBase(); } public static boolean isVisualizedInApplet() { return applet != null; } /** * Tries to create/remove simulator visualizer. * * @param visualized Visualized */ public void setVisualizedInFrame(boolean visualized) { if (visualized) { if (!isVisualizedInFrame()) { configureFrame(myGUI, false); } } else { if (frame != null) { frame.setVisible(false); frame.dispose(); frame = null; } } } public File getLastOpenedFile() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); return historyArray.length > 0 ? new File(historyArray[0]) : null; } public File[] getFileHistory() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); File[] history = new File[historyArray.length]; for (int i = 0; i < historyArray.length; i++) { history[i] = new File(historyArray[i]); } return history; } public void addToFileHistory(File file) { // Fetch current history String[] history = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); String newFile = file.getAbsolutePath(); if (history.length > 0 && history[0].equals(newFile)) { // File already added return; } // Create new history StringBuilder newHistory = new StringBuilder(); newHistory.append(newFile); for (int i = 0, count = 1; i < history.length && count < 10; i++) { String historyFile = history[i]; if (newFile.equals(historyFile) || historyFile.length() == 0) { // File already added or empty file name } else { newHistory.append(';').append(historyFile); count++; } } setExternalToolsSetting("SIMCFG_HISTORY", newHistory.toString()); saveExternalToolsUserSettings(); hasFileHistoryChanged = true; } private void updateOpenHistoryMenuItems() { if (isVisualizedInApplet()) { return; } if (!hasFileHistoryChanged) { // No need to update menu because file history has not changed return; } hasFileHistoryChanged = false; File[] openFilesHistory = getFileHistory(); updateOpenHistoryMenuItems("confopen", menuConfOpenSimulation, openFilesHistory); updateOpenHistoryMenuItems("open", menuOpenSimulation, openFilesHistory); } private void updateOpenHistoryMenuItems(String type, JMenu menu, File[] openFilesHistory) { menu.removeAll(); JMenuItem browseItem = new JMenuItem("Browse..."); browseItem.setActionCommand(type + " sim"); browseItem.addActionListener(guiEventHandler); menu.add(browseItem); menu.add(new JSeparator()); String command = type + " last sim"; int index = 0; JMenuItem lastItem; for (File file: openFilesHistory) { if (index < 10) { char mnemonic = (char) ('0' + (++index % 10)); lastItem = new JMenuItem(mnemonic + " " + file.getName()); lastItem.setMnemonic(mnemonic); } else { lastItem = new JMenuItem(file.getName()); } lastItem.setActionCommand(command); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); lastItem.addActionListener(guiEventHandler); menu.add(lastItem); } } /** * Enables/disables menues and menu items depending on whether a simulation is loaded etc. */ private void updateGUIComponentState() { if (!isVisualized()) { return; } /* Update action state */ for (GUIAction a: guiActions) { a.setEnabled(a.shouldBeEnabled()); } /* Mote and mote type menues */ if (menuMoteTypeClasses != null) { menuMoteTypeClasses.setEnabled(getSimulation() != null); } if (menuMoteTypes != null) { menuMoteTypes.setEnabled(getSimulation() != null); } } private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu; JMenuItem menuItem; /* Prepare GUI actions */ guiActions.add(newSimulationAction); guiActions.add(closeSimulationAction); guiActions.add(reloadSimulationAction); guiActions.add(reloadRandomSimulationAction); guiActions.add(saveSimulationAction); guiActions.add(closePluginsAction); guiActions.add(exitCoojaAction); guiActions.add(startStopSimulationAction); guiActions.add(removeAllMotesAction); guiActions.add(showBufferSettingsAction); /* File menu */ menu = new JMenu("File"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); updateOpenHistoryMenuItems(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); menu.add(new JMenuItem(newSimulationAction)); menuItem = new JMenu("Reload simulation"); menuItem.add(new JMenuItem(reloadSimulationAction)); menuItem.add(new JMenuItem(reloadRandomSimulationAction)); menu.add(menuItem); menu.add(new JMenuItem(closeSimulationAction)); menuOpenSimulation = new JMenu("Open simulation"); menuOpenSimulation.setMnemonic(KeyEvent.VK_O); menu.add(menuOpenSimulation); if (isVisualizedInApplet()) { menuOpenSimulation.setEnabled(false); menuOpenSimulation.setToolTipText("Not available in applet version"); } menuConfOpenSimulation = new JMenu("Open & Reconfigure simulation"); menuConfOpenSimulation.setMnemonic(KeyEvent.VK_R); menu.add(menuConfOpenSimulation); if (isVisualizedInApplet()) { menuConfOpenSimulation.setEnabled(false); menuConfOpenSimulation.setToolTipText("Not available in applet version"); } hasFileHistoryChanged = true; menu.add(new JMenuItem(saveSimulationAction)); menu.addSeparator(); menu.add(new JMenuItem(closePluginsAction)); menu.addSeparator(); menu.add(new JMenuItem(exitCoojaAction)); /* Simulation menu */ menu = new JMenu("Simulation"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_S); menuBar.add(menu); menu.add(new JMenuItem(startStopSimulationAction)); GUIAction guiAction = new StartPluginGUIAction("Control panel"); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.putClientProperty("class", SimControl.class); menu.add(menuItem); guiAction = new StartPluginGUIAction("Information"); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_I); menuItem.putClientProperty("class", SimInformation.class); menu.add(menuItem); // Mote type menu menu = new JMenu("Mote Types"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_T); menuBar.add(menu); // Mote type classes sub menu menuMoteTypeClasses = new JMenu("Create mote type"); menuMoteTypeClasses.setMnemonic(KeyEvent.VK_C); menuMoteTypeClasses.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypeClasses.removeAll(); // Recreate menu items JMenuItem menuItem; for (Class<? extends MoteType> moteTypeClass : moteTypeClasses) { /* Sort mote types according to abstraction level */ String abstractionLevelDescription = GUI.getAbstractionLevelDescriptionOf(moteTypeClass); if(abstractionLevelDescription == null) { abstractionLevelDescription = "[unknown cross-level]"; } /* Check if abstraction description already exists */ JSeparator abstractionLevelSeparator = null; for (Component component: menuMoteTypeClasses.getMenuComponents()) { if (component == null || !(component instanceof JSeparator)) { continue; } JSeparator existing = (JSeparator) component; if (abstractionLevelDescription.equals(existing.getToolTipText())) { abstractionLevelSeparator = existing; break; } } if (abstractionLevelSeparator == null) { abstractionLevelSeparator = new JSeparator(); abstractionLevelSeparator.setToolTipText(abstractionLevelDescription); menuMoteTypeClasses.add(abstractionLevelSeparator); } String description = GUI.getDescriptionOf(moteTypeClass); menuItem = new JMenuItem(description); menuItem.setActionCommand("create mote type"); menuItem.putClientProperty("class", moteTypeClass); menuItem.setToolTipText(abstractionLevelDescription); menuItem.addActionListener(guiEventHandler); if (isVisualizedInApplet() && moteTypeClass.equals(ContikiMoteType.class)) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } /* Add new item directly after cross level separator */ for (int i=0; i < menuMoteTypeClasses.getMenuComponentCount(); i++) { if (menuMoteTypeClasses.getMenuComponent(i) == abstractionLevelSeparator) { menuMoteTypeClasses.add(menuItem, i+1); break; } } } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypeClasses); guiAction = new StartPluginGUIAction("Information"); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.putClientProperty("class", MoteTypeInformation.class); menu.add(menuItem); // Mote menu menu = new JMenu("Motes"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_M); menuBar.add(menu); // Mote types sub menu menuMoteTypes = new JMenu("Add motes of type"); menuMoteTypes.setMnemonic(KeyEvent.VK_A); menuMoteTypes.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypes.removeAll(); if (mySimulation == null) { return; } // Recreate menu items JMenuItem menuItem; for (MoteType moteType : mySimulation.getMoteTypes()) { menuItem = new JMenuItem(moteType.getDescription()); menuItem.setActionCommand("add motes"); menuItem.setToolTipText(getDescriptionOf(moteType.getClass())); menuItem.putClientProperty("motetype", moteType); menuItem.addActionListener(guiEventHandler); menuMoteTypes.add(menuItem); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypes); menu.add(new JMenuItem(removeAllMotesAction)); // Plugins menu if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } else { menuPlugins.setText("Plugins"); } menuPlugins.setMnemonic(KeyEvent.VK_P); menuBar.add(menuPlugins); // Settings menu menu = new JMenu("Settings"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menuBar.add(menu); menuItem = new JMenuItem("External tools paths"); menuItem.setActionCommand("edit paths"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Manage project directories"); menuItem.setActionCommand("manage projects"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Compiler configuration wizard"); menuItem.setActionCommand("configuration wizard"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menu.add(new JMenuItem(showBufferSettingsAction)); menu.addSeparator(); menuItem = new JMenuItem("Java version: " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); menuItem.setEnabled(false); menu.add(menuItem); /* Help */ menu = new JMenu("Help"); menu.setMnemonic(KeyEvent.VK_H); menu.add(new JMenuItem(showKeyboardShortcutsAction)); JCheckBoxMenuItem checkBox = new JCheckBoxMenuItem(showQuickHelpAction); showQuickHelpAction.putValue("checkbox", checkBox); menu.add(checkBox); menuBar.add(menu); // Mote plugins popup menu (not available via menu bar) if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } return menuBar; } private static void configureFrame(final GUI gui, boolean createSimDialog) { if (frame == null) { frame = new JFrame("COOJA Simulator"); } frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* Menu bar */ frame.setJMenuBar(gui.createMenuBar()); /* Scrollable desktop */ JComponent desktop = gui.getDesktopPane(); desktop.setOpaque(true); JScrollPane scroll = new JScrollPane(desktop); scroll.setBorder(null); JPanel container = new JPanel(new BorderLayout()); container.add(BorderLayout.CENTER, scroll); container.add(BorderLayout.EAST, gui.quickHelpScroll); frame.setContentPane(container); frame.setSize(700, 700); frame.setLocationRelativeTo(null); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { gui.doQuit(true); } }); frame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { updateDesktopSize(gui.getDesktopPane()); } }); /* Restore frame size and position */ int framePosX = Integer.parseInt(getExternalToolsSetting("FRAME_POS_X", "0")); int framePosY = Integer.parseInt(getExternalToolsSetting("FRAME_POS_Y", "0")); int frameWidth = Integer.parseInt(getExternalToolsSetting("FRAME_WIDTH", "0")); int frameHeight = Integer.parseInt(getExternalToolsSetting("FRAME_HEIGHT", "0")); String frameScreen = getExternalToolsSetting("FRAME_SCREEN", ""); /* Restore position to the same graphics device */ GraphicsDevice device = null; GraphicsDevice all[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (GraphicsDevice gd : all) { if (gd.getIDstring().equals(frameScreen)) { device = gd; } } /* Check if frame should be maximized */ if (device != null) { if (frameWidth == Integer.MAX_VALUE && frameHeight == Integer.MAX_VALUE) { frame.setLocation(device.getDefaultConfiguration().getBounds().getLocation()); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); } else if (frameWidth > 0 && frameHeight > 0) { /* Sanity-check: will Cooja be visible on screen? */ boolean intersects = device.getDefaultConfiguration().getBounds().intersects( new Rectangle(framePosX, framePosY, frameWidth, frameHeight)); if (intersects) { frame.setLocation(framePosX, framePosY); frame.setSize(frameWidth, frameHeight); } } } frame.setVisible(true); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } private static void configureApplet(final GUI gui, boolean createSimDialog) { applet = CoojaApplet.applet; // Add menu bar JMenuBar menuBar = gui.createMenuBar(); applet.setJMenuBar(menuBar); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); applet.setContentPane(newContentPane); applet.setSize(700, 700); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } /** * @return Current desktop pane (simulator visualizer) */ public JDesktopPane getDesktopPane() { return myDesktopPane; } private static void setLookAndFeel() { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); ToolTipManager.sharedInstance().setDismissDelay(60000); /* Nimbus */ try { String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("linux")) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } else { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } return; } catch (Exception e) { } /* System */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); return; } catch (Exception e) { } } private static void updateDesktopSize(final JDesktopPane desktop) { if (desktop == null || !desktop.isVisible() || desktop.getParent() == null) { return; } Rectangle rect = desktop.getVisibleRect(); Dimension pref = new Dimension(rect.width - 1, rect.height - 1); for (JInternalFrame frame : desktop.getAllFrames()) { if (pref.width < frame.getX() + frame.getWidth() - 20) { pref.width = frame.getX() + frame.getWidth(); } if (pref.height < frame.getY() + frame.getHeight() - 20) { pref.height = frame.getY() + frame.getHeight(); } } desktop.setPreferredSize(pref); desktop.revalidate(); } private static JDesktopPane createDesktopPane() { final JDesktopPane desktop = new JDesktopPane() { public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); updateDesktopSize(this); } public void remove(Component c) { super.remove(c); updateDesktopSize(this); } public Component add(Component comp) { Component c = super.add(comp); updateDesktopSize(this); return c; } }; desktop.setDesktopManager(new DefaultDesktopManager() { public void endResizingFrame(JComponent f) { super.endResizingFrame(f); updateDesktopSize(desktop); } public void endDraggingFrame(JComponent f) { super.endDraggingFrame(f); updateDesktopSize(desktop); } }); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); return desktop; } private static Simulation quickStartSimulationConfig(File config, boolean vis) { logger.info("> Starting COOJA"); JDesktopPane desktop = createDesktopPane(); if (vis) { frame = new JFrame("COOJA Simulator"); } GUI gui = new GUI(desktop); if (vis) { configureFrame(gui, false); } if (vis) { gui.doLoadConfig(false, true, config); return gui.getSimulation(); } else { try { Simulation newSim = gui.loadSimulationConfig(config, true); if (newSim == null) { return null; } gui.setSimulation(newSim, false); return newSim; } catch (Exception e) { logger.fatal("Exception when loading simulation: ", e); return null; } } } /** * Allows user to create a simulation with a single mote type. * * @param source Contiki application file name * @return True if simulation was created */ private static boolean quickStartSimulation(String source) { logger.info("> Starting COOJA"); JDesktopPane desktop = createDesktopPane(); frame = new JFrame("COOJA Simulator"); GUI gui = new GUI(desktop); configureFrame(gui, false); logger.info("> Creating simulation"); Simulation simulation = new Simulation(gui); simulation.setTitle("Quickstarted simulation: " + source); boolean simOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), simulation); if (!simOK) { logger.fatal("No simulation, aborting quickstart"); System.exit(1); } gui.setSimulation(simulation, true); logger.info("> Creating mote type"); ContikiMoteType moteType = new ContikiMoteType(); moteType.setContikiSourceFile(new File(source)); moteType.setDescription("Contiki Mote Type (" + source + ")"); try { boolean compileOK = moteType.configureAndInit(GUI.getTopParentContainer(), simulation, true); if (!compileOK) { logger.fatal("Mote type initialization failed, aborting quickstart"); return false; } } catch (MoteTypeCreationException e1) { logger.fatal("Mote type initialization failed, aborting quickstart"); return false; } simulation.addMoteType(moteType); logger.info("> Adding motes"); gui.doAddMotes(moteType); return true; } //// PROJECT CONFIG AND EXTENDABLE PARTS METHODS //// /** * Register new mote type class. * * @param moteTypeClass * Class to register */ public void registerMoteType(Class<? extends MoteType> moteTypeClass) { moteTypeClasses.add(moteTypeClass); } /** * Unregister all mote type classes. */ public void unregisterMoteTypes() { moteTypeClasses.clear(); } /** * @return All registered mote type classes */ public Vector<Class<? extends MoteType>> getRegisteredMoteTypes() { return moteTypeClasses; } /** * Register new IP distributor class * * @param ipDistributorClass * Class to register * @return True if class was registered */ public boolean registerIPDistributor( Class<? extends IPDistributor> ipDistributorClass) { // Check that vector constructor exists try { ipDistributorClass.getConstructor(new Class[] { Vector.class }); } catch (Exception e) { logger.fatal("No vector constructor found of IP distributor: " + ipDistributorClass); return false; } ipDistributorClasses.add(ipDistributorClass); return true; } /** * Unregister all IP distributors. */ public void unregisterIPDistributors() { ipDistributorClasses.clear(); } /** * @return All registered IP distributors */ public Vector<Class<? extends IPDistributor>> getRegisteredIPDistributors() { return ipDistributorClasses; } /** * Register new positioner class. * * @param positionerClass * Class to register * @return True if class was registered */ public boolean registerPositioner(Class<? extends Positioner> positionerClass) { // Check that interval constructor exists try { positionerClass .getConstructor(new Class[] { int.class, double.class, double.class, double.class, double.class, double.class, double.class }); } catch (Exception e) { logger.fatal("No interval constructor found of positioner: " + positionerClass); return false; } positionerClasses.add(positionerClass); return true; } /** * Unregister all positioner classes. */ public void unregisterPositioners() { positionerClasses.clear(); } /** * @return All registered positioner classes */ public Vector<Class<? extends Positioner>> getRegisteredPositioners() { return positionerClasses; } /** * Register new radio medium class. * * @param radioMediumClass * Class to register * @return True if class was registered */ public boolean registerRadioMedium( Class<? extends RadioMedium> radioMediumClass) { // Check that simulation constructor exists try { radioMediumClass.getConstructor(new Class[] { Simulation.class }); } catch (Exception e) { logger.fatal("No simulation constructor found of radio medium: " + radioMediumClass); return false; } radioMediumClasses.add(radioMediumClass); return true; } /** * Unregister all radio medium classes. */ public void unregisterRadioMediums() { radioMediumClasses.clear(); } /** * @return All registered radio medium classes */ public Vector<Class<? extends RadioMedium>> getRegisteredRadioMediums() { return radioMediumClasses; } /** * Builds new project configuration using current project directories settings. * Reregisters mote types, plugins, IP distributors, positioners and radio * mediums. This method may still return true even if all classes could not be * registered, but always returns false if all project directory configuration * files were not parsed correctly. * * Any registered temporary plugins will be saved and reregistered. */ public void reparseProjectConfig() throws ParseProjectsException { if (PROJECT_DEFAULT_CONFIG_FILENAME == null) { if (isVisualizedInApplet()) { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_applet.config"; } else { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_default.config"; } } // Backup temporary plugins Vector<Class<? extends Plugin>> oldTempPlugins = (Vector<Class<? extends Plugin>>) pluginClassesTemporary.clone(); // Reset current configuration unregisterMoteTypes(); unregisterPlugins(); unregisterIPDistributors(); unregisterPositioners(); unregisterRadioMediums(); try { // Read default configuration projectConfig = new ProjectConfig(true); } catch (FileNotFoundException e) { logger.fatal("Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } catch (IOException e) { logger.fatal("Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } if (!isVisualizedInApplet()) { // Append project directory configurations for (File projectDir : currentProjectDirs) { try { // Append config to general config projectConfig.appendProjectDir(projectDir); } catch (FileNotFoundException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when loading project: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when reading project config: " + e.getMessage()).initCause(e); } } // Create class loader try { projectDirClassLoader = createClassLoader(currentProjectDirs); } catch (ClassLoaderCreationException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when creating class loader").initCause(e); } } else { projectDirClassLoader = null; } // Register mote types String[] moteTypeClassNames = projectConfig.getStringArrayValue(GUI.class, "MOTETYPES"); if (moteTypeClassNames != null) { for (String moteTypeClassName : moteTypeClassNames) { Class<? extends MoteType> moteTypeClass = tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass != null) { registerMoteType(moteTypeClass); // logger.info("Loaded mote type class: " + moteTypeClassName); } else { logger.warn("Could not load mote type class: " + moteTypeClassName); } } } // Register plugins registerPlugin(SimControl.class, false); // Not in menu registerPlugin(SimInformation.class, false); // Not in menu registerPlugin(MoteTypeInformation.class, false); // Not in menu String[] pluginClassNames = projectConfig.getStringArrayValue(GUI.class, "PLUGINS"); if (pluginClassNames != null) { for (String pluginClassName : pluginClassNames) { Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass != null) { registerPlugin(pluginClass); // logger.info("Loaded plugin class: " + pluginClassName); } else { logger.warn("Could not load plugin class: " + pluginClassName); } } } // Reregister temporary plugins again if (oldTempPlugins != null) { for (Class<? extends Plugin> pluginClass : oldTempPlugins) { if (registerTemporaryPlugin(pluginClass)) { // logger.info("Reregistered temporary plugin class: " + // getDescriptionOf(pluginClass)); } else { logger.warn("Could not reregister temporary plugin class: " + getDescriptionOf(pluginClass)); } } } // Register IP distributors String[] ipDistClassNames = projectConfig.getStringArrayValue(GUI.class, "IP_DISTRIBUTORS"); if (ipDistClassNames != null) { for (String ipDistClassName : ipDistClassNames) { Class<? extends IPDistributor> ipDistClass = tryLoadClass(this, IPDistributor.class, ipDistClassName); if (ipDistClass != null) { registerIPDistributor(ipDistClass); // logger.info("Loaded IP distributor class: " + ipDistClassName); } else { logger .warn("Could not load IP distributor class: " + ipDistClassName); } } } // Register positioners String[] positionerClassNames = projectConfig.getStringArrayValue( GUI.class, "POSITIONERS"); if (positionerClassNames != null) { for (String positionerClassName : positionerClassNames) { Class<? extends Positioner> positionerClass = tryLoadClass(this, Positioner.class, positionerClassName); if (positionerClass != null) { registerPositioner(positionerClass); // logger.info("Loaded positioner class: " + positionerClassName); } else { logger .warn("Could not load positioner class: " + positionerClassName); } } } // Register radio mediums String[] radioMediumsClassNames = projectConfig.getStringArrayValue( GUI.class, "RADIOMEDIUMS"); if (radioMediumsClassNames != null) { for (String radioMediumClassName : radioMediumsClassNames) { Class<? extends RadioMedium> radioMediumClass = tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { registerRadioMedium(radioMediumClass); // logger.info("Loaded radio medium class: " + radioMediumClassName); } else { logger.warn("Could not load radio medium class: " + radioMediumClassName); } } } } /** * Returns the current project configuration common to the entire simulator. * * @return Current project configuration */ public ProjectConfig getProjectConfig() { return projectConfig; } /** * Returns the current project directories common to the entire simulator. * * @return Current project directories. */ public Vector<File> getProjectDirs() { return currentProjectDirs; } // // PLUGIN METHODS //// /** * Show a started plugin in working area. * * @param plugin Plugin */ public void showPlugin(final Plugin plugin) { new RunnableInEDT<Boolean>() { public Boolean work() { JInternalFrame pluginFrame = plugin.getGUI(); if (pluginFrame == null) { logger.fatal("Failed trying to show plugin without visualizer!"); return false; } int nrFrames = myDesktopPane.getAllFrames().length; myDesktopPane.add(pluginFrame); /* Set size if not already specified by plugin */ if (pluginFrame.getWidth() <= 0 || pluginFrame.getHeight() <= 0) { pluginFrame.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); } /* Set location if not already visible */ if (pluginFrame.getLocation().x <= 0 && pluginFrame.getLocation().y <= 0) { pluginFrame.setLocation( nrFrames * FRAME_NEW_OFFSET, nrFrames * FRAME_NEW_OFFSET); } pluginFrame.setVisible(true); /* Select plugin */ try { for (JInternalFrame existingPlugin : myDesktopPane.getAllFrames()) { existingPlugin.setSelected(false); } pluginFrame.setSelected(true); } catch (Exception e) { } myDesktopPane.moveToFront(pluginFrame); return true; } }.invokeAndWait(); } /** * Close all mote plugins for given mote. * * @param mote Mote */ public void closeMotePlugins(Mote mote) { Vector<Plugin> pluginsToRemove = new Vector<Plugin>(); for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); if (pluginType != PluginType.MOTE_PLUGIN) { continue; } Mote pluginMote = (Mote) startedPlugin.getTag(); if (pluginMote == mote) { pluginsToRemove.add(startedPlugin); } } for (Plugin pluginToRemove: pluginsToRemove) { removePlugin(pluginToRemove, false); } } /** * Remove a plugin from working area. * * @param plugin * Plugin to remove * @param askUser * If plugin is the last one, ask user if we should remove current * simulation also? */ public void removePlugin(final Plugin plugin, final boolean askUser) { new RunnableInEDT<Boolean>() { public Boolean work() { /* Free resources */ plugin.closePlugin(); startedPlugins.remove(plugin); updateGUIComponentState(); /* Dispose visualized components */ if (plugin.getGUI() != null) { plugin.getGUI().dispose(); } /* (OPTIONAL) Remove simulation if all plugins are closed */ if (getSimulation() != null && askUser && startedPlugins.isEmpty()) { doRemoveSimulation(true); } return true; } }.invokeAndWait(); } /** * Same as the {@link #startPlugin(Class, GUI, Simulation, Mote)} method, * but does not throw exceptions. If COOJA is visualised, an error dialog * is shown if plugin could not be started. * * @see #startPlugin(Class, GUI, Simulation, Mote) * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin */ public Plugin tryStartPlugin(final Class<? extends Plugin> pluginClass, final GUI argGUI, final Simulation argSimulation, final Mote argMote) { try { return startPlugin(pluginClass, argGUI, argSimulation, argMote); } catch (PluginConstructionException ex) { if (GUI.isVisualized()) { GUI.showErrorDialog(GUI.getTopParentContainer(), "Error when starting plugin", ex, false); } else { /* If the plugin requires visualization, inform user */ Throwable cause = ex.getCause(); do { if (cause instanceof PluginRequiresVisualizationException) { logger.info("Visualized plugin was not started: " + pluginClass); return null; } } while ((cause=cause.getCause()) != null); logger.fatal("Error when starting plugin", ex); } } return null; } /** * Starts given plugin. If visualized, the plugin is also shown. * * @see PluginType * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin * @throws PluginConstructionException At errors */ public Plugin startPlugin(final Class<? extends Plugin> pluginClass, final GUI argGUI, final Simulation argSimulation, final Mote argMote) throws PluginConstructionException { // Check that plugin class is registered if (!pluginClasses.contains(pluginClass)) { throw new PluginConstructionException("Plugin class not registered: " + pluginClass); } // Construct plugin depending on plugin type int pluginType = pluginClass.getAnnotation(PluginType.class).value(); Plugin plugin; try { if (pluginType == PluginType.MOTE_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for mote plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for mote plugin"); } if (argMote == null) { throw new PluginConstructionException("No mote argument for mote plugin"); } plugin = pluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, GUI.class }) .newInstance(argMote, argSimulation, argGUI); /* Tag plugin with mote */ plugin.tagWithObject(argMote); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for simulation plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for simulation plugin"); } plugin = pluginClass.getConstructor(new Class[] { Simulation.class, GUI.class }) .newInstance(argSimulation, argGUI); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for GUI plugin"); } plugin = pluginClass.getConstructor(new Class[] { GUI.class }) .newInstance(argGUI); } else { throw new PluginConstructionException("Bad plugin type: " + pluginType); } } catch (PluginRequiresVisualizationException e) { PluginConstructionException ex = new PluginConstructionException("Plugin class requires visualization: " + pluginClass.getName()); ex.initCause(e); throw ex; } catch (Exception e) { PluginConstructionException ex = new PluginConstructionException("Construction error for plugin of class: " + pluginClass.getName()); ex.initCause(e); throw ex; } // Add to active plugins list startedPlugins.add(plugin); updateGUIComponentState(); // Show plugin if visualizer type if (plugin.getGUI() != null) { myGUI.showPlugin(plugin); } return plugin; } /** * Register a plugin to be included in the GUI. The plugin will be visible in * the menubar. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerPlugin(Class<? extends Plugin> newPluginClass) { return registerPlugin(newPluginClass, true); } /** * Register a temporary plugin to be included in the GUI. The plugin will be * visible in the menubar. This plugin will automatically be unregistered if * the current simulation is removed. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerTemporaryPlugin(Class<? extends Plugin> newPluginClass) { if (pluginClasses.contains(newPluginClass)) { return false; } boolean returnVal = registerPlugin(newPluginClass, true); if (!returnVal) { return false; } pluginClassesTemporary.add(newPluginClass); return true; } /** * Unregister a plugin class. Removes any plugin menu items links as well. * * @param pluginClass * Plugin class to unregister */ public void unregisterPlugin(Class<? extends Plugin> pluginClass) { // Remove (if existing) plugin class menu items for (Component menuComponent : menuPlugins.getMenuComponents()) { if (menuComponent.getClass().isAssignableFrom(JMenuItem.class)) { JMenuItem menuItem = (JMenuItem) menuComponent; if (menuItem.getClientProperty("class").equals(pluginClass)) { menuPlugins.remove(menuItem); } } } if (menuMotePluginClasses.contains(pluginClass)) { menuMotePluginClasses.remove(pluginClass); } // Remove from plugin vectors (including temporary) if (pluginClasses.contains(pluginClass)) { pluginClasses.remove(pluginClass); } if (pluginClassesTemporary.contains(pluginClass)) { pluginClassesTemporary.remove(pluginClass); } } /** * Register a plugin to be included in the GUI. * * @param newPluginClass * New plugin to register * @param addToMenu * Should this plugin be added to the dedicated plugins menubar? * @return True if this plugin was registered ok, false otherwise */ private boolean registerPlugin(final Class<? extends Plugin> newPluginClass, boolean addToMenu) { // Get description annotation (if any) final String description = getDescriptionOf(newPluginClass); // Get plugin type annotation (required) final int pluginType; if (newPluginClass.isAnnotationPresent(PluginType.class)) { pluginType = newPluginClass.getAnnotation(PluginType.class).value(); } else { pluginType = PluginType.UNDEFINED_PLUGIN; } // Check that plugin type is valid and constructor exists try { if (pluginType == PluginType.MOTE_PLUGIN) { newPluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, GUI.class }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { newPluginClass.getConstructor(new Class[] { Simulation.class, GUI.class }); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { newPluginClass.getConstructor(new Class[] { GUI.class }); } else { logger.fatal("Could not find valid plugin type annotation in class " + newPluginClass); return false; } } catch (NoSuchMethodException e) { logger.fatal("Could not find valid constructor in class " + newPluginClass + ": " + e); return false; } if (addToMenu && menuPlugins != null) { new RunnableInEDT<Boolean>() { public Boolean work() { // Create 'start plugin'-menu item JMenuItem menuItem; String tooltip = "<html>"; /* Sort menu according to plugin type */ int itemIndex=0; if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { for (; itemIndex < menuPlugins.getItemCount(); itemIndex++) { if (menuPlugins.getItem(itemIndex) == null /* separator */) { break; } } tooltip += "COOJA plugin: " + newPluginClass.getName(); menuItem = new JMenuItem(description); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tryStartPlugin(newPluginClass, myGUI, null, null); } }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { for (; itemIndex < menuPlugins.getItemCount(); itemIndex++) { if (menuPlugins.getItem(itemIndex) == null /* separator */) { break; } } itemIndex++; for (; itemIndex < menuPlugins.getItemCount(); itemIndex++) { if (menuPlugins.getItem(itemIndex) == null /* separator */) { break; } } tooltip += "Simulation plugin: " + newPluginClass.getName(); GUIAction guiAction = new StartPluginGUIAction(description); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); } else if (pluginType == PluginType.MOTE_PLUGIN) { // Disable previous menu item and add new item to mote plugins menu menuItem = new JMenuItem(description); menuItem.setEnabled(false); tooltip += "Mote plugin: " + newPluginClass.getName(); tooltip += "<br>Start mote plugins by right-clicking a mote in the simulation visualizer"; menuMotePluginClasses.add(newPluginClass); itemIndex = menuPlugins.getItemCount(); } else { logger.warn("Unknown plugin type: " + pluginType); return false; } /* Check if plugin was imported by a project directory */ File project = getProjectConfig().getUserProjectDefining(GUI.class, "PLUGINS", newPluginClass.getName()); if (project != null) { tooltip += "<br>Loaded by project: " + project.getPath(); } tooltip += "</html>"; menuItem.setToolTipText(tooltip); menuItem.putClientProperty("class", newPluginClass); menuPlugins.add(menuItem, itemIndex); return true; } }.invokeAndWait(); } pluginClasses.add(newPluginClass); return true; } /** * Unregister all plugin classes, including temporary plugins. */ public void unregisterPlugins() { if (menuPlugins != null) { menuPlugins.removeAll(); /* COOJA/GUI plugins at top, simulation plugins in middle, mote plugins at bottom */ menuPlugins.addSeparator(); menuPlugins.addSeparator(); } if (menuMotePluginClasses != null) { menuMotePluginClasses.clear(); } pluginClasses.clear(); pluginClassesTemporary.clear(); } /** * Returns started plugin with given class name, if any. * * @param classname Class name * @return Plugin instance */ public Plugin getStartedPlugin(String classname) { for (Plugin p: startedPlugins) { if (p.getClass().getName().equals(classname)) { return p; } } return null; } /** * Return a mote plugins submenu for given mote. * * @param mote Mote * @return Mote plugins menu */ public JMenu createMotePluginsSubmenu(Mote mote) { JMenu menuMotePlugins = new JMenu("Open mote plugin for " + mote); for (Class<? extends Plugin> motePluginClass: menuMotePluginClasses) { GUIAction guiAction = new StartPluginGUIAction(getDescriptionOf(motePluginClass)); JMenuItem menuItem = new JMenuItem(guiAction); menuItem.putClientProperty("class", motePluginClass); menuItem.putClientProperty("mote", mote); menuMotePlugins.add(menuItem); } return menuMotePlugins; } // // GUI CONTROL METHODS //// /** * @return Current simulation */ public Simulation getSimulation() { return mySimulation; } public void setSimulation(Simulation sim, boolean startPlugins) { if (sim != null) { doRemoveSimulation(false); } mySimulation = sim; updateGUIComponentState(); // Set frame title if (frame != null) { frame.setTitle("COOJA Simulator" + " - " + sim.getTitle()); } // Open standard plugins (if none opened already) if (startPlugins) { for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.SIM_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, sim, null); } } } setChanged(); notifyObservers(); } /** * Creates a new mote type of the given mote type class. * * @param moteTypeClass * Mote type class */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass) { if (mySimulation == null) { logger.fatal("Can't create mote type (no simulation)"); return; } // Stop simulation (if running) mySimulation.stopSimulation(); // Create mote type MoteType newMoteType = null; boolean moteTypeOK = false; try { newMoteType = moteTypeClass.newInstance(); moteTypeOK = newMoteType.configureAndInit(GUI.getTopParentContainer(), mySimulation, isVisualized()); } catch (Exception e) { logger.fatal("Exception when creating mote type", e); if (isVisualized()) { showErrorDialog(getTopParentContainer(), "Mote type creation error", e, false); } return; } // Add mote type to simulation if (moteTypeOK) { mySimulation.addMoteType(newMoteType); /* Allow user to immediately add motes */ doAddMotes(newMoteType); } } /** * Remove current simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? * @return True if no simulation exists when method returns */ public boolean doRemoveSimulation(boolean askForConfirmation) { if (mySimulation == null) { return true; } if (askForConfirmation) { boolean ok = new RunnableInEDT<Boolean>() { public Boolean work() { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(GUI.getTopParentContainer(), "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return false; } return true; } }.invokeAndWait(); if (!ok) { return false; } } // Close all started non-GUI plugins for (Object startedPlugin : startedPlugins.toArray()) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { removePlugin((Plugin) startedPlugin, false); } } // Delete simulation mySimulation.deleteObservers(); mySimulation.stopSimulation(); /* Clear current mote relations */ MoteRelation relations[] = getMoteRelations(); for (MoteRelation r: relations) { removeMoteRelation(r.source, r.dest); } mySimulation = null; updateGUIComponentState(); // Unregister temporary plugin classes Class<? extends Plugin>[] pluginClasses = new Class[pluginClassesTemporary.size()]; pluginClassesTemporary.toArray(pluginClasses); for (Class<? extends Plugin> pClass: pluginClasses) { unregisterPlugin(pClass); } // Reset frame title if (isVisualizedInFrame()) { frame.setTitle("COOJA Simulator"); } setChanged(); notifyObservers(); return true; } /** * Load a simulation configuration file from disk * * @param askForConfirmation Ask for confirmation before removing any current simulation * @param quick Quick-load simulation * @param configFile Configuration file to load, if null a dialog will appear */ public void doLoadConfig(boolean askForConfirmation, final boolean quick, File configFile) { if (isVisualizedInApplet()) { return; } /* Remove current simulation */ if (!doRemoveSimulation(true)) { return; } /* Use provided configuration, or open File Chooser */ if (configFile != null && !configFile.isDirectory()) { if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file: " + configFile.getAbsolutePath()); /* File does not exist, open dialog */ doLoadConfig(askForConfirmation, quick, null); return; } } else { final File suggestedFile = configFile; configFile = new RunnableInEDT<File>() { public File work() { JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); if (suggestedFile != null && suggestedFile.isDirectory()) { fc.setCurrentDirectory(suggestedFile); } else { /* Suggest file using file history */ File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } } int returnVal = fc.showOpenDialog(GUI.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { logger.info("Load command cancelled by user..."); return null; } File file = fc.getSelectedFile(); if (!file.exists()) { /* Try default file extension */ file = new File(file.getParent(), file.getName() + SAVED_SIMULATIONS_FILES); } if (!file.exists() || !file.canRead()) { logger.fatal("No read access to file"); return null; } return file; } }.invokeAndWait(); if (configFile == null) { return; } } final JDialog progressDialog; final String progressTitle = configFile == null ? "Loading" : ("Loading " + configFile.getAbsolutePath()); if (quick) { final Thread loadThread = Thread.currentThread(); progressDialog = new RunnableInEDT<JDialog>() { public JDialog work() { final JDialog progressDialog; if (GUI.getTopParentContainer() instanceof Window) { progressDialog = new JDialog((Window) GUI.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); } else if (GUI.getTopParentContainer() instanceof Frame) { progressDialog = new JDialog((Frame) GUI.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); } else if (GUI.getTopParentContainer() instanceof Dialog) { progressDialog = new JDialog((Dialog) GUI.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); } else { logger.warn("No parent container"); progressDialog = new JDialog((Frame) null, progressTitle, ModalityType.APPLICATION_MODAL); } JPanel progressPanel = new JPanel(new BorderLayout()); JProgressBar progressBar; JButton button; progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(GUI.getTopParentContainer()); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { progressDialog.setVisible(true); } }); return progressDialog; } }.invokeAndWait(); } else { progressDialog = null; } // Load simulation in this thread, while showing progress monitor final File fileToLoad = configFile; Simulation newSim = null; boolean shouldRetry = false; do { try { shouldRetry = false; myGUI.doRemoveSimulation(false); newSim = loadSimulationConfig(fileToLoad, quick); myGUI.setSimulation(newSim, false); addToFileHistory(fileToLoad); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(GUI.getTopParentContainer(), "Simulation load error", e, true); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(GUI.getTopParentContainer(), "Simulation load error", e, true); } } while (shouldRetry); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } return; } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * * @param autoStart Start executing simulation when loaded * @param newSeed Change simulation seed */ public void reloadCurrentSimulation(final boolean autoStart, final long randomSeed) { if (getSimulation() == null) { logger.fatal("No simulation to reload"); return; } final JDialog progressDialog = new JDialog(frame, "Reloading", true); final Thread loadThread = new Thread(new Runnable() { public void run() { /* Get current simulation configuration */ Element root = new Element("simconf"); Element simulationElement = new Element("simulation"); simulationElement.addContent(getSimulation().getConfigXML()); root.addContent(simulationElement); Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } /* Remove current simulation, and load config */ boolean shouldRetry = false; do { try { shouldRetry = false; myGUI.doRemoveSimulation(false); Simulation newSim = loadSimulationConfig(root, true, new Long(randomSeed)); myGUI.setSimulation(newSim, false); if (autoStart) { newSim.startSimulation(); } } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } } while (shouldRetry); if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); // Display progress dialog while reloading JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ JButton button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); progressDialog.setVisible(true); } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * The same random seed is used. * * @see #reloadCurrentSimulation(boolean, boolean) * @param autoStart Start executing simulation when loaded */ public void reloadCurrentSimulation(boolean autoStart) { reloadCurrentSimulation(autoStart, getSimulation().getRandomSeed()); } /** * Save current simulation configuration to disk * * @param askForConfirmation * Ask for confirmation before overwriting file */ public File doSaveConfig(boolean askForConfirmation) { if (isVisualizedInApplet()) { return null; } if (mySimulation == null) { return null; } mySimulation.stopSimulation(); JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); // Suggest file using history File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = fc.getSelectedFile(); if (!fc.accept(saveFile)) { saveFile = new File(saveFile.getParent(), saveFile.getName() + SAVED_SIMULATIONS_FILES); } if (saveFile.exists()) { if (askForConfirmation) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( GUI.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return null; } } } if (!saveFile.exists() || saveFile.canWrite()) { saveSimulationConfig(saveFile); addToFileHistory(saveFile); return saveFile; } else { logger.fatal("No write access to file"); } } else { logger.info("Save command cancelled by user..."); } return null; } /** * Add new mote to current simulation */ public void doAddMotes(MoteType moteType) { if (mySimulation != null) { mySimulation.stopSimulation(); Vector<Mote> newMotes = AddMoteDialog.showDialog(getTopParentContainer(), mySimulation, moteType); if (newMotes != null) { for (Mote newMote : newMotes) { mySimulation.addMote(newMote); } } } else { logger.warn("No simulation active"); } } /** * Create a new simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doCreateSimulation(boolean askForConfirmation) { /* Remove current simulation */ if (!doRemoveSimulation(askForConfirmation)) { return; } // Create new simulation Simulation newSim = new Simulation(this); boolean createdOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), newSim); if (createdOK) { myGUI.setSimulation(newSim, true); } } /** * Quit program * * @param askForConfirmation * Should we ask for confirmation before quitting? */ public void doQuit(boolean askForConfirmation) { if (isVisualizedInApplet()) { return; } if (askForConfirmation) { String s1 = "Quit"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(GUI.getTopParentContainer(), "Sure you want to quit?", "Close COOJA Simulator", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Clean up resources Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } /* Store frame size and position */ if (isVisualizedInFrame()) { setExternalToolsSetting("FRAME_SCREEN", frame.getGraphicsConfiguration().getDevice().getIDstring()); setExternalToolsSetting("FRAME_POS_X", "" + frame.getLocationOnScreen().x); setExternalToolsSetting("FRAME_POS_Y", "" + frame.getLocationOnScreen().y); if (frame.getExtendedState() == JFrame.MAXIMIZED_BOTH) { setExternalToolsSetting("FRAME_WIDTH", "" + Integer.MAX_VALUE); setExternalToolsSetting("FRAME_HEIGHT", "" + Integer.MAX_VALUE); } else { setExternalToolsSetting("FRAME_WIDTH", "" + frame.getWidth()); setExternalToolsSetting("FRAME_HEIGHT", "" + frame.getHeight()); } } saveExternalToolsUserSettings(); System.exit(0); } // // EXTERNAL TOOLS SETTINGS METHODS //// /** * @return Number of external tools settings */ public static int getExternalToolsSettingsCount() { return externalToolsSettingNames.length; } /** * Get name of external tools setting at given index. * * @param index * Setting index * @return Name */ public static String getExternalToolsSettingName(int index) { return externalToolsSettingNames[index]; } /** * @param name * Name of setting * @return Value */ public static String getExternalToolsSetting(String name) { return currentExternalToolsSettings.getProperty(name); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsSetting(String name, String defaultValue) { if (specifiedContikiPath != null && "PATH_CONTIKI".equals(name)) { return specifiedContikiPath; } return currentExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsDefaultSetting(String name, String defaultValue) { return defaultExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param newVal * New value */ public static void setExternalToolsSetting(String name, String newVal) { if (specifiedContikiPath != null && "PATH_CONTIKI".equals(name)) { specifiedContikiPath = newVal; } else { currentExternalToolsSettings.setProperty(name, newVal); } } /** * Load external tools settings from default file. */ public static void loadExternalToolsDefaultSettings() { String osName = System.getProperty("os.name").toLowerCase(); String osArch = System.getProperty("os.arch").toLowerCase(); String filename = null; if (osName.startsWith("win")) { filename = GUI.EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME; } else if (osName.startsWith("mac os x")) { filename = GUI.EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME; } else if (osName.startsWith("freebsd")) { filename = GUI.EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME; } else if (osName.startsWith("linux")) { filename = GUI.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; if (osArch.startsWith("amd64")) { filename = GUI.EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME; } } else { logger.warn("Unknown system: " + osName); logger.warn("Using default linux external tools configuration"); filename = GUI.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; } logger.info("Loading external tools user settings from: " + filename); try { InputStream in = GUI.class.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " not found"); } Properties settings = new Properties(); settings.load(in); in.close(); currentExternalToolsSettings = settings; defaultExternalToolsSettings = (Properties) currentExternalToolsSettings.clone(); } catch (IOException e) { // Error while importing default properties logger.warn( "Error when reading external tools settings from " + filename, e); } finally { if (currentExternalToolsSettings == null) { defaultExternalToolsSettings = new Properties(); currentExternalToolsSettings = new Properties(); } } } /** * Load user values from external properties file */ public static void loadExternalToolsUserSettings() { if (externalToolsUserSettingsFile == null) { return; } try { FileInputStream in = new FileInputStream(externalToolsUserSettingsFile); Properties settings = new Properties(); settings.load(in); in.close(); Enumeration en = settings.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); setExternalToolsSetting(key, settings.getProperty(key)); } } catch (FileNotFoundException e) { // No default configuration file found, using default } catch (IOException e) { // Error while importing saved properties, using default logger.warn("Error when reading default settings from " + externalToolsUserSettingsFile); } } /** * Save external tools user settings to file. */ public static void saveExternalToolsUserSettings() { if (isVisualizedInApplet()) { return; } if (externalToolsUserSettingsFileReadOnly) { return; } try { FileOutputStream out = new FileOutputStream(externalToolsUserSettingsFile); Properties differingSettings = new Properties(); Enumeration keyEnum = currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = getExternalToolsDefaultSetting(key, ""); String currentSetting = currentExternalToolsSettings.getProperty(key, ""); if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "COOJA External Tools (User specific)"); out.close(); } catch (FileNotFoundException ex) { // Could not open settings file for writing, aborting logger.warn("Could not save external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } catch (IOException ex) { // Could not open settings file for writing, aborting logger.warn("Error while saving external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } } // // GUI EVENT HANDLER //// private class GUIEventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("confopen sim")) { new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, false, null); } }).start(); } else if (e.getActionCommand().equals("confopen last sim")) { final File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, false, file); } }).start(); } else if (e.getActionCommand().equals("open sim")) { new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, true, null); } }).start(); } else if (e.getActionCommand().equals("open last sim")) { final File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, true, file); } }).start(); } else if (e.getActionCommand().equals("create mote type")) { myGUI.doCreateMoteType((Class<? extends MoteType>) ((JMenuItem) e .getSource()).getClientProperty("class")); } else if (e.getActionCommand().equals("add motes")) { myGUI.doAddMotes((MoteType) ((JMenuItem) e.getSource()) .getClientProperty("motetype")); } else if (e.getActionCommand().equals("edit paths")) { ExternalToolsDialog.showDialog(GUI.getTopParentContainer()); } else if (e.getActionCommand().equals("manage projects")) { File[] newProjects = ProjectDirectoriesDialog.showDialog( GUI.getTopParentContainer(), GUI.this, currentProjectDirs.toArray(new File[0]) ); if (newProjects != null) { currentProjectDirs.clear(); for (File p: newProjects) { currentProjectDirs.add(p); } try { reparseProjectConfig(); } catch (ParseProjectsException ex) { logger.fatal("Error when loading projects: " + ex.getMessage(), ex); if (isVisualized()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Configured projects could not load, reconfigure project directories:" + "\n\tMenu->Settings->Manage project directories" + "\n\nSee console for stack trace with more information.", "Project loading error", JOptionPane.ERROR_MESSAGE); } } } } else if (e.getActionCommand().equals("configuration wizard")) { ConfigurationWizard.startWizard(GUI.getTopParentContainer(), GUI.this); } else { logger.warn("Unhandled action: " + e.getActionCommand()); } } } // // VARIOUS HELP METHODS //// /** * Help method that tries to load and initialize a class with given name. * * @param <N> * Class extending given class type * @param classType * Class type * @param className * Class name * @return Class extending given class type or null if not found */ public <N extends Object> Class<? extends N> tryLoadClass( Object callingObject, Class<N> classType, String className) { if (callingObject != null) { try { return callingObject.getClass().getClassLoader().loadClass(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } try { return Class.forName(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } if (!isVisualizedInApplet()) { try { if (projectDirClassLoader != null) { return projectDirClassLoader.loadClass(className).asSubclass( classType); } } catch (NoClassDefFoundError e) { } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } return null; } public ClassLoader createProjectDirClassLoader(Vector<File> projectsDirs) throws ParseProjectsException, ClassLoaderCreationException { if (projectDirClassLoader == null) { reparseProjectConfig(); } return createClassLoader(projectDirClassLoader, projectsDirs); } private ClassLoader createClassLoader(Vector<File> currentProjectDirs) throws ClassLoaderCreationException { return createClassLoader(ClassLoader.getSystemClassLoader(), currentProjectDirs); } private File findJarFile(File projectDir, String jarfile) { File fp = new File(jarfile); if (!fp.exists()) { fp = new File(projectDir, jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/lib/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "lib/" + jarfile); } return fp.exists() ? fp : null; } private ClassLoader createClassLoader(ClassLoader parent, Vector<File> projectDirs) throws ClassLoaderCreationException { if (projectDirs == null || projectDirs.isEmpty()) { return parent; } // Combine class loader from all project directories (including any // specified JAR files) ArrayList<URL> urls = new ArrayList<URL>(); for (int j = projectDirs.size() - 1; j >= 0; j--) { File projectDir = projectDirs.get(j); try { urls.add((new File(projectDir, "java")).toURI().toURL()); // Read configuration to check if any JAR files should be loaded ProjectConfig projectConfig = new ProjectConfig(false); projectConfig.appendProjectDir(projectDir); String[] projectJarFiles = projectConfig.getStringArrayValue( GUI.class, "JARFILES"); if (projectJarFiles != null && projectJarFiles.length > 0) { for (String jarfile : projectJarFiles) { File jarpath = findJarFile(projectDir, jarfile); if (jarpath == null) { throw new FileNotFoundException(jarfile); } urls.add(jarpath.toURI().toURL()); } } } catch (Exception e) { logger.fatal("Error when trying to read JAR-file in " + projectDir + ": " + e); throw (ClassLoaderCreationException) new ClassLoaderCreationException( "Error when trying to read JAR-file in " + projectDir).initCause(e); } } URL[] urlsArray = urls.toArray(new URL[urls.size()]); /* TODO Load from webserver if applet */ return new URLClassLoader(urlsArray, parent); } /** * Help method that returns the description for given object. This method * reads from the object's class annotations if existing. Otherwise it returns * the simple class name of object's class. * * @param object * Object * @return Description */ public static String getDescriptionOf(Object object) { return getDescriptionOf(object.getClass()); } /** * Help method that returns the description for given class. This method reads * from class annotations if existing. Otherwise it returns the simple class * name. * * @param clazz * Class * @return Description */ public static String getDescriptionOf(Class<? extends Object> clazz) { if (clazz.isAnnotationPresent(ClassDescription.class)) { return clazz.getAnnotation(ClassDescription.class).value(); } return clazz.getSimpleName(); } /** * Help method that returns the abstraction level description for given mote type class. * * @param clazz * Class * @return Description */ public static String getAbstractionLevelDescriptionOf(Class<? extends MoteType> clazz) { if (clazz.isAnnotationPresent(AbstractionLevelDescription.class)) { return clazz.getAnnotation(AbstractionLevelDescription.class).value(); } return null; } /** * Load configurations and create a GUI. * * @param args * null */ public static void main(String[] args) { try { // Configure logger if ((new File(LOG_CONFIG_FILE)).exists()) { DOMConfigurator.configure(LOG_CONFIG_FILE); } else { // Used when starting from jar DOMConfigurator.configure(GUI.class.getResource("/" + LOG_CONFIG_FILE)); } externalToolsUserSettingsFile = new File(System.getProperty("user.home"), EXTERNAL_TOOLS_USER_SETTINGS_FILENAME); } catch (AccessControlException e) { BasicConfigurator.configure(); externalToolsUserSettingsFile = null; } /* Look and Feel: Nimbus */ setLookAndFeel(); // Parse general command arguments for (String element : args) { if (element.startsWith("-contiki=")) { String arg = element.substring("-contiki=".length()); GUI.specifiedContikiPath = arg; } if (element.startsWith("-external_tools_config=")) { String arg = element.substring("-external_tools_config=".length()); File specifiedExternalToolsConfigFile = new File(arg); if (!specifiedExternalToolsConfigFile.exists()) { logger.fatal("Specified external tools configuration not found: " + specifiedExternalToolsConfigFile); specifiedExternalToolsConfigFile = null; System.exit(1); } else { GUI.externalToolsUserSettingsFile = specifiedExternalToolsConfigFile; GUI.externalToolsUserSettingsFileReadOnly = true; } } } // Check if simulator should be quick-started if (args.length > 0 && args[0].startsWith("-quickstart=")) { String contikiApp = args[0].substring("-quickstart=".length()); /* Cygwin fix */ if (contikiApp.startsWith("/cygdrive/")) { char driveCharacter = contikiApp.charAt("/cygdrive/".length()); contikiApp = contikiApp.replace("/cygdrive/" + driveCharacter + "/", driveCharacter + ":/"); } boolean ok = false; if (contikiApp.endsWith(".csc")) { ok = quickStartSimulationConfig(new File(contikiApp), true) != null; } else { if (contikiApp.endsWith(".cooja")) { contikiApp = contikiApp.substring(0, contikiApp.length() - ".cooja".length()); } if (!contikiApp.endsWith(".c")) { contikiApp += ".c"; } ok = quickStartSimulation(contikiApp); } if (!ok) { System.exit(1); } } else if (args.length > 0 && args[0].startsWith("-nogui=")) { /* Load simulation */ String config = args[0].substring("-nogui=".length()); File configFile = new File(config); Simulation sim = quickStartSimulationConfig(configFile, false); if (sim == null) { System.exit(1); } GUI gui = sim.getGUI(); /* Make sure at least one test editor is controlling the simulation */ boolean hasEditor = false; for (Plugin startedPlugin : gui.startedPlugins) { if (startedPlugin instanceof ScriptRunner) { hasEditor = true; break; } } /* Backwards compatibility: * simulation has no test editor, but has external (old style) test script. * We will manually start a test editor from here. */ if (!hasEditor) { File scriptFile = new File(config.substring(0, config.length()-4) + ".js"); if (scriptFile.exists()) { logger.info("Detected old simulation test, starting test editor manually from: " + scriptFile); ScriptRunner plugin = (ScriptRunner) gui.tryStartPlugin(ScriptRunner.class, gui, sim, null); if (plugin == null) { System.exit(1); } plugin.updateScript(scriptFile); plugin.setScriptActive(true); sim.setDelayTime(0); sim.startSimulation(); } else { logger.fatal("No test editor controlling simulation, aborting"); System.exit(1); } } } else if (args.length > 0 && args[0].startsWith("-applet")) { String tmpWebPath=null, tmpBuildPath=null, tmpEsbFirmware=null, tmpSkyFirmware=null; for (int i = 1; i < args.length; i++) { if (args[i].startsWith("-web=")) { tmpWebPath = args[i].substring("-web=".length()); } else if (args[i].startsWith("-sky_firmware=")) { tmpSkyFirmware = args[i].substring("-sky_firmware=".length()); } else if (args[i].startsWith("-esb_firmware=")) { tmpEsbFirmware = args[i].substring("-esb_firmware=".length()); } else if (args[i].startsWith("-build=")) { tmpBuildPath = args[i].substring("-build=".length()); } } // Applet start-up final String webPath = tmpWebPath, buildPath = tmpBuildPath; final String skyFirmware = tmpSkyFirmware, esbFirmware = tmpEsbFirmware; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); applet = CoojaApplet.applet; GUI gui = new GUI(desktop); GUI.setExternalToolsSetting("PATH_CONTIKI_BUILD", buildPath); GUI.setExternalToolsSetting("PATH_CONTIKI_WEB", webPath); GUI.setExternalToolsSetting("SKY_FIRMWARE", skyFirmware); GUI.setExternalToolsSetting("ESB_FIRMWARE", esbFirmware); configureApplet(gui, false); } }); } else { // Frame start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); frame = new JFrame("COOJA Simulator"); GUI gui = new GUI(desktop); configureFrame(gui, false); } }); } } /** * Loads a simulation configuration from given file. * * When loading Contiki mote types, the libraries must be recompiled. User may * change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public Simulation loadSimulationConfig(File file, boolean quick) throws UnsatisfiedLinkError, SimulationCreationException { this.currentConfigFile = file; /* Used to generate config relative paths */ try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(file); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick, null); } catch (JDOMException e) { logger.fatal("Config not wellformed: " + e.getMessage()); return null; } catch (IOException e) { logger.fatal("Load simulation error: " + e.getMessage()); return null; } } private Simulation loadSimulationConfig(StringReader stringReader, boolean quick) throws SimulationCreationException { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(stringReader); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick, null); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "IO Exception: " + e.getMessage()).initCause(e); } } private Simulation loadSimulationConfig(Element root, boolean quick, Long manualRandomSeed) throws SimulationCreationException { Simulation newSim = null; try { // Check that config file version is correct if (!root.getName().equals("simconf")) { logger.fatal("Not a valid COOJA simulation config!"); return null; } /* Verify project directories */ boolean projectsOk = verifyProjects(root.getChildren(), !quick); /* GENERATE UNIQUE MOTE TYPE IDENTIFIERS */ root.detach(); String configString = new XMLOutputter().outputString(new Document(root)); /* Locate Contiki mote types in config */ Properties moteTypeIDMappings = new Properties(); String identifierExtraction = ContikiMoteType.class.getName() + "[\\s\\n]*<identifier>([^<]*)</identifier>"; Matcher matcher = Pattern.compile(identifierExtraction).matcher(configString); while (matcher.find()) { moteTypeIDMappings.setProperty(matcher.group(1), ""); } /* Create old to new identifier mappings */ Enumeration<Object> existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); MoteType[] existingMoteTypes = null; if (mySimulation != null) { existingMoteTypes = mySimulation.getMoteTypes(); } ArrayList<Object> reserved = new ArrayList<Object>(); reserved.addAll(moteTypeIDMappings.keySet()); reserved.addAll(moteTypeIDMappings.values()); String newID = ContikiMoteType.generateUniqueMoteTypeID(existingMoteTypes, reserved); moteTypeIDMappings.setProperty(existingIdentifier, newID); } /* Create new config */ existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); configString = configString.replaceAll( "<identifier>" + existingIdentifier + "</identifier>", "<identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</identifier>"); configString = configString.replaceAll( "<motetype_identifier>" + existingIdentifier + "</motetype_identifier>", "<motetype_identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</motetype_identifier>"); } /* Replace existing config */ root = new SAXBuilder().build(new StringReader(configString)).getRootElement(); // Create new simulation from config for (Object element : root.getChildren()) { if (((Element) element).getName().equals("simulation")) { Collection<Element> config = ((Element) element).getChildren(); newSim = new Simulation(this); System.gc(); boolean createdOK = newSim.setConfigXML(config, !quick, manualRandomSeed); if (!createdOK) { logger.info("Simulation not loaded"); return null; } } } // Restart plugins from config setPluginsConfigXML(root.getChildren(), newSim, !quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "No access to configuration file: " + e.getMessage()).initCause(e); } catch (MoteTypeCreationException e) { throw (SimulationCreationException) new SimulationCreationException( "Mote type creation error: " + e.getMessage()).initCause(e); } catch (Exception e) { throw (SimulationCreationException) new SimulationCreationException( "Unknown error: " + e.getMessage()).initCause(e); } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File, boolean) * @param file * File to write */ public void saveSimulationConfig(File file) { this.currentConfigFile = file; /* Used to generate config relative paths */ try { // Create simulation config Element root = new Element("simconf"); /* Store project directories meta data */ for (File project: currentProjectDirs) { Element projectElement = new Element("project"); projectElement.addContent(createPortablePath(project).getPath().replaceAll("\\\\", "/")); root.addContent(projectElement); } Element simulationElement = new Element("simulation"); simulationElement.addContent(mySimulation.getConfigXML()); root.addContent(simulationElement); // Create started plugins config Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } // Create and write to document Document doc = new Document(root); FileOutputStream out = new FileOutputStream(file); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); e.printStackTrace(); } } /** * Returns started plugins config. * * @return Config or null */ public Collection<Element> getPluginsConfigXML() { Vector<Element> config = new Vector<Element>(); // Loop through all started plugins // (Only return config of non-GUI plugins) Element pluginElement, pluginSubElement; for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); // Ignore GUI plugins if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { continue; } pluginElement = new Element("plugin"); pluginElement.setText(startedPlugin.getClass().getName()); // Create mote argument config (if mote plugin) if (pluginType == PluginType.MOTE_PLUGIN && startedPlugin.getTag() != null) { pluginSubElement = new Element("mote_arg"); Mote taggedMote = (Mote) startedPlugin.getTag(); for (int moteNr = 0; moteNr < mySimulation.getMotesCount(); moteNr++) { if (mySimulation.getMote(moteNr) == taggedMote) { pluginSubElement.setText(Integer.toString(moteNr)); pluginElement.addContent(pluginSubElement); break; } } } // Create plugin specific configuration Collection<Element> pluginXML = startedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("plugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } // If plugin is visualizer plugin, create visualization arguments if (startedPlugin.getGUI() != null) { JInternalFrame pluginFrame = startedPlugin.getGUI(); pluginSubElement = new Element("width"); pluginSubElement.setText("" + pluginFrame.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + getDesktopPane().getComponentZOrder(pluginFrame)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + pluginFrame.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + pluginFrame.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + pluginFrame.getLocation().y); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("minimized"); pluginSubElement.setText(new Boolean(pluginFrame.isIcon()).toString()); pluginElement.addContent(pluginSubElement); } config.add(pluginElement); } return config; } public boolean verifyProjects(Collection<Element> configXML, boolean visAvailable) { boolean allOk = true; /* Match current projects against projects in simulation config */ for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("project")) { File projectFile = restorePortablePath(new File(pluginElement.getText())); try { projectFile = projectFile.getCanonicalFile(); } catch (IOException e) { } boolean found = false; for (File currentProject: currentProjectDirs) { if (projectFile.getPath().replaceAll("\\\\", "/"). equals(currentProject.getPath().replaceAll("\\\\", "/"))) { found = true; break; } } if (!found) { logger.warn("Loaded simulation may depend on not found project: '" + projectFile + "'"); allOk = false; } } } return allOk; } /** * Starts plugins with arguments in given config. * * @param configXML * Config XML elements * @param simulation * Simulation on which to start plugins * @return True if all plugins started, false otherwise */ public boolean setPluginsConfigXML(Collection<Element> configXML, Simulation simulation, boolean visAvailable) { for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("plugin")) { // Read plugin class String pluginClassName = pluginElement.getText().trim(); /* Backwards compatibility: old visualizers were replaced */ if (pluginClassName.equals("se.sics.cooja.plugins.VisUDGM") || pluginClassName.equals("se.sics.cooja.plugins.VisBattery") || pluginClassName.equals("se.sics.cooja.plugins.VisTraffic") || pluginClassName.equals("se.sics.cooja.plugins.VisState") || pluginClassName.equals("se.sics.cooja.plugins.VisUDGM")) { logger.warn("Old simulation config detected: visualizers have been remade"); pluginClassName = "se.sics.cooja.plugins.Visualizer"; } Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass == null) { logger.fatal("Could not load plugin class: " + pluginClassName); return false; } // Parse plugin mote argument (if any) Mote mote = null; for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("mote_arg")) { int moteNr = Integer.parseInt(pluginSubElement.getText()); if (moteNr >= 0 && moteNr < simulation.getMotesCount()) { mote = simulation.getMote(moteNr); } } } /* Start plugin */ final Plugin startedPlugin = tryStartPlugin(pluginClass, this, simulation, mote); if (startedPlugin == null) { continue; } /* Apply plugin specific configuration */ for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("plugin_config")) { startedPlugin.setConfigXML(pluginSubElement.getChildren(), visAvailable); } } /* If Cooja not visualized, ignore window configuration */ if (startedPlugin.getGUI() == null) { continue; } // If plugin is visualizer plugin, parse visualization arguments new RunnableInEDT<Boolean>() { public Boolean work() { Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("width")) { size.width = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); // Save z order as temporary client property startedPlugin.getGUI().putClientProperty("zorder", zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getGUI().setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { try { startedPlugin.getGUI().setIcon(Boolean.parseBoolean(pluginSubElement.getText())); } catch (PropertyVetoException e) { } } } // For all visualized plugins, check if they have a zorder property try { for (JInternalFrame plugin : getDesktopPane().getAllFrames()) { if (plugin.getClientProperty("zorder") != null) { getDesktopPane().setComponentZOrder(plugin, ((Integer) plugin.getClientProperty("zorder")).intValue()); plugin.putClientProperty("zorder", null); } } } catch (Exception e) { } return true; } }.invokeAndWait(); } } return true; } public class ParseProjectsException extends Exception { public ParseProjectsException(String message) { super(message); } } public class ClassLoaderCreationException extends Exception { public ClassLoaderCreationException(String message) { super(message); } } public class SimulationCreationException extends Exception { public SimulationCreationException(String message) { super(message); } } public class PluginConstructionException extends Exception { public PluginConstructionException(String message) { super(message); } } /** * A simple error dialog with compilation output and stack trace. * * @param parentComponent * Parent component * @param title * Title of error window * @param exception * Exception causing window to be shown * @param retryAvailable * If true, a retry option is presented * @return Retry failed operation */ public static boolean showErrorDialog(final Component parentComponent, final String title, final Throwable exception, final boolean retryAvailable) { return new RunnableInEDT<Boolean>() { public Boolean work() { JTabbedPane tabbedPane = new JTabbedPane(); final JDialog errorDialog; if (parentComponent instanceof Dialog) { errorDialog = new JDialog((Dialog) parentComponent, title, true); } else if (parentComponent instanceof Frame) { errorDialog = new JDialog((Frame) parentComponent, title, true); } else { errorDialog = new JDialog((Frame) null, title); } Box buttonBox = Box.createHorizontalBox(); if (exception != null) { /* Compilation output */ MessageList compilationOutput = null; if (exception instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception).getCompilationOutput(); } else if (exception.getCause() != null && exception.getCause() instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception.getCause()).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception.getCause()).getCompilationOutput(); } if (compilationOutput != null) { compilationOutput.addPopupMenuItem(null, true); tabbedPane.addTab("Compilation output", null, new JScrollPane(compilationOutput), null); } /* Stack trace */ MessageList stackTrace = new MessageList(); PrintStream printStream = stackTrace.getInputStream(MessageList.NORMAL); exception.printStackTrace(printStream); stackTrace.addPopupMenuItem(null, true); tabbedPane.addTab("Java stack trace", null, new JScrollPane(stackTrace), null); /* Exception message */ buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(new JLabel(exception.getMessage())); buttonBox.add(Box.createHorizontalStrut(10)); } buttonBox.add(Box.createHorizontalGlue()); if (retryAvailable) { Action retryAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { errorDialog.setTitle("-RETRY-"); errorDialog.dispose(); } }; JButton retryButton = new JButton(retryAction); retryButton.setText("Retry Ctrl+R"); buttonBox.add(retryButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK, false), "retry"); errorDialog.getRootPane().getActionMap().put("retry", retryAction); } AbstractAction closeAction = new AbstractAction(){ public void actionPerformed(ActionEvent e) { errorDialog.dispose(); } }; JButton closeButton = new JButton(closeAction); closeButton.setText("Close"); buttonBox.add(closeButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "close"); errorDialog.getRootPane().getActionMap().put("close", closeAction); errorDialog.getRootPane().setDefaultButton(closeButton); errorDialog.getContentPane().add(BorderLayout.CENTER, tabbedPane); errorDialog.getContentPane().add(BorderLayout.SOUTH, buttonBox); errorDialog.setSize(700, 500); errorDialog.setLocationRelativeTo(parentComponent); errorDialog.setVisible(true); /* BLOCKS */ if (errorDialog.getTitle().equals("-RETRY-")) { return true; } return false; } }.invokeAndWait(); } /** * Runs work method in event dispatcher thread. * Worker method returns a value. * * @author Fredrik Osterlind */ public static abstract class RunnableInEDT<T> { private T val; /** * Work method to be implemented. * * @return Return value */ public abstract T work(); /** * Runs worker method in event dispatcher thread. * * @see #work() * @return Worker method return value */ public T invokeAndWait() { if(java.awt.EventQueue.isDispatchThread()) { return RunnableInEDT.this.work(); } try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { val = RunnableInEDT.this.work(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return val; } } /** * This method can be used by various different modules in the simulator to * indicate for example that a mote has been selected. All mote highlight * listeners will be notified. An example application of mote highlightinh is * a simulator visualizer that highlights the mote. * * @see #addMoteHighlightObserver(Observer) * @param m * Mote to highlight */ public void signalMoteHighlight(Mote m) { moteHighlightObservable.setChangedAndNotify(m); } /** * Adds directed relation between given motes. * * @param source Source mote * @param dest Destination mote */ public void addMoteRelation(Mote source, Mote dest) { if (source == null || dest == null) { return; } removeMoteRelation(source, dest); /* Unique relations */ moteRelations.add(new MoteRelation(source, dest)); moteRelationObservable.setChangedAndNotify(); } /** * Removes the relations between given motes. * * @param source Source mote * @param dest Destination mote */ public void removeMoteRelation(Mote source, Mote dest) { if (source == null || dest == null) { return; } MoteRelation[] arr = getMoteRelations(); for (MoteRelation r: arr) { if (r.source == source && r.dest == dest) { moteRelations.remove(r); } } moteRelationObservable.setChangedAndNotify(); } /** * @return All current mote relations. * * @see #addMoteRelationsObserver(Observer) */ public MoteRelation[] getMoteRelations() { MoteRelation[] arr = new MoteRelation[moteRelations.size()]; moteRelations.toArray(arr); return arr; } /** * Adds mote relation observer. * Typically used by visualizer plugins. * * @param newObserver Observer */ public void addMoteRelationsObserver(Observer newObserver) { moteRelationObservable.addObserver(newObserver); } /** * Removes mote relation observer. * Typically used by visualizer plugins. * * @param observer Observer */ public void deleteMoteRelationsObserver(Observer observer) { moteRelationObservable.deleteObserver(observer); } /** * Tries to convert given file to be "portable". * The portable path is either relative to Contiki, or to the configuration (.csc) file. * * If this method fails, it returns the original file. * * @param file Original file * @return Portable file, or original file is conversion failed */ public File createPortablePath(File file) { File portable = null; portable = createContikiRelativePath(file); if (portable != null) { /*logger.info("Generated Contiki relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } portable = createConfigRelativePath(file); if (portable != null) { /*logger.info("Generated config relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } logger.warn("Path is not portable: '" + file.getPath()); return file; } /** * Tries to restore a previously "portable" file to be "absolute". * If the given file already exists, no conversion is performed. * * @see #createPortablePath(File) * @param file Portable file * @return Absolute file */ public File restorePortablePath(File file) { if (file == null || file.exists()) { /* No conversion possible/needed */ return file; } File absolute = null; absolute = restoreContikiRelativePath(file); if (absolute != null) { /*logger.info("Restored Contiki relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } absolute = restoreConfigRelativePath(file); if (absolute != null) { /*logger.info("Restored config relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } /*logger.info("Portable path was not restored: '" + file.getPath());*/ return file; } private final static String PATH_CONTIKI_IDENTIFIER = "[CONTIKI_DIR]"; private File createContikiRelativePath(File file) { try { File contikiPath = new File(GUI.getExternalToolsSetting("PATH_CONTIKI", null)); String contikiCanonical = contikiPath.getCanonicalPath(); String fileCanonical = file.getCanonicalPath(); if (!fileCanonical.startsWith(contikiCanonical)) { /* File is not in a Contiki subdirectory */ /*logger.info("File is not in a Contiki subdirectory: " + file.getAbsolutePath());*/ return null; } /* Replace Contiki's canonical path with Contiki identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(contikiCanonical), java.util.regex.Matcher.quoteReplacement(PATH_CONTIKI_IDENTIFIER)); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreContikiRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to Contiki relative path: " + e1.getMessage());*/ return null; } } private File restoreContikiRelativePath(File portable) { try { File contikiPath = new File(GUI.getExternalToolsSetting("PATH_CONTIKI", null)); String contikiCanonical = contikiPath.getCanonicalPath(); String portablePath = portable.getPath(); if (!portablePath.startsWith(PATH_CONTIKI_IDENTIFIER)) { return null; } File absolute = new File(portablePath.replace(PATH_CONTIKI_IDENTIFIER, contikiCanonical)); return absolute; } catch (IOException e) { return null; } } private final static String PATH_CONFIG_IDENTIFIER = "[CONFIG_DIR]"; public File currentConfigFile = null; /* Used to generate config relative paths */ private File createConfigRelativePath(File file) { String id = PATH_CONFIG_IDENTIFIER; if (currentConfigFile == null) { return null; } try { File configPath = currentConfigFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String configCanonical = configPath.getCanonicalPath(); String fileCanonical = file.getCanonicalPath(); if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow one parent directory */ configCanonical = configPath.getParentFile().getCanonicalPath(); id += "/.."; } if (!fileCanonical.startsWith(configCanonical)) { /* File is not in a config subdirectory */ logger.info("File is not in a config subdirectory: " + file.getAbsolutePath()); return null; } /* Replace config's canonical path with config identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(configCanonical), java.util.regex.Matcher.quoteReplacement(id)); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreConfigRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to config relative path: " + e1.getMessage());*/ return null; } } private File restoreConfigRelativePath(File portable) { if (currentConfigFile == null) { return null; } File configPath = currentConfigFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String portablePath = portable.getPath(); if (!portablePath.startsWith(PATH_CONFIG_IDENTIFIER)) { return null; } File absolute = new File(portablePath.replace(PATH_CONFIG_IDENTIFIER, configPath.getAbsolutePath())); return absolute; } private static JProgressBar PROGRESS_BAR = null; public static void setProgressMessage(String msg) { if (PROGRESS_BAR != null && PROGRESS_BAR.isShowing()) { PROGRESS_BAR.setString(msg); PROGRESS_BAR.setStringPainted(true); } } public interface HasQuickHelp { /** * @return Quick help. May be HTML formatted, but must not include the * document html-tags. */ public String getQuickHelp(); } /** * Load quick help for given object or identifier. Note that this method does not * show the quick help pane. * * @param obj If string: help identifier. Else, the class name of the argument * is used as help identifier. */ public void loadQuickHelp(final Object obj) { if (obj == null) { return; } String key; if (obj instanceof String) { key = (String) obj; } else { key = obj.getClass().getName(); } String help = null; if (obj instanceof HasQuickHelp) { help = ((HasQuickHelp) obj).getQuickHelp(); } else { if (quickHelpProperties == null) { /* Load quickhelp.txt */ try { quickHelpProperties = new Properties(); quickHelpProperties.load(new FileReader("quickhelp.txt")); } catch (Exception e) { quickHelpProperties = null; help = "<html><b>Failed to read quickhelp.txt:</b><p>" + e.getMessage() + "</html>"; } } if (quickHelpProperties != null) { help = quickHelpProperties.getProperty(key); } } if (help != null) { quickHelpTextPane.setText("<html>" + help + "</html>"); } else { quickHelpTextPane.setText( "<html><b>" + getDescriptionOf(obj) +"</b>" + "<p>No help available</html>"); } quickHelpTextPane.setCaretPosition(0); } /* GUI actions */ abstract class GUIAction extends AbstractAction { public GUIAction(String name) { super(name); } public GUIAction(String name, int nmenomic) { this(name); putValue(Action.MNEMONIC_KEY, nmenomic); } public GUIAction(String name, KeyStroke accelerator) { this(name); putValue(Action.ACCELERATOR_KEY, accelerator); } public GUIAction(String name, int nmenomic, KeyStroke accelerator) { this(name, nmenomic); putValue(Action.ACCELERATOR_KEY, accelerator); } public abstract boolean shouldBeEnabled(); } GUIAction newSimulationAction = new GUIAction("New simulation", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { myGUI.doCreateSimulation(true); } public boolean shouldBeEnabled() { return true; } }; GUIAction closeSimulationAction = new GUIAction("Close simulation", KeyEvent.VK_C) { public void actionPerformed(ActionEvent e) { myGUI.doRemoveSimulation(true); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction reloadSimulationAction = new GUIAction("keep random seed", KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { if (getSimulation() == null) { /* Reload last opened simulation */ final File file = getLastOpenedFile(); new Thread(new Runnable() { public void run() { myGUI.doLoadConfig(true, true, file); } }).start(); return; } /* Reload current simulation */ long seed = getSimulation().getRandomSeed(); reloadCurrentSimulation(getSimulation().isRunning(), seed); } public boolean shouldBeEnabled() { return true; } }; GUIAction reloadRandomSimulationAction = new GUIAction("new random seed", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)) { public void actionPerformed(ActionEvent e) { /* Replace seed before reloading */ if (getSimulation() != null) { getSimulation().setRandomSeed(getSimulation().getRandomSeed()+1); reloadSimulationAction.actionPerformed(null); } } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction saveSimulationAction = new GUIAction("Save simulation", KeyEvent.VK_S) { public void actionPerformed(ActionEvent e) { myGUI.doSaveConfig(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return getSimulation() != null; } }; GUIAction closePluginsAction = new GUIAction("Close all plugins") { public void actionPerformed(ActionEvent e) { Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } } public boolean shouldBeEnabled() { return !startedPlugins.isEmpty(); } }; GUIAction exitCoojaAction = new GUIAction("Exit", KeyEvent.VK_X, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { myGUI.doQuit(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return true; } }; GUIAction startStopSimulationAction = new GUIAction("Start/Stop simulation", KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)) { public void actionPerformed(ActionEvent e) { /* Start/Stop current simulation */ Simulation s = getSimulation(); if (s == null) { return; } if (s.isRunning()) { s.stopSimulation(); } else { s.startSimulation(); } } public void setEnabled(boolean newValue) { if (getSimulation() == null) { putValue(NAME, "Start/Stop simulation"); } else if (getSimulation().isRunning()) { putValue(NAME, "Stop simulation"); } else { putValue(NAME, "Start simulation"); } super.setEnabled(newValue); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; class StartPluginGUIAction extends GUIAction { public StartPluginGUIAction(String name) { super(name); } public void actionPerformed(final ActionEvent e) { new Thread(new Runnable() { public void run() { Class<Plugin> pluginClass = (Class<Plugin>) ((JMenuItem) e.getSource()).getClientProperty("class"); Mote mote = (Mote) ((JMenuItem) e.getSource()).getClientProperty("mote"); tryStartPlugin(pluginClass, myGUI, mySimulation, mote); } }).start(); } public boolean shouldBeEnabled() { return getSimulation() != null; } } GUIAction removeAllMotesAction = new GUIAction("Remove all motes") { public void actionPerformed(ActionEvent e) { Simulation s = getSimulation(); if (s.isRunning()) { s.stopSimulation(); } while (s.getMotesCount() > 0) { s.removeMote(getSimulation().getMote(0)); } } public boolean shouldBeEnabled() { Simulation s = getSimulation(); return s != null && s.getMotesCount() > 0; } }; GUIAction showQuickHelpAction = new GUIAction("Quick help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { public void actionPerformed(ActionEvent e) { if (!(e.getSource() instanceof JCheckBoxMenuItem)) { return; } boolean show = ((JCheckBoxMenuItem) e.getSource()).isSelected(); quickHelpTextPane.setVisible(show); quickHelpScroll.setVisible(show); ((JPanel)frame.getContentPane()).revalidate(); updateDesktopSize(getDesktopPane()); } public boolean shouldBeEnabled() { return true; } }; GUIAction showKeyboardShortcutsAction = new GUIAction("Keyboard shortcuts") { public void actionPerformed(ActionEvent e) { loadQuickHelp("KEYBOARD_SHORTCUTS"); JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } public boolean shouldBeEnabled() { return true; } }; GUIAction showBufferSettingsAction = new GUIAction("Buffer sizes") { public void actionPerformed(ActionEvent e) { if (mySimulation == null) { return; } BufferSettings.showDialog(myDesktopPane, mySimulation); } public boolean shouldBeEnabled() { return mySimulation != null; } }; }
added experimental feature: generate executable JAR from current simulation + made some methods public for accessing configuration state etc from outside the GUI class + minor bug fix in reparse projectes method
tools/cooja/java/se/sics/cooja/GUI.java
added experimental feature: generate executable JAR from current simulation
Java
mit
de349e4fc9c76f9be0a0cc5bebe27b488f4e724c
0
Innovimax-SARL/mix-them
package innovimax.mixthem.io; import java.io.IOException; /** * This interface provides for writing characters in an output stream. * @author Innovimax * @version 1.0 */ public interface IOutputChar { /** * Writes a single character. * @param c The character as an int to be written * @throws IOException - If an I/O error occurs */ void writeCharacter(int c) throws IOException; /** * Writes a portion of an array of characters. * @param buffer Buffer of characters * @param len Number of characters to write * @throws IOException - If an I/O error occurs */ void writeCharacters(char[] buffer, int len) throws IOException; /** * Closes this output and releases any system resources associated with it. * @throws IOException - If an I/O error occurs */ void close() throws IOException; }
src/main/java/innovimax/mixthem/io/IOutputChar.java
package innovimax.mixthem.io; import java.io.IOException; /** * This interface provides for writing lines in an output stream. * @author Innovimax * @version 1.0 */ public interface IOutputChar { /** * Writes a single character. * @param c The character as an int to be written * @throws IOException - If an I/O error occurs */ void writeCharacter(int c) throws IOException; /** * Writes a portion of an array of characters. * @param buffer Buffer of characters * @param len Number of characters to write * @throws IOException - If an I/O error occurs */ void writeCharacters(char[] buffer, int len) throws IOException; /** * Closes this output and releases any system resources associated with it. * @throws IOException - If an I/O error occurs */ void close() throws IOException; }
Update IOutputChar.java
src/main/java/innovimax/mixthem/io/IOutputChar.java
Update IOutputChar.java
Java
mit
4376121714f3dec57a9143a86f8661c001f45115
0
TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android
/* DConnectMessageService.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.res.AssetManager; import android.os.Build; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.event.cache.MemoryCacheController; import org.deviceconnect.android.localoauth.CheckAccessTokenResult; import org.deviceconnect.android.localoauth.ClientPackageInfo; import org.deviceconnect.android.localoauth.LocalOAuth2Main; import org.deviceconnect.android.manager.DevicePluginManager.DevicePluginEventListener; import org.deviceconnect.android.manager.event.EventBroker; import org.deviceconnect.android.manager.event.EventSessionTable; import org.deviceconnect.android.manager.hmac.HmacManager; import org.deviceconnect.android.manager.policy.OriginValidator; import org.deviceconnect.android.manager.profile.AuthorizationProfile; import org.deviceconnect.android.manager.profile.DConnectAvailabilityProfile; import org.deviceconnect.android.manager.profile.DConnectDeliveryProfile; import org.deviceconnect.android.manager.profile.DConnectServiceDiscoveryProfile; import org.deviceconnect.android.manager.profile.DConnectSystemProfile; import org.deviceconnect.android.manager.request.DConnectRequest; import org.deviceconnect.android.manager.request.DConnectRequestManager; import org.deviceconnect.android.manager.request.RegisterNetworkServiceDiscovery; import org.deviceconnect.android.manager.setting.SettingActivity; import org.deviceconnect.android.manager.util.DConnectUtil; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.DConnectProfile; import org.deviceconnect.android.profile.DConnectProfileProvider; import org.deviceconnect.android.profile.spec.DConnectProfileSpec; import org.deviceconnect.android.profile.spec.parser.DConnectProfileSpecJsonParser; import org.deviceconnect.android.profile.spec.parser.DConnectProfileSpecJsonParserFactory; import org.deviceconnect.android.provider.FileManager; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * DConnectMessageを受信するサービス. * @author NTT DOCOMO, INC. */ public abstract class DConnectMessageService extends Service implements DConnectProfileProvider, DevicePluginEventListener { /** 匿名オリジン. */ public static final String ANONYMOUS_ORIGIN = "<anonymous>"; /** Notification ID.*/ private static final int ONGOING_NOTIFICATION_ID = 4035; /** プロファイル仕様定義ファイルの拡張子. */ private static final String SPEC_FILE_EXTENSION = ".json"; /** サービスIDやセッションキーを分割するセパレータ. */ public static final String SEPARATOR = "."; /** セッションキーとreceiverを分けるセパレータ. */ public static final String SEPARATOR_SESSION = "@"; /** リクエストコードのエラー値を定義. */ private static final int ERROR_CODE = Integer.MIN_VALUE; /** 起動用URIスキーム名. */ private static final String SCHEME_LAUNCH = "dconnect"; /** ロガー. */ protected final Logger mLogger = Logger.getLogger("dconnect.manager"); /** プロファイルインスタンスマップ. */ protected Map<String, DConnectProfile> mProfileMap = new HashMap<String, DConnectProfile>(); /** 最後に処理されるプロファイル. */ private DConnectProfile mDeliveryProfile; /** Origin妥当性確認クラス. */ private OriginValidator mOriginValidator; /** リクエスト管理クラス. */ protected DConnectRequestManager mRequestManager; /** デバイスプラグイン管理. */ protected DevicePluginManager mPluginMgr; /** DeviceConnectの設定. */ protected DConnectSettings mSettings; /** ファイル管理用プロバイダ. */ protected FileManager mFileMgr; /** Local OAuthのデータを管理するクラス. */ private DConnectLocalOAuth mLocalOAuth; /** HMAC管理クラス. */ private HmacManager mHmacManager; /** サーバの起動状態. */ protected boolean mRunningFlag; /** イベントセッション管理テーブル. */ protected final EventSessionTable mEventSessionTable = new EventSessionTable(); /** イベントブローカー. */ protected EventBroker mEventBroker; @Override public IBinder onBind(final Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); // イベント管理クラスの初期化 EventManager.INSTANCE.setController(new MemoryCacheController()); // Local OAuthの初期化 LocalOAuth2Main.initialize(getApplicationContext()); // DConnect設定 mSettings = DConnectSettings.getInstance(); mSettings.load(this); // ファイル管理クラス mFileMgr = new FileManager(this); // デバイスプラグインとのLocal OAuth情報 mLocalOAuth = new DConnectLocalOAuth(this); // デバイスプラグイン管理クラスの作成 mPluginMgr = ((DConnectApplication) getApplication()).getDevicePluginManager(); // イベントハンドラーの初期化 mEventBroker = new EventBroker(this, mEventSessionTable, mLocalOAuth, mPluginMgr); // プロファイルの追加 addProfile(new AuthorizationProfile()); addProfile(new DConnectAvailabilityProfile()); addProfile(new DConnectServiceDiscoveryProfile(null, mPluginMgr)); addProfile(new DConnectSystemProfile(this, mPluginMgr)); // dConnect Managerで処理せず、登録されたデバイスプラグインに処理させるプロファイル setDeliveryProfile(new DConnectDeliveryProfile(mPluginMgr, mLocalOAuth, mEventBroker, mSettings.requireOrigin())); loadProfileSpecs(); } @Override public void onDestroy() { stopDConnect(); LocalOAuth2Main.destroy(); super.onDestroy(); } @Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (!mRunningFlag) { return START_NOT_STICKY; } if (intent == null) { mLogger.warning("intent is null."); return START_STICKY; } String action = intent.getAction(); if (action == null) { mLogger.warning("action is null."); return START_STICKY; } String scheme = intent.getScheme(); if (SCHEME_LAUNCH.equals(scheme)) { String key = intent.getStringExtra(IntentDConnectMessage.EXTRA_KEY); String origin = intent.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN); if (key != null && !TextUtils.isEmpty(origin)) { mHmacManager.updateKey(origin, key); } return START_STICKY; } if (checkAction(action)) { onRequestReceive(intent); } else if (IntentDConnectMessage.ACTION_RESPONSE.equals(action)) { onResponseReceive(intent); } else if (IntentDConnectMessage.ACTION_EVENT.equals(action)) { onEventReceive(intent); } return START_STICKY; } /** * リクエスト用Intentを受領したときの処理を行う. * @param request リクエスト用Intent */ private void onRequestReceive(final Intent request) { // リクエストコードが定義されていない場合には無視 int requestCode = getRequestCode(request); if (requestCode == ERROR_CODE) { mLogger.warning("Illegal requestCode in onRequestReceive. requestCode=" + requestCode); return; } // 不要になったキャッシュファイルの削除を行う if (mFileMgr != null) { mFileMgr.checkAndRemove(); } // レスポンス用のIntentの用意 Intent response = new Intent(IntentDConnectMessage.ACTION_RESPONSE); response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_ERROR); response.putExtra(DConnectMessage.EXTRA_REQUEST_CODE, requestCode); // オリジンの正当性チェック String profileName = request.getStringExtra(DConnectMessage.EXTRA_PROFILE); String origin = request.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN); OriginValidator.OriginError error = mOriginValidator.checkOrigin(origin); switch (error) { case NOT_SPECIFIED: MessageUtils.setInvalidOriginError(response, "Origin is not specified."); sendResponse(request, response); return; case NOT_UNIQUE: MessageUtils.setInvalidOriginError(response, "The specified origin is not unique."); sendResponse(request, response); return; case NOT_ALLOWED: // NOTE: Local OAuth関連のAPIに対する特別措置 DConnectProfile profile = getProfile(profileName); if (profile != null && profile instanceof AuthorizationProfile) { ((AuthorizationProfile) profile).onInvalidOrigin(request, response); } MessageUtils.setInvalidOriginError(response, "The specified origin is not allowed."); sendResponse(request, response); return; case NONE: if (origin == null && !mSettings.requireOrigin()) { request.putExtra(IntentDConnectMessage.EXTRA_ORIGIN, ANONYMOUS_ORIGIN); } break; default: break; } if (profileName == null) { MessageUtils.setNotSupportProfileError(response); sendResponse(request, response); return; } if (mSettings.isUseALocalOAuth()) { // アクセストークンの取得 String accessToken = request.getStringExtra(AuthorizationProfile.PARAM_ACCESS_TOKEN); CheckAccessTokenResult result = LocalOAuth2Main.checkAccessToken(accessToken, profileName.toLowerCase(), DConnectLocalOAuth.IGNORE_PROFILES); if (result.checkResult()) { executeRequest(request, response); } else { if (accessToken == null) { MessageUtils.setEmptyAccessTokenError(response); } else if (!result.isExistAccessToken()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistClientId()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistScope()) { MessageUtils.setScopeError(response); } else if (!result.isNotExpired()) { MessageUtils.setExpiredAccessTokenError(response); } else { MessageUtils.setAuthorizationError(response); } sendResponse(request, response); } } else { executeRequest(request, response); } } /** * レスポンス受信ハンドラー. * @param response レスポンス用Intent */ private void onResponseReceive(final Intent response) { // リクエストコードが定義されていない場合にはエラー int requestCode = getRequestCode(response); if (requestCode == ERROR_CODE) { mLogger.warning("Illegal requestCode in onResponseReceive. requestCode=" + requestCode); return; } // レスポンスをリクエスト管理クラスに渡す mRequestManager.setResponse(response); } /** * イベントメッセージ受信ハンドラー. * @param event イベント用Intent */ private void onEventReceive(final Intent event) { mEventBroker.onEvent(event); } /** * リクエストを実行する. * @param request リクエスト * @param response レスポンス */ private void executeRequest(final Intent request, final Intent response) { // リクエストにDeviceConnectManagerの情報を付加する request.putExtra(DConnectMessage.EXTRA_PRODUCT, getString(R.string.app_name)); request.putExtra(DConnectMessage.EXTRA_VERSION, DConnectUtil.getVersionName(this)); DConnectProfile profile = getProfile(request); if (profile != null && !isDeliveryRequest(request)) { if (profile.onRequest(request, response)) { sendResponse(request, response); } } else { sendDeliveryProfile(request, response); } } /** * 指定されたリクエストがデバイスプラグインに配送するリクエストか確認する. * @param request リクエスト * @return プラグインに配送する場合にはtrue、それ以外はfalse */ private boolean isDeliveryRequest(final Intent request) { return DConnectSystemProfile.isWakeUpRequest(request); } /** * リクエストを追加する. * @param request 追加するリクエスト */ public void addRequest(final DConnectRequest request) { mRequestManager.addRequest(request); } private void loadProfileSpecs() { for (DConnectProfile profile : mProfileMap.values()) { final String profileName = profile.getProfileName(); try { profile.setProfileSpec(loadProfileSpec(profileName)); mLogger.info("Loaded a profile spec: " + profileName); } catch (IOException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } catch (JSONException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } } } private DConnectProfileSpec loadProfileSpec(final String profileName) throws IOException, JSONException { AssetManager assets = getAssets(); String path = findProfileSpecPath(assets, profileName); if (path == null) { return null; } String json = loadFile(assets.open(path)); DConnectProfileSpecJsonParser parser = DConnectProfileSpecJsonParserFactory.getDefaultFactory().createParser(); return parser.parseJson(new JSONObject(json)); } private static String findProfileSpecPath(final AssetManager assets, final String profileName) throws IOException { String[] fileNames = assets.list("api"); if (fileNames == null) { return null; } for (String fileFullName : fileNames) { if (!fileFullName.endsWith(SPEC_FILE_EXTENSION)) { continue; } String fileName = fileFullName.substring(0, fileFullName.length() - SPEC_FILE_EXTENSION.length()); if (fileName.equalsIgnoreCase(profileName)) { return "api/" + fileFullName; } } throw new FileNotFoundException("A spec file is not found: " + profileName); } private static String loadFile(final InputStream in) throws IOException { try { byte[] buf = new byte[1024]; int len; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); } return new String(baos.toByteArray()); } finally { in.close(); } } @Override public List<DConnectProfile> getProfileList() { return new ArrayList<>(mProfileMap.values()); } @Override public void addProfile(final DConnectProfile profile) { if (profile != null) { profile.setContext(this); mProfileMap.put(profile.getProfileName(), profile); } } @Override public void removeProfile(final DConnectProfile profile) { if (profile != null) { mProfileMap.remove(profile.getProfileName()); } } @Override public DConnectProfile getProfile(final String name) { if (name == null) { return null; } return mProfileMap.get(name); } /** * リクエスト用Intentからプロファイルを取得する. * @param request リクエスト用Intent * @return プロファイル */ private DConnectProfile getProfile(final Intent request) { return getProfile(DConnectProfile.getProfile(request)); } /** * リクエスト用Intentからプロファイル名を取得する. * @param request リクエスト用Intent * @return プロファイル名 */ protected String parseProfileName(final Intent request) { return DConnectProfile.getProfile(request); } /** * レスポンス用Intentからリクエストコードを取得する. * @param response レスポンス用Intent * @return リクエストコード */ private int getRequestCode(final Intent response) { return response.getIntExtra(IntentDConnectMessage.EXTRA_REQUEST_CODE, ERROR_CODE); } /** * プロファイル処理が行われなかったときに呼び出されるプロファイルを設定する. * @param profile プロファイル */ private void setDeliveryProfile(final DConnectProfile profile) { if (profile != null) { profile.setContext(this); mDeliveryProfile = profile; } } @Override public void onDeviceFound(final DevicePlugin plugin) { RegisterNetworkServiceDiscovery req = new RegisterNetworkServiceDiscovery(); req.setContext(this); req.setDestination(plugin); req.setDevicePluginManager(mPluginMgr); addRequest(req); } @Override public void onDeviceLost(final DevicePlugin plugin) { mLocalOAuth.deleteOAuthDatas(plugin.getPluginId()); } /** * 指定されたアクションがdConnectのアクションをチェックする. * @param action アクション * @return dConnectのアクションの場合はtrue, それ以外はfalse */ private boolean checkAction(final String action) { return (action.equals(IntentDConnectMessage.ACTION_GET) || action.equals(IntentDConnectMessage.ACTION_PUT) || action.equals(IntentDConnectMessage.ACTION_POST) || action.equals(IntentDConnectMessage.ACTION_DELETE)); } /** * DConnectManagerを起動する。 */ protected void startDConnect() { mHmacManager = new HmacManager(this); mRequestManager = new DConnectRequestManager(); mOriginValidator = new OriginValidator(this, mSettings.requireOrigin(), mSettings.isBlockingOrigin()); mPluginMgr.setEventListener(this); showNotification(); } /** * DConnectManagerを停止する. */ protected void stopDConnect() { sendTerminateEvent(); mPluginMgr.setEventListener(null); if (mRequestManager != null) { mRequestManager.shutdown(); } hideNotification(); } /** * 全デバイスプラグインに対して、Device Connect Manager終了通知を行う. */ private void sendTerminateEvent() { List<DevicePlugin> plugins = mPluginMgr.getDevicePlugins(); for (DevicePlugin plugin : plugins) { if (plugin.getPluginId() != null) { Intent request = new Intent(); request.setComponent(plugin.getComponentName()); request.setAction(IntentDConnectMessage.ACTION_MANAGER_TERMINATED); request.putExtra("pluginId", plugin.getPluginId()); sendBroadcast(request); } } } /** * 各デバイスプラグインにリクエストを受け渡す. * * ここで、アクセストークンをリクエストに付加する。 * また、アクセストークンが存在しない場合には、デバイスプラグインにアクセストークンの取得要求を行う。 * * @param request リクエスト * @param response レスポンス */ protected void sendDeliveryProfile(final Intent request, final Intent response) { mDeliveryProfile.onRequest(request, response); } /** * サービスをフォアグランドに設定する。 */ protected void showNotification() { Intent notificationIntent = new Intent(getApplicationContext(), SettingActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( getApplicationContext(), 0, notificationIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); builder.setContentIntent(pendingIntent); builder.setTicker(getString(R.string.app_name)); builder.setContentTitle(getString(R.string.app_name)); builder.setContentText(DConnectUtil.getIPAddress(this) + ":" + mSettings.getPort()); int iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.drawable.icon : R.drawable.on_icon; builder.setSmallIcon(iconType); startForeground(ONGOING_NOTIFICATION_ID, builder.build()); } /** * フォアグランドを停止する。 */ protected void hideNotification() { stopForeground(true); } /** * レスポンス用のIntentを作成する. * @param request リクエスト * @param response リクエストに対応するレスポンス * @return 送信するレスポンス用Intent */ protected Intent createResponseIntent(final Intent request, final Intent response) { int requestCode = request.getIntExtra( IntentDConnectMessage.EXTRA_REQUEST_CODE, ERROR_CODE); ComponentName cn = request .getParcelableExtra(IntentDConnectMessage.EXTRA_RECEIVER); Intent intent = new Intent(response); intent.putExtra(IntentDConnectMessage.EXTRA_REQUEST_CODE, requestCode); intent.putExtra(IntentDConnectMessage.EXTRA_PRODUCT, getString(R.string.app_name)); intent.putExtra(IntentDConnectMessage.EXTRA_VERSION, DConnectUtil.getVersionName(this)); // HMAC生成 String origin = request.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN); if (origin == null) { String accessToken = request.getStringExtra(DConnectMessage.EXTRA_ACCESS_TOKEN); if (accessToken != null) { origin = findOrigin(accessToken); } } if (origin != null) { if (mHmacManager.usesHmac(origin)) { String nonce = request.getStringExtra(IntentDConnectMessage.EXTRA_NONCE); if (nonce != null) { String hmac = mHmacManager.generateHmac(origin, nonce); if (hmac != null) { intent.putExtra(IntentDConnectMessage.EXTRA_HMAC, hmac); } } } } else { mLogger.warning("Origin is not found."); } intent.setComponent(cn); return intent; } /** * 指定されたアクセストークンのOriginを取得する. * * @param accessToken アクセストークン * @return Origin */ private String findOrigin(final String accessToken) { ClientPackageInfo packageInfo = LocalOAuth2Main.findClientPackageInfoByAccessToken(accessToken); if (packageInfo == null) { return null; } // Origin is a package name of LocalOAuth client. return packageInfo.getPackageInfo().getPackageName(); } /** * リクエストの送信元にレスポンスを返却する. * @param request 送信元のリクエスト * @param response 返却するレスポンス */ public void sendResponse(final Intent request, final Intent response) { Intent intent = createResponseIntent(request, response); if (intent.getComponent() == null) { return; } sendBroadcast(intent); } /** * イベントメッセージを送信する. * @param receiver 送信先のBroadcastReceiver * @param event 送信するイベントメッセージ */ public void sendEvent(final String receiver, final Intent event) { if (BuildConfig.DEBUG) { mLogger.info(String.format("sendEvent: %s intent: %s", receiver, event.getExtras())); } Intent targetIntent = new Intent(event); targetIntent.setComponent(ComponentName.unflattenFromString(receiver)); sendBroadcast(targetIntent); } /** * オリジン要求設定を取得する. * @return オリジンが必要な場合はtrue、それ以外はfalse */ public boolean requiresOrigin() { return mSettings.requireOrigin(); } /** * Local OAuth要求設定を取得する. * @return Local OAuthが必要な場合はtrue、それ以外はfalse */ public boolean usesLocalOAuth() { return mSettings.isUseALocalOAuth(); } }
dConnectManager/dConnectManager/app/src/main/java/org/deviceconnect/android/manager/DConnectMessageService.java
/* DConnectMessageService.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.res.AssetManager; import android.os.Build; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.event.cache.MemoryCacheController; import org.deviceconnect.android.localoauth.CheckAccessTokenResult; import org.deviceconnect.android.localoauth.ClientPackageInfo; import org.deviceconnect.android.localoauth.LocalOAuth2Main; import org.deviceconnect.android.manager.DevicePluginManager.DevicePluginEventListener; import org.deviceconnect.android.manager.event.EventBroker; import org.deviceconnect.android.manager.event.EventSessionTable; import org.deviceconnect.android.manager.hmac.HmacManager; import org.deviceconnect.android.manager.policy.OriginValidator; import org.deviceconnect.android.manager.profile.AuthorizationProfile; import org.deviceconnect.android.manager.profile.DConnectAvailabilityProfile; import org.deviceconnect.android.manager.profile.DConnectDeliveryProfile; import org.deviceconnect.android.manager.profile.DConnectServiceDiscoveryProfile; import org.deviceconnect.android.manager.profile.DConnectSystemProfile; import org.deviceconnect.android.manager.request.DConnectRequest; import org.deviceconnect.android.manager.request.DConnectRequestManager; import org.deviceconnect.android.manager.request.RegisterNetworkServiceDiscovery; import org.deviceconnect.android.manager.setting.SettingActivity; import org.deviceconnect.android.manager.util.DConnectUtil; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.DConnectProfile; import org.deviceconnect.android.profile.DConnectProfileProvider; import org.deviceconnect.android.profile.spec.DConnectProfileSpec; import org.deviceconnect.android.profile.spec.parser.DConnectProfileSpecJsonParser; import org.deviceconnect.android.profile.spec.parser.DConnectProfileSpecJsonParserFactory; import org.deviceconnect.android.provider.FileManager; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * DConnectMessageを受信するサービス. * @author NTT DOCOMO, INC. */ public abstract class DConnectMessageService extends Service implements DConnectProfileProvider, DevicePluginEventListener { /** 匿名オリジン. */ public static final String ANONYMOUS_ORIGIN = "<anonymous>"; /** Notification ID.*/ private static final int ONGOING_NOTIFICATION_ID = 4035; /** プロファイル仕様定義ファイルの拡張子. */ private static final String SPEC_FILE_EXTENSION = ".json"; /** サービスIDやセッションキーを分割するセパレータ. */ public static final String SEPARATOR = "."; /** セッションキーとreceiverを分けるセパレータ. */ public static final String SEPARATOR_SESSION = "@"; /** リクエストコードのエラー値を定義. */ private static final int ERROR_CODE = Integer.MIN_VALUE; /** 起動用URIスキーム名. */ private static final String SCHEME_LAUNCH = "dconnect"; /** ロガー. */ protected final Logger mLogger = Logger.getLogger("dconnect.manager"); /** プロファイルインスタンスマップ. */ protected Map<String, DConnectProfile> mProfileMap = new HashMap<String, DConnectProfile>(); /** 最後に処理されるプロファイル. */ private DConnectProfile mDeliveryProfile; /** Origin妥当性確認クラス. */ private OriginValidator mOriginValidator; /** リクエスト管理クラス. */ protected DConnectRequestManager mRequestManager; /** デバイスプラグイン管理. */ protected DevicePluginManager mPluginMgr; /** DeviceConnectの設定. */ protected DConnectSettings mSettings; /** ファイル管理用プロバイダ. */ protected FileManager mFileMgr; /** Local OAuthのデータを管理するクラス. */ private DConnectLocalOAuth mLocalOAuth; /** HMAC管理クラス. */ private HmacManager mHmacManager; /** サーバの起動状態. */ protected boolean mRunningFlag; /** イベントセッション管理テーブル. */ protected final EventSessionTable mEventSessionTable = new EventSessionTable(); /** イベントブローカー. */ protected EventBroker mEventBroker; @Override public IBinder onBind(final Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); // イベント管理クラスの初期化 EventManager.INSTANCE.setController(new MemoryCacheController()); // Local OAuthの初期化 LocalOAuth2Main.initialize(getApplicationContext()); // DConnect設定 mSettings = DConnectSettings.getInstance(); mSettings.load(this); // ファイル管理クラス mFileMgr = new FileManager(this); // デバイスプラグインとのLocal OAuth情報 mLocalOAuth = new DConnectLocalOAuth(this); // デバイスプラグイン管理クラスの作成 mPluginMgr = ((DConnectApplication) getApplication()).getDevicePluginManager(); // イベントハンドラーの初期化 mEventBroker = new EventBroker(this, mEventSessionTable, mLocalOAuth, mPluginMgr); // プロファイルの追加 addProfile(new AuthorizationProfile()); addProfile(new DConnectAvailabilityProfile()); addProfile(new DConnectServiceDiscoveryProfile(null, mPluginMgr)); addProfile(new DConnectSystemProfile(this, mPluginMgr)); // dConnect Managerで処理せず、登録されたデバイスプラグインに処理させるプロファイル setDeliveryProfile(new DConnectDeliveryProfile(mPluginMgr, mLocalOAuth, mEventBroker, mSettings.requireOrigin())); loadProfileSpecs(); } @Override public void onDestroy() { stopDConnect(); LocalOAuth2Main.destroy(); super.onDestroy(); } @Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (!mRunningFlag) { return START_NOT_STICKY; } if (intent == null) { mLogger.warning("intent is null."); return START_STICKY; } String action = intent.getAction(); if (action == null) { mLogger.warning("action is null."); return START_STICKY; } String scheme = intent.getScheme(); if (SCHEME_LAUNCH.equals(scheme)) { String key = intent.getStringExtra(IntentDConnectMessage.EXTRA_KEY); String origin = intent.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN); if (key != null && !TextUtils.isEmpty(origin)) { mHmacManager.updateKey(origin, key); } return START_STICKY; } if (checkAction(action)) { onRequestReceive(intent); } else if (IntentDConnectMessage.ACTION_RESPONSE.equals(action)) { onResponseReceive(intent); } else if (IntentDConnectMessage.ACTION_EVENT.equals(action)) { onEventReceive(intent); } return START_STICKY; } /** * リクエスト用Intentを受領したときの処理を行う. * @param request リクエスト用Intent */ private void onRequestReceive(final Intent request) { // リクエストコードが定義されていない場合には無視 int requestCode = getRequestCode(request); if (requestCode == ERROR_CODE) { mLogger.warning("Illegal requestCode in onRequestReceive. requestCode=" + requestCode); return; } // 不要になったキャッシュファイルの削除を行う if (mFileMgr != null) { mFileMgr.checkAndRemove(); } // レスポンス用のIntentの用意 Intent response = new Intent(IntentDConnectMessage.ACTION_RESPONSE); response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_ERROR); response.putExtra(DConnectMessage.EXTRA_REQUEST_CODE, requestCode); // オリジンの正当性チェック String profileName = request.getStringExtra(DConnectMessage.EXTRA_PROFILE); String origin = request.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN); OriginValidator.OriginError error = mOriginValidator.checkOrigin(origin); switch (error) { case NOT_SPECIFIED: MessageUtils.setInvalidOriginError(response, "Origin is not specified."); sendResponse(request, response); return; case NOT_UNIQUE: MessageUtils.setInvalidOriginError(response, "The specified origin is not unique."); sendResponse(request, response); return; case NOT_ALLOWED: // NOTE: Local OAuth関連のAPIに対する特別措置 DConnectProfile profile = getProfile(profileName); if (profile != null && profile instanceof AuthorizationProfile) { ((AuthorizationProfile) profile).onInvalidOrigin(request, response); } MessageUtils.setInvalidOriginError(response, "The specified origin is not allowed."); sendResponse(request, response); return; case NONE: if (origin == null && !mSettings.requireOrigin()) { request.putExtra(IntentDConnectMessage.EXTRA_ORIGIN, ANONYMOUS_ORIGIN); } break; default: break; } if (profileName == null) { MessageUtils.setNotSupportProfileError(response); sendResponse(request, response); return; } if (mSettings.isUseALocalOAuth()) { // アクセストークンの取得 String accessToken = request.getStringExtra(AuthorizationProfile.PARAM_ACCESS_TOKEN); CheckAccessTokenResult result = LocalOAuth2Main.checkAccessToken(accessToken, profileName.toLowerCase(), DConnectLocalOAuth.IGNORE_PROFILES); if (result.checkResult()) { executeRequest(request, response); } else { if (accessToken == null) { MessageUtils.setEmptyAccessTokenError(response); } else if (!result.isExistAccessToken()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistClientId()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistScope()) { MessageUtils.setScopeError(response); } else if (!result.isNotExpired()) { MessageUtils.setExpiredAccessTokenError(response); } else { MessageUtils.setAuthorizationError(response); } sendResponse(request, response); } } else { executeRequest(request, response); } } /** * レスポンス受信ハンドラー. * @param response レスポンス用Intent */ private void onResponseReceive(final Intent response) { // リクエストコードが定義されていない場合にはエラー int requestCode = getRequestCode(response); if (requestCode == ERROR_CODE) { mLogger.warning("Illegal requestCode in onResponseReceive. requestCode=" + requestCode); return; } // レスポンスをリクエスト管理クラスに渡す mRequestManager.setResponse(response); } /** * イベントメッセージ受信ハンドラー. * @param event イベント用Intent */ private void onEventReceive(final Intent event) { mEventBroker.onEvent(event); } /** * リクエストを実行する. * @param request リクエスト * @param response レスポンス */ private void executeRequest(final Intent request, final Intent response) { // リクエストにDeviceConnectManagerの情報を付加する request.putExtra(DConnectMessage.EXTRA_PRODUCT, getString(R.string.app_name)); request.putExtra(DConnectMessage.EXTRA_VERSION, DConnectUtil.getVersionName(this)); DConnectProfile profile = getProfile(request); if (profile != null && !isDeliveryRequest(request)) { if (profile.onRequest(request, response)) { sendResponse(request, response); } } else { sendDeliveryProfile(request, response); } } /** * 指定されたリクエストがデバイスプラグインに配送するリクエストか確認する. * @param request リクエスト * @return プラグインに配送する場合にはtrue、それ以外はfalse */ private boolean isDeliveryRequest(final Intent request) { return DConnectSystemProfile.isWakeUpRequest(request); } /** * リクエストを追加する. * @param request 追加するリクエスト */ public void addRequest(final DConnectRequest request) { mRequestManager.addRequest(request); } private void loadProfileSpecs() { for (DConnectProfile profile : mProfileMap.values()) { final String profileName = profile.getProfileName(); try { profile.setProfileSpec(loadProfileSpec(profileName)); mLogger.info("Loaded a profile spec: " + profileName); } catch (IOException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } catch (JSONException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } } } private DConnectProfileSpec loadProfileSpec(final String profileName) throws IOException, JSONException { AssetManager assets = getAssets(); String path = findProfileSpecPath(assets, profileName); if (path == null) { return null; } String json = loadFile(assets.open(path)); DConnectProfileSpecJsonParser parser = DConnectProfileSpecJsonParserFactory.getDefaultFactory().createParser(); return parser.parseJson(new JSONObject(json)); } private static String findProfileSpecPath(final AssetManager assets, final String profileName) throws IOException { String[] fileNames = assets.list("api"); if (fileNames == null) { return null; } for (String fileFullName : fileNames) { if (!fileFullName.endsWith(SPEC_FILE_EXTENSION)) { continue; } String fileName = fileFullName.substring(0, fileFullName.length() - SPEC_FILE_EXTENSION.length()); if (fileName.equalsIgnoreCase(profileName)) { return "api/" + fileFullName; } } throw new FileNotFoundException("A spec file is not found: " + profileName); } private static String loadFile(final InputStream in) throws IOException { try { byte[] buf = new byte[1024]; int len; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); } return new String(baos.toByteArray()); } finally { in.close(); } } @Override public List<DConnectProfile> getProfileList() { return new ArrayList<>(mProfileMap.values()); } @Override public void addProfile(final DConnectProfile profile) { if (profile != null) { profile.setContext(this); mProfileMap.put(profile.getProfileName(), profile); } } @Override public void removeProfile(final DConnectProfile profile) { if (profile != null) { mProfileMap.remove(profile.getProfileName()); } } @Override public DConnectProfile getProfile(final String name) { if (name == null) { return null; } return mProfileMap.get(name); } /** * リクエスト用Intentからプロファイルを取得する. * @param request リクエスト用Intent * @return プロファイル */ private DConnectProfile getProfile(final Intent request) { return getProfile(DConnectProfile.getProfile(request)); } /** * リクエスト用Intentからプロファイル名を取得する. * @param request リクエスト用Intent * @return プロファイル名 */ protected String parseProfileName(final Intent request) { return DConnectProfile.getProfile(request); } /** * レスポンス用Intentからリクエストコードを取得する. * @param response レスポンス用Intent * @return リクエストコード */ private int getRequestCode(final Intent response) { return response.getIntExtra(IntentDConnectMessage.EXTRA_REQUEST_CODE, ERROR_CODE); } /** * プロファイル処理が行われなかったときに呼び出されるプロファイルを設定する. * @param profile プロファイル */ private void setDeliveryProfile(final DConnectProfile profile) { if (profile != null) { profile.setContext(this); mDeliveryProfile = profile; } } @Override public void onDeviceFound(final DevicePlugin plugin) { RegisterNetworkServiceDiscovery req = new RegisterNetworkServiceDiscovery(); req.setContext(this); req.setDestination(plugin); req.setDevicePluginManager(mPluginMgr); addRequest(req); } @Override public void onDeviceLost(final DevicePlugin plugin) { mLocalOAuth.deleteOAuthDatas(plugin.getPluginId()); } /** * 指定されたアクションがdConnectのアクションをチェックする. * @param action アクション * @return dConnectのアクションの場合はtrue, それ以外はfalse */ private boolean checkAction(final String action) { return (action.equals(IntentDConnectMessage.ACTION_GET) || action.equals(IntentDConnectMessage.ACTION_PUT) || action.equals(IntentDConnectMessage.ACTION_POST) || action.equals(IntentDConnectMessage.ACTION_DELETE)); } /** * DConnectManagerを起動する。 */ protected void startDConnect() { mHmacManager = new HmacManager(this); mRequestManager = new DConnectRequestManager(); mOriginValidator = new OriginValidator(this, mSettings.requireOrigin(), mSettings.isBlockingOrigin()); mPluginMgr.setEventListener(this); showNotification(); } /** * DConnectManagerを停止する. */ protected void stopDConnect() { sendTerminateEvent(); mPluginMgr.setEventListener(null); mRequestManager.shutdown(); hideNotification(); } /** * 全デバイスプラグインに対して、Device Connect Manager終了通知を行う. */ private void sendTerminateEvent() { List<DevicePlugin> plugins = mPluginMgr.getDevicePlugins(); for (DevicePlugin plugin : plugins) { if (plugin.getPluginId() != null) { Intent request = new Intent(); request.setComponent(plugin.getComponentName()); request.setAction(IntentDConnectMessage.ACTION_MANAGER_TERMINATED); request.putExtra("pluginId", plugin.getPluginId()); sendBroadcast(request); } } } /** * 各デバイスプラグインにリクエストを受け渡す. * * ここで、アクセストークンをリクエストに付加する。 * また、アクセストークンが存在しない場合には、デバイスプラグインにアクセストークンの取得要求を行う。 * * @param request リクエスト * @param response レスポンス */ protected void sendDeliveryProfile(final Intent request, final Intent response) { mDeliveryProfile.onRequest(request, response); } /** * サービスをフォアグランドに設定する。 */ protected void showNotification() { Intent notificationIntent = new Intent(getApplicationContext(), SettingActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( getApplicationContext(), 0, notificationIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); builder.setContentIntent(pendingIntent); builder.setTicker(getString(R.string.app_name)); builder.setContentTitle(getString(R.string.app_name)); builder.setContentText(DConnectUtil.getIPAddress(this) + ":" + mSettings.getPort()); int iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.drawable.icon : R.drawable.on_icon; builder.setSmallIcon(iconType); startForeground(ONGOING_NOTIFICATION_ID, builder.build()); } /** * フォアグランドを停止する。 */ protected void hideNotification() { stopForeground(true); } /** * レスポンス用のIntentを作成する. * @param request リクエスト * @param response リクエストに対応するレスポンス * @return 送信するレスポンス用Intent */ protected Intent createResponseIntent(final Intent request, final Intent response) { int requestCode = request.getIntExtra( IntentDConnectMessage.EXTRA_REQUEST_CODE, ERROR_CODE); ComponentName cn = request .getParcelableExtra(IntentDConnectMessage.EXTRA_RECEIVER); Intent intent = new Intent(response); intent.putExtra(IntentDConnectMessage.EXTRA_REQUEST_CODE, requestCode); intent.putExtra(IntentDConnectMessage.EXTRA_PRODUCT, getString(R.string.app_name)); intent.putExtra(IntentDConnectMessage.EXTRA_VERSION, DConnectUtil.getVersionName(this)); // HMAC生成 String origin = request.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN); if (origin == null) { String accessToken = request.getStringExtra(DConnectMessage.EXTRA_ACCESS_TOKEN); if (accessToken != null) { origin = findOrigin(accessToken); } } if (origin != null) { if (mHmacManager.usesHmac(origin)) { String nonce = request.getStringExtra(IntentDConnectMessage.EXTRA_NONCE); if (nonce != null) { String hmac = mHmacManager.generateHmac(origin, nonce); if (hmac != null) { intent.putExtra(IntentDConnectMessage.EXTRA_HMAC, hmac); } } } } else { mLogger.warning("Origin is not found."); } intent.setComponent(cn); return intent; } /** * 指定されたアクセストークンのOriginを取得する. * * @param accessToken アクセストークン * @return Origin */ private String findOrigin(final String accessToken) { ClientPackageInfo packageInfo = LocalOAuth2Main.findClientPackageInfoByAccessToken(accessToken); if (packageInfo == null) { return null; } // Origin is a package name of LocalOAuth client. return packageInfo.getPackageInfo().getPackageName(); } /** * リクエストの送信元にレスポンスを返却する. * @param request 送信元のリクエスト * @param response 返却するレスポンス */ public void sendResponse(final Intent request, final Intent response) { Intent intent = createResponseIntent(request, response); if (intent.getComponent() == null) { return; } sendBroadcast(intent); } /** * イベントメッセージを送信する. * @param receiver 送信先のBroadcastReceiver * @param event 送信するイベントメッセージ */ public void sendEvent(final String receiver, final Intent event) { if (BuildConfig.DEBUG) { mLogger.info(String.format("sendEvent: %s intent: %s", receiver, event.getExtras())); } Intent targetIntent = new Intent(event); targetIntent.setComponent(ComponentName.unflattenFromString(receiver)); sendBroadcast(targetIntent); } /** * オリジン要求設定を取得する. * @return オリジンが必要な場合はtrue、それ以外はfalse */ public boolean requiresOrigin() { return mSettings.requireOrigin(); } /** * Local OAuth要求設定を取得する. * @return Local OAuthが必要な場合はtrue、それ以外はfalse */ public boolean usesLocalOAuth() { return mSettings.isUseALocalOAuth(); } }
Managerの初期起動後に、バックボタンでManagerを終了させるとDestroy処理で異常終了する不具合を修正。
dConnectManager/dConnectManager/app/src/main/java/org/deviceconnect/android/manager/DConnectMessageService.java
Managerの初期起動後に、バックボタンでManagerを終了させるとDestroy処理で異常終了する不具合を修正。
Java
mit
6db14f44b9c58923b6a7c76772cb1481e2d643e8
0
Squadity/bb-kit
package net.bolbat.kit.service; /** * {@link SampleService} exception. * * @author Alexandr Bolbat */ public class SampleServiceException extends ServiceException { /** * Basic serialVersionUID variable. */ private static final long serialVersionUID = 3203342520435342442L; /** * Default constructor. */ public SampleServiceException() { } /** * Public constructor. * * @param message * exception message */ public SampleServiceException(final String message) { super(message); } /** * Public constructor. * * @param cause * exception cause */ public SampleServiceException(final Throwable cause) { super(cause); } /** * Public constructor. * * @param message * exception message * @param cause * exception cause */ public SampleServiceException(final String message, final Throwable cause) { super(message, cause); } }
src/test/java/net/bolbat/kit/service/SampleServiceException.java
package net.bolbat.kit.service; import net.bolbat.kit.service.ServiceException; /** * {@link SampleService} exception. * * @author Alexandr Bolbat */ public class SampleServiceException extends ServiceException { /** * Basic serialVersionUID variable. */ private static final long serialVersionUID = 3203342520435342442L; /** * Default constructor. */ public SampleServiceException() { } /** * Public constructor. * * @param message * exception message */ public SampleServiceException(final String message) { super(message); } /** * Public constructor. * * @param cause * exception cause */ public SampleServiceException(final Throwable cause) { super(cause); } /** * Public constructor. * * @param message * exception message * @param cause * exception cause */ public SampleServiceException(final String message, final Throwable cause) { super(message, cause); } }
removed unused import
src/test/java/net/bolbat/kit/service/SampleServiceException.java
removed unused import
Java
mit
c95ab72f5b5183d0a6cf761e47ea9135bc4d0d3a
0
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
package leetcode; /** * https://leetcode.com/problems/buddy-strings/ */ public class Problem859 { public boolean buddyStrings(String A, String B) { if (A.length() != B.length()) { return false; } int idx1 = 0; int idx2 = 0; int count = 0; int[] charCounts = new int[26]; boolean hasDuplicate = false; for (int i = 0; i < A.length(); i++) { int index = A.charAt(i) - 'a'; charCounts[index]++; if (charCounts[index] > 1) { hasDuplicate = true; } if (A.charAt(i) != B.charAt(i)) { if (count == 0) { idx1 = i; } else if (count == 1) { idx2 = i; } else { return false; } count++; } } if (count == 0) { return hasDuplicate; } return (A.charAt(idx1) == B.charAt(idx2) && A.charAt(idx2) == B.charAt(idx1)); } }
src/main/java/leetcode/Problem859.java
package leetcode; /** * https://leetcode.com/problems/buddy-strings/ */ public class Problem859 { public boolean buddyStrings(String A, String B) { if (A.length() != B.length()) { return false; } int idx1 = 0; int idx2 = 0; int count = 0; for (int i = 0; i < A.length(); i++) { if (A.charAt(i) != B.charAt(i)) { if (count == 0) { idx1 = i; } else if (count == 1) { idx2 = i; } else { return false; } count++; } } return (A.charAt(idx1) == B.charAt(idx2) && A.charAt(idx2) == B.charAt(idx1)); } public static void main(String[] args) { Problem859 prob = new Problem859(); System.out.println(prob.buddyStrings("ab", "ba")); // true System.out.println(prob.buddyStrings("ab", "ab")); // false System.out.println(prob.buddyStrings("aa", "aa")); // true System.out.println(prob.buddyStrings("aaaaaaabc", "aaaaaaacb")); // true System.out.println(prob.buddyStrings("", "aa")); // false System.out.println(prob.buddyStrings("abc", "cba")); // true System.out.println(prob.buddyStrings("aab", "aab")); // true System.out.println(prob.buddyStrings("aba", "aba")); // true } }
Solve problem 859
src/main/java/leetcode/Problem859.java
Solve problem 859
Java
epl-1.0
72d68c056ebe5c79cd48c479b93edcc0f3969287
0
ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio
package org.csstudio.opibuilder.runmode; import org.csstudio.opibuilder.util.MacrosInput; import org.csstudio.opibuilder.util.UIBundlingThread; import org.csstudio.platform.logging.CentralLogger; import org.eclipse.core.resources.IFile; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IPageListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; /**The service for running of OPI. * @author Xihui Chen * */ public class RunModeService { public enum TargetWindow{ NEW_WINDOW, SAME_WINDOW, RUN_WINDOW; } private IWorkbenchWindow runWorkbenchWindow; private static RunModeService instance; public static RunModeService getInstance(){ if(instance == null) instance = new RunModeService(); return instance; } public IWorkbenchWindow getRunWorkbenchWindow(){ return runWorkbenchWindow; } public void replaceActiveEditorContent(RunnerInput input) throws PartInitException{ IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow(). getActivePage().getActiveEditor(); activeEditor.init(activeEditor.getEditorSite(),input); } /**Run an OPI file with necessary parameters. This function should be called when open an OPI * from another OPI. * @param file * @param targetWindow * @param displayOpenManager * @param macrosInput */ public void runOPI(IFile file, TargetWindow targetWindow, DisplayOpenManager displayOpenManager, MacrosInput macrosInput){ runOPI(file, targetWindow, displayOpenManager, macrosInput, null); } /**Run an OPI file in the target window. * @param file * @param targetWindow */ public void runOPI(IFile file, TargetWindow targetWindow, Dimension windowSize){ runOPI(file, targetWindow, null, null, windowSize); } /**Run an OPI file. * @param file the file to be ran. If displayModel is not null, this will be ignored. * @param displayModel the display model to be ran. null for file input only. * @param displayOpenManager the manager help to manage the opened displays. null if the OPI is not * replacing the current active display. */ public void runOPI(final IFile file, final TargetWindow target, final DisplayOpenManager displayOpenManager, final MacrosInput macrosInput, final Dimension windowSize){ final RunnerInput runnerInput = new RunnerInput(file, displayOpenManager, macrosInput); UIBundlingThread.getInstance().addRunnable(new Runnable(){ public void run() { IWorkbenchWindow targetWindow = null; switch (target) { case NEW_WINDOW: targetWindow = createNewWindow(windowSize); break; case RUN_WINDOW: if(runWorkbenchWindow == null){ runWorkbenchWindow = createNewWindow(windowSize); runWorkbenchWindow.addPageListener(new IPageListener(){ public void pageClosed(IWorkbenchPage page) { runWorkbenchWindow = null; } public void pageActivated(IWorkbenchPage page) { } public void pageOpened(IWorkbenchPage page) { } }); }else{ for(IEditorReference editor : runWorkbenchWindow.getActivePage().getEditorReferences()){ try { if(editor.getEditorInput().equals(runnerInput)) editor.getPage().closeEditor(editor.getEditor(false), false); } catch (PartInitException e) { CentralLogger.getInstance().error(this,e); } } } targetWindow = runWorkbenchWindow; break; case SAME_WINDOW: default: targetWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); break; } if(targetWindow != null){ try { targetWindow.getShell().forceActive(); targetWindow.getShell().forceFocus(); targetWindow.getActivePage().openEditor( runnerInput, "org.csstudio.opibuilder.OPIRunner"); //$NON-NLS-1$ targetWindow.getShell().moveAbove(null); } catch (PartInitException e) { CentralLogger.getInstance().error(this, "Failed to run OPI " + file.getName(), e); } } } }); } /** * @param displayModel */ private IWorkbenchWindow createNewWindow(Dimension size) { IWorkbenchWindow newWindow = null; try { newWindow = PlatformUI.getWorkbench().openWorkbenchWindow("org.csstudio.opibuilder.OPIRunner", null); //$NON-NLS-1$ //ActionFactory.IWorkbenchAction toggleToolbar = ActionFactory.TOGGLE_COOLBAR.create(runWorkbenchWindow); //toggleToolbar.run(); if(size != null) newWindow.getShell().setSize(size.width+45, size.height + 165); } catch (WorkbenchException e) { CentralLogger.getInstance().error(this, "Failed to open new window", e); } return newWindow; } }
applications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/runmode/RunModeService.java
package org.csstudio.opibuilder.runmode; import org.csstudio.opibuilder.util.MacrosInput; import org.csstudio.opibuilder.util.UIBundlingThread; import org.csstudio.platform.logging.CentralLogger; import org.eclipse.core.resources.IFile; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPageListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; /**The service for running of OPI. * @author Xihui Chen * */ public class RunModeService { public enum TargetWindow{ NEW_WINDOW, SAME_WINDOW, RUN_WINDOW; } private IWorkbenchWindow runWorkbenchWindow; private static RunModeService instance; public static RunModeService getInstance(){ if(instance == null) instance = new RunModeService(); return instance; } public IWorkbenchWindow getRunWorkbenchWindow(){ return runWorkbenchWindow; } public void replaceActiveEditorContent(RunnerInput input) throws PartInitException{ IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow(). getActivePage().getActiveEditor(); activeEditor.init(activeEditor.getEditorSite(),input); } /**Run an OPI file with necessary parameters. This function should be called when open an OPI * from another OPI. * @param file * @param targetWindow * @param displayOpenManager * @param macrosInput */ public void runOPI(IFile file, TargetWindow targetWindow, DisplayOpenManager displayOpenManager, MacrosInput macrosInput){ runOPI(file, targetWindow, displayOpenManager, macrosInput, null); } /**Run an OPI file in the target window. * @param file * @param targetWindow */ public void runOPI(IFile file, TargetWindow targetWindow, Dimension windowSize){ runOPI(file, targetWindow, null, null, windowSize); } /**Run an OPI file. * @param file the file to be ran. If displayModel is not null, this will be ignored. * @param displayModel the display model to be ran. null for file input only. * @param displayOpenManager the manager help to manage the opened displays. null if the OPI is not * replacing the current active display. */ public void runOPI(final IFile file, final TargetWindow target, final DisplayOpenManager displayOpenManager, final MacrosInput macrosInput, final Dimension windowSize){ UIBundlingThread.getInstance().addRunnable(new Runnable(){ public void run() { IWorkbenchWindow targetWindow = null; switch (target) { case NEW_WINDOW: targetWindow = createNewWindow(windowSize); break; case RUN_WINDOW: if(runWorkbenchWindow == null){ runWorkbenchWindow = createNewWindow(windowSize); runWorkbenchWindow.addPageListener(new IPageListener(){ public void pageClosed(IWorkbenchPage page) { runWorkbenchWindow = null; } public void pageActivated(IWorkbenchPage page) { } public void pageOpened(IWorkbenchPage page) { } }); } targetWindow = runWorkbenchWindow; break; case SAME_WINDOW: default: targetWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); break; } if(targetWindow != null){ try { targetWindow.getActivePage().openEditor( new RunnerInput(file, displayOpenManager, macrosInput), "org.csstudio.opibuilder.OPIRunner"); //$NON-NLS-1$ targetWindow.getShell().moveAbove(null); } catch (PartInitException e) { CentralLogger.getInstance().error(this, "Failed to run OPI " + file.getName(), e); } } } }); } /** * @param displayModel */ private IWorkbenchWindow createNewWindow(Dimension size) { IWorkbenchWindow newWindow = null; try { newWindow = PlatformUI.getWorkbench().openWorkbenchWindow("org.csstudio.opibuilder.OPIRunner", null); //$NON-NLS-1$ //ActionFactory.IWorkbenchAction toggleToolbar = ActionFactory.TOGGLE_COOLBAR.create(runWorkbenchWindow); //toggleToolbar.run(); if(size != null) newWindow.getShell().setSize(size.width+45, size.height + 165); } catch (WorkbenchException e) { CentralLogger.getInstance().error(this, "Failed to open new window", e); } return newWindow; } }
Close the running OPI before running it again from OPI Editor, so that the changes can be automatically synchronized.
applications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/runmode/RunModeService.java
Close the running OPI before running it again from OPI Editor, so that the changes can be automatically synchronized.
Java
agpl-3.0
9e208cd476a20aea96d428892d3ba8f06f2eda8a
0
TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil
package nl.mpi.arbil; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableCellEditor; /** * Document : LinorgSplitPanel * Created on : * @author Peter.Withers@mpi.nl */ public class LinorgSplitPanel extends JPanel { private JList fileList; public ImdiTable imdiTable; private JScrollPane tableScrollPane; private JScrollPane listScroller; private JSplitPane splitPane; private JLabel hiddenColumnsLabel; private FindReplacePanel findReplacePanel = null; private boolean showSearchPanel = false; private JPanel tableOuterPanel; boolean selectionChangeInProcess = false; // this is to stop looping selection changes public LinorgSplitPanel(ImdiTable localImdiTable) { // setBackground(new Color(0xFF00FF)); this.setLayout(new BorderLayout()); imdiTable = localImdiTable; splitPane = new JSplitPane(); hiddenColumnsLabel = new JLabel(); tableScrollPane = new JScrollPane(imdiTable); tableScrollPane.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { imdiTable.setColumnWidths(); } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } }); tableOuterPanel = new JPanel(new BorderLayout()); tableOuterPanel.add(tableScrollPane, BorderLayout.CENTER); tableOuterPanel.add(hiddenColumnsLabel, BorderLayout.SOUTH); ((ImdiTableModel) localImdiTable.getModel()).setHiddenColumnsLabel(hiddenColumnsLabel); fileList = new JList(((ImdiTableModel) localImdiTable.getModel()).getListModel(this)); fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); fileList.setLayoutOrientation(JList.HORIZONTAL_WRAP); fileList.setVisibleRowCount(-1); listScroller = new JScrollPane(fileList); listScroller.setPreferredSize(new Dimension(250, 80)); ImageBoxRenderer renderer = new ImageBoxRenderer(); fileList.setCellRenderer(renderer); splitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); splitPane.setDividerSize(5); fileList.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { ContextMenu.getSingleInstance().showTreePopup(evt.getSource(), evt.getX(), evt.getY()); } } @Override public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { ContextMenu.getSingleInstance().showTreePopup(evt.getSource(), evt.getX(), evt.getY()); } } }); fileList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); fileList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting() && !selectionChangeInProcess) { // while this is not thread safe this should only be called by the swing thread via the gui or as a consequence of the enclosed selection changes selectionChangeInProcess = true; if (e.getSource() instanceof JList) { // System.out.println("JList"); imdiTable.clearSelection(); int minSelectedRow = -1; int maxSelectedRow = -1; for (Object selectedRow : ((JList) e.getSource()).getSelectedValues()) { imdiTable.setColumnSelectionAllowed(false); imdiTable.setRowSelectionAllowed(true); for (int rowCount = 0; rowCount < imdiTable.getRowCount(); rowCount++) { if (imdiTable.getValueAt(rowCount, 0).equals(selectedRow)) { imdiTable.addRowSelectionInterval(rowCount, rowCount); if (maxSelectedRow == -1 || maxSelectedRow < rowCount) { maxSelectedRow = rowCount; } if (minSelectedRow == -1 || minSelectedRow > rowCount) { minSelectedRow = rowCount; } } } // System.out.println("selectedRow:" + selectedRow); if (maxSelectedRow != -1) { imdiTable.scrollRectToVisible(imdiTable.getCellRect(minSelectedRow, 0, true)); } } if (LinorgSessionStorage.getSingleInstance().trackTableSelection) { TreeHelper.getSingleInstance().jumpToSelectionInTree(true, (ImdiTreeObject) ((JList) e.getSource()).getSelectedValue()); } } selectionChangeInProcess = false; } } }); imdiTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting() && !selectionChangeInProcess) { // while this is not thread safe this should only be called by the swing thread via the gui or as a consequence of the enclosed selection changes selectionChangeInProcess = true; fileList.clearSelection(); int minSelectedRow = -1; int maxSelectedRow = -1; for (Object selectedRow : imdiTable.getSelectedRowsFromTable()) { // System.out.println("selectedRow:" + selectedRow); for (int rowCount = 0; rowCount < fileList.getModel().getSize(); rowCount++) { // System.out.println("JList:" + fileList.getModel().getElementAt(rowCount)); if (fileList.getModel().getElementAt(rowCount).equals(selectedRow)) { fileList.addSelectionInterval(rowCount, rowCount); // System.out.println("add selection"); if (maxSelectedRow == -1 || maxSelectedRow < rowCount) { maxSelectedRow = rowCount; } if (minSelectedRow == -1 || minSelectedRow > rowCount) { minSelectedRow = rowCount; } } } } if (maxSelectedRow != -1) { fileList.scrollRectToVisible(fileList.getCellBounds(minSelectedRow, maxSelectedRow)); } if (LinorgSessionStorage.getSingleInstance().trackTableSelection) { TreeHelper.getSingleInstance().jumpToSelectionInTree(true, imdiTable.getImdiNodeForSelection()); } selectionChangeInProcess = false; } } }); } public void showSearchPane() { if (findReplacePanel == null) { findReplacePanel = new FindReplacePanel(this); } if (!showSearchPanel) { tableOuterPanel.remove(hiddenColumnsLabel); tableOuterPanel.add(findReplacePanel, BorderLayout.SOUTH); } else { tableOuterPanel.remove(findReplacePanel); tableOuterPanel.add(hiddenColumnsLabel, BorderLayout.SOUTH); } showSearchPanel = !showSearchPanel; this.revalidate(); this.repaint(); } public void setSplitDisplay() { this.removeAll(); if (fileList.getModel().getSize() == 0) { this.add(tableOuterPanel); } else { splitPane.setTopComponent(tableOuterPanel); // splitPane.setTopComponent(tableScrollPane); splitPane.setBottomComponent(listScroller); ArbilDragDrop.getSingleInstance().addDrag(fileList); ArbilDragDrop.getSingleInstance().addTransferHandler(tableScrollPane); this.add(splitPane); this.doLayout(); splitPane.setDividerLocation(0.5); } ArbilDragDrop.getSingleInstance().addDrag(imdiTable); ArbilDragDrop.getSingleInstance().addTransferHandler(this); this.doLayout(); } @Override public void doLayout() { // imdiTable.doLayout(); super.doLayout(); } public void addFocusListener(JInternalFrame internalFrame) { internalFrame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameDeactivated(InternalFrameEvent e) { TableCellEditor tableCellEditor = imdiTable.getCellEditor(); if (tableCellEditor != null) { tableCellEditor.stopCellEditing(); } super.internalFrameDeactivated(e); } }); } }
src/nl/mpi/arbil/LinorgSplitPanel.java
package nl.mpi.arbil; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableCellEditor; /** * Document : LinorgSplitPanel * Created on : * @author Peter.Withers@mpi.nl */ public class LinorgSplitPanel extends JPanel { private JList fileList; public ImdiTable imdiTable; private JScrollPane tableScrollPane; private JScrollPane listScroller; private JSplitPane splitPane; private JLabel hiddenColumnsLabel; private FindReplacePanel findReplacePanel = null; private boolean showSearchPanel = false; private JPanel tableOuterPanel; boolean selectionChangeInProcess = false; // this is to stop looping selection changes public LinorgSplitPanel(ImdiTable localImdiTable) { // setBackground(new Color(0xFF00FF)); this.setLayout(new BorderLayout()); imdiTable = localImdiTable; splitPane = new JSplitPane(); hiddenColumnsLabel = new JLabel(); tableScrollPane = new JScrollPane(imdiTable); tableScrollPane.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { imdiTable.setColumnWidths(); } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } }); tableOuterPanel = new JPanel(new BorderLayout()); tableOuterPanel.add(tableScrollPane, BorderLayout.CENTER); tableOuterPanel.add(hiddenColumnsLabel, BorderLayout.SOUTH); ((ImdiTableModel) localImdiTable.getModel()).setHiddenColumnsLabel(hiddenColumnsLabel); fileList = new JList(((ImdiTableModel) localImdiTable.getModel()).getListModel(this)); fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); fileList.setLayoutOrientation(JList.HORIZONTAL_WRAP); fileList.setVisibleRowCount(-1); listScroller = new JScrollPane(fileList); listScroller.setPreferredSize(new Dimension(250, 80)); ImageBoxRenderer renderer = new ImageBoxRenderer(); fileList.setCellRenderer(renderer); splitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); splitPane.setDividerSize(5); fileList.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { ContextMenu.getSingleInstance().showTreePopup(evt.getSource(), evt.getX(), evt.getY()); } } @Override public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { ContextMenu.getSingleInstance().showTreePopup(evt.getSource(), evt.getX(), evt.getY()); } } }); fileList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); fileList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting() && !selectionChangeInProcess) { // while this is not thread safe this should only be called by the swing thread via the gui or as a consequence of the enclosed selection changes selectionChangeInProcess = true; if (e.getSource() instanceof JList) { // System.out.println("JList"); imdiTable.clearSelection(); int minSelectedRow = -1; int maxSelectedRow = -1; for (Object selectedRow : ((JList) e.getSource()).getSelectedValues()) { imdiTable.setColumnSelectionAllowed(false); imdiTable.setRowSelectionAllowed(true); for (int rowCount = 0; rowCount < imdiTable.getRowCount(); rowCount++) { if (imdiTable.getValueAt(rowCount, 0).equals(selectedRow)) { imdiTable.addRowSelectionInterval(rowCount, rowCount); if (maxSelectedRow == -1 || maxSelectedRow < rowCount) { maxSelectedRow = rowCount; } if (minSelectedRow == -1 || minSelectedRow > rowCount) { minSelectedRow = rowCount; } } } // System.out.println("selectedRow:" + selectedRow); if (maxSelectedRow != -1) { imdiTable.scrollRectToVisible(imdiTable.getCellRect(minSelectedRow, 0, true)); } } if (LinorgSessionStorage.getSingleInstance().trackTableSelection) { TreeHelper.getSingleInstance().jumpToSelectionInTree(true, (ImdiTreeObject) ((JList) e.getSource()).getSelectedValue()); } } selectionChangeInProcess = false; } } }); imdiTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting() && !selectionChangeInProcess) { // while this is not thread safe this should only be called by the swing thread via the gui or as a consequence of the enclosed selection changes selectionChangeInProcess = true; fileList.clearSelection(); int minSelectedRow = -1; int maxSelectedRow = -1; for (Object selectedRow : imdiTable.getSelectedRowsFromTable()) { // System.out.println("selectedRow:" + selectedRow); for (int rowCount = 0; rowCount < fileList.getModel().getSize(); rowCount++) { // System.out.println("JList:" + fileList.getModel().getElementAt(rowCount)); if (fileList.getModel().getElementAt(rowCount).equals(selectedRow)) { fileList.addSelectionInterval(rowCount, rowCount); // System.out.println("add selection"); if (maxSelectedRow == -1 || maxSelectedRow < rowCount) { maxSelectedRow = rowCount; } if (minSelectedRow == -1 || minSelectedRow > rowCount) { minSelectedRow = rowCount; } } } } if (maxSelectedRow != -1) { fileList.scrollRectToVisible(fileList.getCellBounds(minSelectedRow, maxSelectedRow)); } if (LinorgSessionStorage.getSingleInstance().trackTableSelection) { TreeHelper.getSingleInstance().jumpToSelectionInTree(true, imdiTable.getImdiNodeForSelection()); } selectionChangeInProcess = false; } } }); } public void showSearchPane() { if (findReplacePanel == null) { findReplacePanel = new FindReplacePanel(this); } if (!showSearchPanel) { tableOuterPanel.remove(hiddenColumnsLabel); tableOuterPanel.add(findReplacePanel, BorderLayout.SOUTH); } else { tableOuterPanel.remove(findReplacePanel); tableOuterPanel.add(hiddenColumnsLabel, BorderLayout.SOUTH); } showSearchPanel = !showSearchPanel; this.revalidate(); this.repaint(); } public void setSplitDisplay() { this.removeAll(); if (fileList.getModel().getSize() == 0) { this.add(tableOuterPanel); } else { splitPane.setTopComponent(tableOuterPanel); // splitPane.setTopComponent(tableScrollPane); splitPane.setBottomComponent(listScroller); GuiHelper.arbilDragDrop.addDrag(fileList); GuiHelper.arbilDragDrop.addTransferHandler(tableScrollPane); this.add(splitPane); this.doLayout(); splitPane.setDividerLocation(0.5); } GuiHelper.arbilDragDrop.addDrag(imdiTable); GuiHelper.arbilDragDrop.addTransferHandler(this); this.doLayout(); } @Override public void doLayout() { // imdiTable.doLayout(); super.doLayout(); } public void addFocusListener(JInternalFrame internalFrame) { internalFrame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameDeactivated(InternalFrameEvent e) { TableCellEditor tableCellEditor = imdiTable.getCellEditor(); if (tableCellEditor != null) { tableCellEditor.stopCellEditing(); } super.internalFrameDeactivated(e); } }); } }
Resolved the issue re-importing nodes when the storage location is non standard. Replaced indicache with ArbilWorkingFiles as default when no existing directory is found. Replaced change cache directory menu item with change local storage directory menu item. Added text find and replace to the table. Added find replace into the context menu. Added the insertion of dummy data into clarin nodes when required. Added profile preview class. Added the display of info links in the tree and the table or previewed when html/txt. Corrected the defaults in the catalogue template.
src/nl/mpi/arbil/LinorgSplitPanel.java
Resolved the issue re-importing nodes when the storage location is non standard. Replaced indicache with ArbilWorkingFiles as default when no existing directory is found. Replaced change cache directory menu item with change local storage directory menu item. Added text find and replace to the table. Added find replace into the context menu. Added the insertion of dummy data into clarin nodes when required. Added profile preview class. Added the display of info links in the tree and the table or previewed when html/txt. Corrected the defaults in the catalogue template.
Java
apache-2.0
78ce50ccb321e53a65ba6aba5dcdf7274c07b81f
0
EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4,EBIBioSamples/biosamples-v4
/* * Copyright 2021 EMBL - European Bioinformatics Institute * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package uk.ac.ebi.biosamples.submission; import com.google.common.collect.Multimap; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.csv.CSVParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import uk.ac.ebi.biosamples.Messaging; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.*; import uk.ac.ebi.biosamples.mongo.model.MongoFileUpload; import uk.ac.ebi.biosamples.mongo.repo.MongoFileUploadRepository; import uk.ac.ebi.biosamples.mongo.util.BioSamplesFileUploadSubmissionStatus; import uk.ac.ebi.biosamples.mongo.util.SampleNameAccessionPair; import uk.ac.ebi.biosamples.utils.upload.Characteristics; import uk.ac.ebi.biosamples.utils.upload.FileUploadUtils; import uk.ac.ebi.biosamples.utils.upload.ValidationResult; @Service public class BioSamplesFileUploadSubmissionService { private Logger log = LoggerFactory.getLogger(getClass()); private ValidationResult validationResult; private FileUploadUtils fileUploadUtils; @Autowired BioSamplesClient bioSamplesAapClient; @Autowired @Qualifier("WEBINCLIENT") BioSamplesClient bioSamplesWebinClient; @Autowired BioSamplesFileUploadDataRetrievalService bioSamplesFileUploadDataRetrievalService; @Autowired MongoFileUploadRepository mongoFileUploadRepository; @RabbitListener( queues = Messaging.fileUploadQueue, containerFactory = "biosamplesFileUploadSubmissionContainerFactory") public void receiveMessageFromBioSamplesFileUploaderQueue(final String mongoFileId) { handleMessage(mongoFileId); } private void handleMessage(final String submissionId) { final MongoFileUpload mongoFileUpload = mongoFileUploadRepository.findOne(submissionId); try { validationResult = new ValidationResult(); fileUploadUtils = new FileUploadUtils(); log.info("Received file with file ID " + submissionId); final BioSamplesSubmissionFile bioSamplesSubmissionFile = bioSamplesFileUploadDataRetrievalService.getFile(submissionId); // get bioSamplesSubmissionFile metadata, determine webin aur aap auth and use client // accordingly final boolean isWebin = mongoFileUpload.isWebin(); final String checklist = mongoFileUpload.getChecklist(); String aapDomain = null; String webinId = null; if (isWebin) { webinId = mongoFileUpload.getSubmitterDetails(); } else { aapDomain = mongoFileUpload.getSubmitterDetails(); } final Path temp = Files.createTempFile("upload", ".tsv"); Files.copy(bioSamplesSubmissionFile.getStream(), temp, StandardCopyOption.REPLACE_EXISTING); final File fileToBeUploaded = temp.toFile(); final FileReader fr = new FileReader(fileToBeUploaded); final BufferedReader reader = new BufferedReader(fr); final CSVParser csvParser = fileUploadUtils.buildParser(reader); final List<Multimap<String, String>> csvDataMap = fileUploadUtils.getCSVDataInMap(csvParser); log.info("CSV data size: " + csvDataMap.size()); final List<Sample> samples = buildSamples(csvDataMap, aapDomain, webinId, checklist, validationResult, isWebin); final List<SampleNameAccessionPair> accessionsList = samples.stream() .map(sample -> new SampleNameAccessionPair(sample.getName(), sample.getAccession())) .collect(Collectors.toList()); final String persistenceMessage = "Number of samples persisted: " + samples.size(); validationResult.addValidationMessage(persistenceMessage); final String joinedValidationMessage = String.join(" -- ", validationResult.getValidationMessagesList()); log.info(joinedValidationMessage); final MongoFileUpload mongoFileUploadCompleted = new MongoFileUpload( submissionId, BioSamplesFileUploadSubmissionStatus.COMPLETED, mongoFileUpload.getSubmitterDetails(), mongoFileUpload.getChecklist(), isWebin, accessionsList, joinedValidationMessage); mongoFileUploadRepository.save(mongoFileUploadCompleted); } catch (final Exception e) { final String messageForBsdDevTeam = "********FEEDBACK TO BSD DEV TEAM START********" + e.getMessage() + "********FEEDBACK TO BSD DEV TEAM END********"; validationResult.addValidationMessage(messageForBsdDevTeam); final MongoFileUpload mongoFileUploadFailed = new MongoFileUpload( submissionId, BioSamplesFileUploadSubmissionStatus.FAILED, mongoFileUpload.getSubmitterDetails(), mongoFileUpload.getChecklist(), mongoFileUpload.isWebin(), mongoFileUpload.getSampleNameAccessionPairs(), String.join(" -- ", validationResult.getValidationMessagesList())); mongoFileUploadRepository.save(mongoFileUploadFailed); } finally { validationResult.clear(); } } private List<Sample> buildSamples( final List<Multimap<String, String>> csvDataMap, final String aapDomain, final String webinId, final String checklist, final ValidationResult validationResult, final boolean isWebin) { final Map<String, String> sampleNameToAccessionMap = new LinkedHashMap<>(); final Map<Sample, Multimap<String, String>> sampleToMappedSample = new LinkedHashMap<>(); csvDataMap.forEach( csvRecordMap -> { Sample sample = null; try { sample = buildAndPersistSample(csvRecordMap, aapDomain, webinId, checklist, isWebin); if (sample == null) { validationResult.addValidationMessage( "Failed to create sample in the file with sample name " + fileUploadUtils.getSampleName(csvRecordMap)); } } catch (Exception e) { validationResult.addValidationMessage( "Failed to create sample in the file with sample name " + fileUploadUtils.getSampleName(csvRecordMap)); } if (sample != null) { sampleNameToAccessionMap.put(sample.getName(), sample.getAccession()); sampleToMappedSample.put(sample, csvRecordMap); } }); return addRelationshipsAndThenBuildSamples( sampleNameToAccessionMap, sampleToMappedSample, validationResult, isWebin); } private List<Sample> addRelationshipsAndThenBuildSamples( final Map<String, String> sampleNameToAccessionMap, final Map<Sample, Multimap<String, String>> sampleToMappedSample, final ValidationResult validationResult, final boolean isWebin) { return sampleToMappedSample.entrySet().stream() .map( sampleMultimapEntry -> addRelationshipAndThenBuildAndPersistSample( sampleNameToAccessionMap, sampleMultimapEntry, validationResult, isWebin)) .collect(Collectors.toList()); } private Sample addRelationshipAndThenBuildAndPersistSample( final Map<String, String> sampleNameToAccessionMap, final Map.Entry<Sample, Multimap<String, String>> sampleMultimapEntry, final ValidationResult validationResult, final boolean isWebin) { final Multimap<String, String> relationshipMap = fileUploadUtils.parseRelationships(sampleMultimapEntry.getValue()); Sample sample = sampleMultimapEntry.getKey(); final List<Relationship> relationships = fileUploadUtils.createRelationships( sample, sampleNameToAccessionMap, relationshipMap, validationResult); relationships.forEach(relationship -> log.info(relationship.toString())); sample = Sample.Builder.fromSample(sample).withRelationships(relationships).build(); if (isWebin) { sample = bioSamplesWebinClient.persistSampleResource(sample).getContent(); } else { sample = bioSamplesAapClient.persistSampleResource(sample).getContent(); } return sample; } private Sample buildAndPersistSample( final Multimap<String, String> multiMap, final String aapDomain, final String webinId, final String checklist, final boolean isWebin) { final String sampleName = fileUploadUtils.getSampleName(multiMap); final String sampleReleaseDate = fileUploadUtils.getReleaseDate(multiMap); final String accession = fileUploadUtils.getSampleAccession(multiMap); final boolean sampleWithAccession = accession != null ? true : false; final List<Characteristics> characteristicsList = fileUploadUtils.handleCharacteristics(multiMap); final List<ExternalReference> externalReferenceList = fileUploadUtils.handleExternalReferences(multiMap); final List<Contact> contactsList = fileUploadUtils.handleContacts(multiMap); if (fileUploadUtils.isValidSample(sampleName, sampleReleaseDate, validationResult)) { Sample sample = fileUploadUtils.buildSample( sampleName, accession, sampleReleaseDate, characteristicsList, externalReferenceList, contactsList); sample = fileUploadUtils.addChecklistAttributeAndBuildSample(checklist, sample); if (isWebin) { try { sample = Sample.Builder.fromSample(sample).withWebinSubmissionAccountId(webinId).build(); sample = bioSamplesWebinClient.persistSampleResource(sample).getContent(); if (sampleWithAccession) { log.info("Updated sample " + sample.getAccession()); } else { log.info( "Sample " + sample.getName() + " created with accession " + sample.getAccession()); } } catch (final Exception e) { validationResult.addValidationMessage( "Error in persisting sample with name " + sampleName); } } else { try { sample = Sample.Builder.fromSample(sample).withDomain(aapDomain).build(); sample = bioSamplesAapClient.persistSampleResource(sample).getContent(); if (sampleWithAccession) { log.info("Updated sample " + sample.getAccession()); } else { log.info( "Sample " + sample.getName() + " created with accession " + sample.getAccession()); } } catch (final Exception e) { validationResult.addValidationMessage( "Error in persisting sample with name " + sampleName); } } return sample; } return null; } }
agents/uploadworkers/src/main/java/uk/ac/ebi/biosamples/submission/BioSamplesFileUploadSubmissionService.java
/* * Copyright 2021 EMBL - European Bioinformatics Institute * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package uk.ac.ebi.biosamples.submission; import com.google.common.collect.Multimap; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.csv.CSVParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import uk.ac.ebi.biosamples.Messaging; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.*; import uk.ac.ebi.biosamples.mongo.model.MongoFileUpload; import uk.ac.ebi.biosamples.mongo.repo.MongoFileUploadRepository; import uk.ac.ebi.biosamples.mongo.util.BioSamplesFileUploadSubmissionStatus; import uk.ac.ebi.biosamples.mongo.util.SampleNameAccessionPair; import uk.ac.ebi.biosamples.utils.upload.Characteristics; import uk.ac.ebi.biosamples.utils.upload.FileUploadUtils; import uk.ac.ebi.biosamples.utils.upload.ValidationResult; @Service public class BioSamplesFileUploadSubmissionService { private Logger log = LoggerFactory.getLogger(getClass()); private ValidationResult validationResult; private FileUploadUtils fileUploadUtils; @Autowired BioSamplesClient bioSamplesAapClient; @Autowired @Qualifier("WEBINCLIENT") BioSamplesClient bioSamplesWebinClient; @Autowired BioSamplesFileUploadDataRetrievalService bioSamplesFileUploadDataRetrievalService; @Autowired MongoFileUploadRepository mongoFileUploadRepository; @RabbitListener( queues = Messaging.fileUploadQueue, containerFactory = "biosamplesFileUploadSubmissionContainerFactory") public void receiveMessageFromBioSamplesFileUploaderQueue(final String mongoFileId) { handleMessage(mongoFileId); } private void handleMessage(final String submissionId) { final MongoFileUpload mongoFileUpload = mongoFileUploadRepository.findOne(submissionId); try { validationResult = new ValidationResult(); fileUploadUtils = new FileUploadUtils(); log.info("Received file with file ID " + submissionId); final BioSamplesSubmissionFile bioSamplesSubmissionFile = bioSamplesFileUploadDataRetrievalService.getFile(submissionId); // get bioSamplesSubmissionFile metadata, determine webin aur aap auth and use client // accordingly final boolean isWebin = mongoFileUpload.isWebin(); final String checklist = mongoFileUpload.getChecklist(); String aapDomain = null; String webinId = null; if (isWebin) { webinId = mongoFileUpload.getSubmitterDetails(); } else { aapDomain = mongoFileUpload.getSubmitterDetails(); } final Path temp = Files.createTempFile("upload", ".tsv"); Files.copy(bioSamplesSubmissionFile.getStream(), temp, StandardCopyOption.REPLACE_EXISTING); final File fileToBeUploaded = temp.toFile(); final FileReader fr = new FileReader(fileToBeUploaded); final BufferedReader reader = new BufferedReader(fr); final CSVParser csvParser = fileUploadUtils.buildParser(reader); final List<Multimap<String, String>> csvDataMap = fileUploadUtils.getCSVDataInMap(csvParser); log.info("CSV data size: " + csvDataMap.size()); final List<Sample> samples = buildSamples(csvDataMap, aapDomain, webinId, checklist, validationResult, isWebin); final List<SampleNameAccessionPair> accessionsList = samples.stream() .map(sample -> new SampleNameAccessionPair(sample.getName(), sample.getAccession())) .collect(Collectors.toList()); final String persistenceMessage = "Number of samples persisted: " + samples.size(); validationResult.addValidationMessage(persistenceMessage); final String joinedValidationMessage = String.join(" -- ", validationResult.getValidationMessagesList()); log.info(joinedValidationMessage); final MongoFileUpload mongoFileUploadCompleted = new MongoFileUpload( submissionId, BioSamplesFileUploadSubmissionStatus.COMPLETED, mongoFileUpload.getSubmitterDetails(), mongoFileUpload.getChecklist(), isWebin, accessionsList, joinedValidationMessage); mongoFileUploadRepository.save(mongoFileUploadCompleted); } catch (final Exception e) { final String messageForBsdDevTeam = "********FEEDBACK TO BSD DEV TEAM START********" + e.getMessage() + "********FEEDBACK TO BSD DEV TEAM END********"; validationResult.addValidationMessage(messageForBsdDevTeam); final MongoFileUpload mongoFileUploadFailed = new MongoFileUpload( submissionId, BioSamplesFileUploadSubmissionStatus.FAILED, mongoFileUpload.getSubmitterDetails(), mongoFileUpload.getChecklist(), mongoFileUpload.isWebin(), mongoFileUpload.getSampleNameAccessionPairs(), String.join(" -- ", validationResult.getValidationMessagesList())); mongoFileUploadRepository.save(mongoFileUploadFailed); } finally { validationResult.clear(); } } private List<Sample> buildSamples( final List<Multimap<String, String>> csvDataMap, final String aapDomain, final String webinId, final String checklist, final ValidationResult validationResult, final boolean isWebin) { final Map<String, String> sampleNameToAccessionMap = new LinkedHashMap<>(); final Map<Sample, Multimap<String, String>> sampleToMappedSample = new LinkedHashMap<>(); csvDataMap.forEach( csvRecordMap -> { Sample sample = null; try { sample = buildSample(csvRecordMap, aapDomain, webinId, checklist, isWebin); if (sample == null) { validationResult.addValidationMessage( "Failed to create sample in the file with sample name " + fileUploadUtils.getSampleName(csvRecordMap)); } } catch (Exception e) { validationResult.addValidationMessage( "Failed to create sample in the file with sample name " + fileUploadUtils.getSampleName(csvRecordMap)); } if (sample != null) { sampleNameToAccessionMap.put(sample.getName(), sample.getAccession()); sampleToMappedSample.put(sample, csvRecordMap); } }); return addRelationshipsAndThenBuildSamples( sampleNameToAccessionMap, sampleToMappedSample, validationResult, isWebin); } private List<Sample> addRelationshipsAndThenBuildSamples( final Map<String, String> sampleNameToAccessionMap, final Map<Sample, Multimap<String, String>> sampleToMappedSample, final ValidationResult validationResult, final boolean isWebin) { return sampleToMappedSample.entrySet().stream() .map( sampleMultimapEntry -> addRelationshipAndThenBuildSample( sampleNameToAccessionMap, sampleMultimapEntry, validationResult, isWebin)) .collect(Collectors.toList()); } private Sample addRelationshipAndThenBuildSample( final Map<String, String> sampleNameToAccessionMap, final Map.Entry<Sample, Multimap<String, String>> sampleMultimapEntry, final ValidationResult validationResult, final boolean isWebin) { final Multimap<String, String> relationshipMap = fileUploadUtils.parseRelationships(sampleMultimapEntry.getValue()); Sample sample = sampleMultimapEntry.getKey(); final List<Relationship> relationships = fileUploadUtils.createRelationships( sample, sampleNameToAccessionMap, relationshipMap, validationResult); relationships.forEach(relationship -> log.info(relationship.toString())); sample = Sample.Builder.fromSample(sample).withRelationships(relationships).build(); if (isWebin) { sample = bioSamplesWebinClient.persistSampleResource(sample).getContent(); } else { sample = bioSamplesAapClient.persistSampleResource(sample).getContent(); } return sample; } private Sample buildSample( final Multimap<String, String> multiMap, final String aapDomain, final String webinId, final String checklist, final boolean isWebin) { final String sampleName = fileUploadUtils.getSampleName(multiMap); final String sampleReleaseDate = fileUploadUtils.getReleaseDate(multiMap); final String accession = fileUploadUtils.getSampleAccession(multiMap); final List<Characteristics> characteristicsList = fileUploadUtils.handleCharacteristics(multiMap); final List<ExternalReference> externalReferenceList = fileUploadUtils.handleExternalReferences(multiMap); final List<Contact> contactsList = fileUploadUtils.handleContacts(multiMap); if (fileUploadUtils.isValidSample(sampleName, sampleReleaseDate, validationResult)) { Sample sample = fileUploadUtils.buildSample( sampleName, accession, sampleReleaseDate, characteristicsList, externalReferenceList, contactsList); sample = fileUploadUtils.addChecklistAttributeAndBuildSample(checklist, sample); if (isWebin) { try { sample = Sample.Builder.fromSample(sample).withWebinSubmissionAccountId(webinId).build(); sample = bioSamplesWebinClient.persistSampleResource(sample).getContent(); log.info( "Sample " + sample.getName() + " created with accession " + sample.getAccession()); } catch (final Exception e) { validationResult.addValidationMessage("Checklist validation failed for some/all samples"); } } else { try { sample = Sample.Builder.fromSample(sample).withDomain(aapDomain).build(); sample = bioSamplesAapClient.persistSampleResource(sample).getContent(); log.info( "Sample " + sample.getName() + " created with accession " + sample.getAccession()); } catch (final Exception e) { validationResult.addValidationMessage( "Checklist validation failed for some/ all samples"); } } return sample; } return null; } }
Improvements to logging in BioSamplesFileUploadSubmissionService
agents/uploadworkers/src/main/java/uk/ac/ebi/biosamples/submission/BioSamplesFileUploadSubmissionService.java
Improvements to logging in BioSamplesFileUploadSubmissionService
Java
apache-2.0
47eba72d43975437d45cd8071bc51e0ff327e108
0
samthor/intellij-community,da1z/intellij-community,kdwink/intellij-community,signed/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,petteyg/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,clumsy/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,vladmm/intellij-community,joewalnes/idea-community,hurricup/intellij-community,caot/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,robovm/robovm-studio,jagguli/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,allotria/intellij-community,dslomov/intellij-community,izonder/intellij-community,slisson/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ernestp/consulo,vvv1559/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,fnouama/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,dslomov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,kool79/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,slisson/intellij-community,fnouama/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ibinti/intellij-community,adedayo/intellij-community,hurricup/intellij-community,retomerz/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,holmes/intellij-community,vladmm/intellij-community,retomerz/intellij-community,holmes/intellij-community,ernestp/consulo,petteyg/intellij-community,apixandru/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,signed/intellij-community,fnouama/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,kdwink/intellij-community,robovm/robovm-studio,kool79/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,caot/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,joewalnes/idea-community,alphafoobar/intellij-community,adedayo/intellij-community,xfournet/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,asedunov/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,semonte/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,consulo/consulo,semonte/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,kool79/intellij-community,allotria/intellij-community,izonder/intellij-community,retomerz/intellij-community,kool79/intellij-community,petteyg/intellij-community,kdwink/intellij-community,amith01994/intellij-community,joewalnes/idea-community,fnouama/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,blademainer/intellij-community,hurricup/intellij-community,retomerz/intellij-community,samthor/intellij-community,jagguli/intellij-community,retomerz/intellij-community,supersven/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,da1z/intellij-community,supersven/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,robovm/robovm-studio,dslomov/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,signed/intellij-community,caot/intellij-community,diorcety/intellij-community,ibinti/intellij-community,clumsy/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,fitermay/intellij-community,da1z/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,caot/intellij-community,caot/intellij-community,orekyuu/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,kool79/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,fitermay/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,allotria/intellij-community,orekyuu/intellij-community,slisson/intellij-community,diorcety/intellij-community,retomerz/intellij-community,kool79/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,ryano144/intellij-community,caot/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,FHannes/intellij-community,petteyg/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,consulo/consulo,fnouama/intellij-community,caot/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,clumsy/intellij-community,ryano144/intellij-community,apixandru/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,jagguli/intellij-community,adedayo/intellij-community,semonte/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,slisson/intellij-community,Lekanich/intellij-community,consulo/consulo,kool79/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,izonder/intellij-community,xfournet/intellij-community,allotria/intellij-community,ibinti/intellij-community,kool79/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,blademainer/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,vladmm/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,izonder/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,consulo/consulo,tmpgit/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,da1z/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,adedayo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,caot/intellij-community,holmes/intellij-community,apixandru/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,suncycheng/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,slisson/intellij-community,petteyg/intellij-community,da1z/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,signed/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ahb0327/intellij-community,da1z/intellij-community,blademainer/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,slisson/intellij-community,caot/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,apixandru/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,tmpgit/intellij-community,consulo/consulo,jagguli/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,da1z/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,xfournet/intellij-community,adedayo/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,ernestp/consulo,orekyuu/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,kool79/intellij-community,robovm/robovm-studio,kool79/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,kdwink/intellij-community,clumsy/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,samthor/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,holmes/intellij-community,vladmm/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,clumsy/intellij-community,FHannes/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,consulo/consulo,holmes/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,adedayo/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,robovm/robovm-studio,kdwink/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,xfournet/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,amith01994/intellij-community,jagguli/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,supersven/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,signed/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,dslomov/intellij-community,holmes/intellij-community,izonder/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,caot/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,joewalnes/idea-community,da1z/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ernestp/consulo,lucafavatella/intellij-community,kool79/intellij-community,tmpgit/intellij-community,izonder/intellij-community,FHannes/intellij-community,izonder/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,caot/intellij-community,da1z/intellij-community,amith01994/intellij-community,amith01994/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,signed/intellij-community,blademainer/intellij-community,supersven/intellij-community,asedunov/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.introduceParameter; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.lang.Language; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.util.FieldConflictsResolver; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.refactoring.util.javadoc.MethodJavaDocHelper; import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; import com.intellij.util.containers.MultiMap; import gnu.trove.TIntArrayList; import gnu.trove.TIntProcedure; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Maxim.Medvedev */ public class JavaIntroduceParameterMethodUsagesProcessor implements IntroduceParameterMethodUsagesProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceParameter.JavaIntroduceParameterMethodUsagesProcessor"); private static final JavaLanguage myLanguage = Language.findInstance(JavaLanguage.class); private static boolean isJavaUsage(UsageInfo usage) { PsiElement e = usage.getElement(); return e != null && e.getLanguage().is(myLanguage); } public boolean isMethodUsage(UsageInfo usage) { return RefactoringUtil.isMethodUsage(usage.getElement()) && isJavaUsage(usage); } public boolean processChangeMethodUsage(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!isMethodUsage(usage)) return true; final PsiElement ref = usage.getElement(); PsiCall callExpression = RefactoringUtil.getCallExpressionByMethodReference(ref); PsiExpressionList argList = RefactoringUtil.getArgumentListByMethodReference(ref); PsiExpression[] oldArgs = argList.getExpressions(); final PsiExpression anchor; if (!data.getMethodToSearchFor().isVarArgs()) { anchor = getLast(oldArgs); } else { final PsiParameter[] parameters = data.getMethodToSearchFor().getParameterList().getParameters(); if (parameters.length > oldArgs.length) { anchor = getLast(oldArgs); } else { LOG.assertTrue(parameters.length > 0); final int lastNonVararg = parameters.length - 2; anchor = lastNonVararg >= 0 ? oldArgs[lastNonVararg] : null; } } //if we insert parameter in method usage which is contained in method in which we insert this parameter too, we must insert parameter name instead of its initializer PsiMethod method = PsiTreeUtil.getParentOfType(argList, PsiMethod.class); if (method != null && isMethodInUsages(data, method, usages)) { argList .addAfter(JavaPsiFacade.getElementFactory(data.getProject()).createExpressionFromText(data.getParameterName(), argList), anchor); } else { ChangeContextUtil.encodeContextInfo(data.getParameterInitializer(), true); PsiExpression newArg = (PsiExpression)argList.addAfter(data.getParameterInitializer(), anchor); ChangeContextUtil.decodeContextInfo(newArg, null, null); ChangeContextUtil.clearContextInfo(data.getParameterInitializer()); // here comes some postprocessing... new OldReferenceResolver(callExpression, newArg, data.getMethodToReplaceIn(), data.getReplaceFieldsWithGetters(), data.getParameterInitializer()).resolve(); } final PsiExpressionList argumentList = callExpression.getArgumentList(); LOG.assertTrue(argumentList != null, callExpression.getText()); removeParametersFromCall(argumentList, data.getParametersToRemove()); return false; } private static boolean isMethodInUsages(IntroduceParameterData data, PsiMethod method, UsageInfo[] usages) { PsiManager manager = PsiManager.getInstance(data.getProject()); for (UsageInfo info : usages) { if (!(info instanceof DefaultConstructorImplicitUsageInfo) && manager.areElementsEquivalent(info.getElement(), method)) { return true; } } return false; } private static void removeParametersFromCall(@NotNull final PsiExpressionList argList, TIntArrayList parametersToRemove) { final PsiExpression[] exprs = argList.getExpressions(); parametersToRemove.forEachDescending(new TIntProcedure() { public boolean execute(final int paramNum) { try { exprs[paramNum].delete(); } catch (IncorrectOperationException e) { LOG.error(e); } return true; } }); } @Nullable private static PsiExpression getLast(PsiExpression[] oldArgs) { PsiExpression anchor; if (oldArgs.length > 0) { anchor = oldArgs[oldArgs.length - 1]; } else { anchor = null; } return anchor; } public void findConflicts(IntroduceParameterData data, UsageInfo[] usages, MultiMap<PsiElement, String> conflicts) { } public boolean processChangeMethodSignature(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!(usage.getElement() instanceof PsiMethod) || !isJavaUsage(usage)) return true; PsiMethod method = (PsiMethod)usage.getElement(); final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(data.getParameterName(), method.getBody()); final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(method); PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); final PsiParameter[] parameters = method.getParameterList().getParameters(); data.getParametersToRemove().forEachDescending(new TIntProcedure() { public boolean execute(final int paramNum) { try { PsiParameter param = parameters[paramNum]; PsiDocTag tag = javaDocHelper.getTagForParameter(param); if (tag != null) { tag.delete(); } param.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } return true; } }); PsiParameter parameter = factory.createParameter(data.getParameterName(), data.getForcedType()); PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, data.isDeclareFinal()); final PsiParameter anchorParameter = getAnchorParameter(method); final PsiParameterList parameterList = method.getParameterList(); parameter = (PsiParameter)parameterList.addAfter(parameter, anchorParameter); JavaCodeStyleManager.getInstance(data.getProject()).shortenClassReferences(parameter); final PsiDocTag tagForAnchorParameter = javaDocHelper.getTagForParameter(anchorParameter); javaDocHelper.addParameterAfter(data.getParameterName(), tagForAnchorParameter); fieldConflictsResolver.fix(); return false; } @Nullable private static PsiParameter getAnchorParameter(PsiMethod methodToReplaceIn) { PsiParameterList parameterList = methodToReplaceIn.getParameterList(); final PsiParameter anchorParameter; final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (!methodToReplaceIn.isVarArgs()) { anchorParameter = length > 0 ? parameters[length - 1] : null; } else { LOG.assertTrue(length > 0); LOG.assertTrue(parameters[length - 1].isVarArgs()); anchorParameter = length > 1 ? parameters[length - 2] : null; } return anchorParameter; } public boolean processAddDefaultConstructor(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) { if (!(usage.getElement() instanceof PsiClass) || !isJavaUsage(usage)) return true; PsiClass aClass = (PsiClass)usage.getElement(); if (!(aClass instanceof PsiAnonymousClass)) { final PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiMethod constructor = factory.createMethodFromText(aClass.getName() + "(){}", aClass); constructor = (PsiMethod)CodeStyleManager.getInstance(data.getProject()).reformat(constructor); constructor = (PsiMethod)aClass.add(constructor); PsiUtil.setModifierProperty(constructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true); processAddSuperCall(data, new UsageInfo(constructor), usages); } else { return true; } return false; } public boolean processAddSuperCall(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!(usage.getElement() instanceof PsiMethod) || !isJavaUsage(usage)) return true; PsiMethod constructor = (PsiMethod)usage.getElement(); if (!constructor.isConstructor()) return true; final PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiExpressionStatement superCall = (PsiExpressionStatement)factory.createStatementFromText("super();", constructor); superCall = (PsiExpressionStatement)CodeStyleManager.getInstance(data.getProject()).reformat(superCall); PsiCodeBlock body = constructor.getBody(); final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { superCall = (PsiExpressionStatement)body.addBefore(superCall, statements[0]); } else { superCall = (PsiExpressionStatement)body.add(superCall); } processChangeMethodUsage(data, new ExternalUsageInfo(((PsiMethodCallExpression)superCall.getExpression()).getMethodExpression()), usages); return false; } }
java/java-impl/src/com/intellij/refactoring/introduceParameter/JavaIntroduceParameterMethodUsagesProcessor.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.introduceParameter; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.lang.Language; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.util.FieldConflictsResolver; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.refactoring.util.javadoc.MethodJavaDocHelper; import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; import com.intellij.util.containers.MultiMap; import gnu.trove.TIntArrayList; import gnu.trove.TIntProcedure; import org.jetbrains.annotations.Nullable; /** * @author Maxim.Medvedev */ public class JavaIntroduceParameterMethodUsagesProcessor implements IntroduceParameterMethodUsagesProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceParameter.JavaIntroduceParameterMethodUsagesProcessor"); private static final JavaLanguage myLanguage = Language.findInstance(JavaLanguage.class); private static boolean isJavaUsage(UsageInfo usage) { PsiElement e = usage.getElement(); return e != null && e.getLanguage().is(myLanguage); } public boolean isMethodUsage(UsageInfo usage) { return RefactoringUtil.isMethodUsage(usage.getElement()) && isJavaUsage(usage); } public boolean processChangeMethodUsage(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!isMethodUsage(usage)) return true; final PsiElement ref = usage.getElement(); PsiCall callExpression = RefactoringUtil.getCallExpressionByMethodReference(ref); PsiExpressionList argList = RefactoringUtil.getArgumentListByMethodReference(ref); PsiExpression[] oldArgs = argList.getExpressions(); final PsiExpression anchor; if (!data.getMethodToSearchFor().isVarArgs()) { anchor = getLast(oldArgs); } else { final PsiParameter[] parameters = data.getMethodToSearchFor().getParameterList().getParameters(); if (parameters.length > oldArgs.length) { anchor = getLast(oldArgs); } else { LOG.assertTrue(parameters.length > 0); final int lastNonVararg = parameters.length - 2; anchor = lastNonVararg >= 0 ? oldArgs[lastNonVararg] : null; } } //if we insert parameter in method usage which is contained in method in which we insert this parameter too, we must insert parameter name instead of its initializer PsiMethod method = PsiTreeUtil.getParentOfType(argList, PsiMethod.class); if (method != null && isMethodInUsages(data, method, usages)) { argList .addAfter(JavaPsiFacade.getElementFactory(data.getProject()).createExpressionFromText(data.getParameterName(), argList), anchor); } else { ChangeContextUtil.encodeContextInfo(data.getParameterInitializer(), true); PsiExpression newArg = (PsiExpression)argList.addAfter(data.getParameterInitializer(), anchor); ChangeContextUtil.decodeContextInfo(newArg, null, null); ChangeContextUtil.clearContextInfo(data.getParameterInitializer()); // here comes some postprocessing... new OldReferenceResolver(callExpression, newArg, data.getMethodToReplaceIn(), data.getReplaceFieldsWithGetters(), data.getParameterInitializer()).resolve(); } removeParametersFromCall(callExpression.getArgumentList(), data.getParametersToRemove()); return false; } private static boolean isMethodInUsages(IntroduceParameterData data, PsiMethod method, UsageInfo[] usages) { PsiManager manager = PsiManager.getInstance(data.getProject()); for (UsageInfo info : usages) { if (!(info instanceof DefaultConstructorImplicitUsageInfo) && manager.areElementsEquivalent(info.getElement(), method)) { return true; } } return false; } private static void removeParametersFromCall(final PsiExpressionList argList, TIntArrayList parametersToRemove) { final PsiExpression[] exprs = argList.getExpressions(); parametersToRemove.forEachDescending(new TIntProcedure() { public boolean execute(final int paramNum) { try { exprs[paramNum].delete(); } catch (IncorrectOperationException e) { LOG.error(e); } return true; } }); } @Nullable private static PsiExpression getLast(PsiExpression[] oldArgs) { PsiExpression anchor; if (oldArgs.length > 0) { anchor = oldArgs[oldArgs.length - 1]; } else { anchor = null; } return anchor; } public void findConflicts(IntroduceParameterData data, UsageInfo[] usages, MultiMap<PsiElement, String> conflicts) { } public boolean processChangeMethodSignature(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!(usage.getElement() instanceof PsiMethod) || !isJavaUsage(usage)) return true; PsiMethod method = (PsiMethod)usage.getElement(); final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(data.getParameterName(), method.getBody()); final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(method); PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); final PsiParameter[] parameters = method.getParameterList().getParameters(); data.getParametersToRemove().forEachDescending(new TIntProcedure() { public boolean execute(final int paramNum) { try { PsiParameter param = parameters[paramNum]; PsiDocTag tag = javaDocHelper.getTagForParameter(param); if (tag != null) { tag.delete(); } param.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } return true; } }); PsiParameter parameter = factory.createParameter(data.getParameterName(), data.getForcedType()); PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, data.isDeclareFinal()); final PsiParameter anchorParameter = getAnchorParameter(method); final PsiParameterList parameterList = method.getParameterList(); parameter = (PsiParameter)parameterList.addAfter(parameter, anchorParameter); JavaCodeStyleManager.getInstance(data.getProject()).shortenClassReferences(parameter); final PsiDocTag tagForAnchorParameter = javaDocHelper.getTagForParameter(anchorParameter); javaDocHelper.addParameterAfter(data.getParameterName(), tagForAnchorParameter); fieldConflictsResolver.fix(); return false; } @Nullable private static PsiParameter getAnchorParameter(PsiMethod methodToReplaceIn) { PsiParameterList parameterList = methodToReplaceIn.getParameterList(); final PsiParameter anchorParameter; final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (!methodToReplaceIn.isVarArgs()) { anchorParameter = length > 0 ? parameters[length - 1] : null; } else { LOG.assertTrue(length > 0); LOG.assertTrue(parameters[length - 1].isVarArgs()); anchorParameter = length > 1 ? parameters[length - 2] : null; } return anchorParameter; } public boolean processAddDefaultConstructor(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) { if (!(usage.getElement() instanceof PsiClass) || !isJavaUsage(usage)) return true; PsiClass aClass = (PsiClass)usage.getElement(); if (!(aClass instanceof PsiAnonymousClass)) { final PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiMethod constructor = factory.createMethodFromText(aClass.getName() + "(){}", aClass); constructor = (PsiMethod)CodeStyleManager.getInstance(data.getProject()).reformat(constructor); constructor = (PsiMethod)aClass.add(constructor); PsiUtil.setModifierProperty(constructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true); processAddSuperCall(data, new UsageInfo(constructor), usages); } else { return true; } return false; } public boolean processAddSuperCall(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!(usage.getElement() instanceof PsiMethod) || !isJavaUsage(usage)) return true; PsiMethod constructor = (PsiMethod)usage.getElement(); if (!constructor.isConstructor()) return true; final PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiExpressionStatement superCall = (PsiExpressionStatement)factory.createStatementFromText("super();", constructor); superCall = (PsiExpressionStatement)CodeStyleManager.getInstance(data.getProject()).reformat(superCall); PsiCodeBlock body = constructor.getBody(); final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { superCall = (PsiExpressionStatement)body.addBefore(superCall, statements[0]); } else { superCall = (PsiExpressionStatement)body.add(superCall); } processChangeMethodUsage(data, new ExternalUsageInfo(((PsiMethodCallExpression)superCall.getExpression()).getMethodExpression()), usages); return false; } }
assert (14772)
java/java-impl/src/com/intellij/refactoring/introduceParameter/JavaIntroduceParameterMethodUsagesProcessor.java
assert (14772)
Java
apache-2.0
aaae4872dc081c15fa8564ee614e281df487f5a8
0
DevStreet/FinanceAnalytics,jeorme/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,jerome79/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,DevStreet/FinanceAnalytics,nssales/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.forex.forward; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.threeten.bp.Clock; import org.threeten.bp.ZonedDateTime; import com.google.common.collect.Sets; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.forex.derivative.Forex; import com.opengamma.analytics.financial.instrument.InstrumentDefinition; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.conversion.ForexSecurityConverter; import com.opengamma.financial.analytics.model.forex.ForexVisitors; import com.opengamma.financial.currency.CurrencyPairs; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * */ public abstract class FXForwardFunction extends AbstractFunction.NonCompiledInvoker { /** * @deprecated Deprecated value property name - has been moved to {@link ValuePropertyNames#PAY_CURVE_CALCULATION_CONFIG} */ @Deprecated public static final String PAY_CURVE_CALC_CONFIG = ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG; /** * @deprecated Deprecated value property name - has been moved to {@link ValuePropertyNames#RECEIVE_CURVE_CALCULATION_CONFIG} */ @Deprecated public static final String RECEIVE_CURVE_CALC_CONFIG = ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG; /** The value requirement produced by this function */ private final String _valueRequirementName; /** * @param valueRequirementName The value requirement name, not null */ public FXForwardFunction(final String valueRequirementName) { ArgumentChecker.notNull(valueRequirementName, "value requirement name"); _valueRequirementName = valueRequirementName; } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final Clock snapshotClock = executionContext.getValuationClock(); final ZonedDateTime now = ZonedDateTime.now(snapshotClock); final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency payCurrency = security.accept(ForexVisitors.getPayCurrencyVisitor()); final Currency receiveCurrency = security.accept(ForexVisitors.getReceiveCurrencyVisitor()); if (now.isAfter(security.accept(ForexVisitors.getExpiryVisitor()))) { throw new OpenGammaRuntimeException("FX forward " + payCurrency.getCode() + "/" + receiveCurrency + " has expired"); } final ValueRequirement desiredValue = desiredValues.iterator().next(); final String payCurveName = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE); final String receiveCurveName = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE); final String payCurveConfig = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG); final String receiveCurveConfig = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG); final String fullPayCurveName = payCurveName + "_" + payCurrency.getCode(); final String fullReceiveCurveName = receiveCurveName + "_" + receiveCurrency.getCode(); final YieldAndDiscountCurve payCurve = getPayCurve(inputs, payCurrency, payCurveName, payCurveConfig); final YieldAndDiscountCurve receiveCurve = getReceiveCurve(inputs, receiveCurrency, receiveCurveName, receiveCurveConfig); final Map<String, Currency> curveCurrency = new HashMap<>(); curveCurrency.put(fullPayCurveName, payCurrency); curveCurrency.put(fullReceiveCurveName, receiveCurrency); final Object baseQuotePairsObject = inputs.getValue(ValueRequirementNames.CURRENCY_PAIRS); if (baseQuotePairsObject == null) { throw new OpenGammaRuntimeException("Could not get base/quote pair data"); } final CurrencyPairs baseQuotePairs = (CurrencyPairs) baseQuotePairsObject; final YieldAndDiscountCurve[] curves; final String[] allCurveNames; curves = new YieldAndDiscountCurve[] {payCurve, receiveCurve}; allCurveNames = new String[] {fullPayCurveName, fullReceiveCurveName}; // Implementation note: The ForexSecurityConverter create the Forex with currency order pay/receive. The curve are passed in the same order. final ForexSecurityConverter converter = new ForexSecurityConverter(baseQuotePairs); final InstrumentDefinition<?> definition = security.accept(converter); final Forex forex = (Forex) definition.toDerivative(now, allCurveNames); final YieldCurveBundle yieldCurves = new YieldCurveBundle(allCurveNames, curves); final ValueProperties.Builder properties = getResultProperties(target, desiredValue); final ValueSpecification spec = new ValueSpecification(_valueRequirementName, target.toSpecification(), properties.get()); return getResult(forex, yieldCurves, target, desiredValues, inputs, spec, executionContext); } //TODO clumsy. Push the execute() method down into the functions and have getForward() and getData() methods /** * Performs the calculation. * @param fxForward The FX forward * @param data The yield curve data * @param target The computation target * @param desiredValues The desired values * @param inputs The function inputs * @param spec The specification of the result * @param executionContext The execution context * @return A set of computed values */ protected abstract Set<ComputedValue> getResult(final Forex fxForward, final YieldCurveBundle data, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec, final FunctionExecutionContext executionContext); @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.FX_FORWARD_SECURITY.or(FinancialSecurityTypes.NON_DELIVERABLE_FX_FORWARD_SECURITY); } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = getResultProperties(target).get(); return Collections.singleton(new ValueSpecification(_valueRequirementName, target.toSpecification(), properties)); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> payCurveNames = constraints.getValues(ValuePropertyNames.PAY_CURVE); if (payCurveNames == null || payCurveNames.size() != 1) { return null; } final Set<String> receiveCurveNames = constraints.getValues(ValuePropertyNames.RECEIVE_CURVE); if (receiveCurveNames == null || receiveCurveNames.size() != 1) { return null; } final Set<String> payCurveConfigNames = constraints.getValues(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG); if (payCurveConfigNames == null || payCurveConfigNames.size() != 1) { return null; } final Set<String> receiveCurveConfigNames = constraints.getValues(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG); if (receiveCurveConfigNames == null || receiveCurveConfigNames.size() != 1) { return null; } final String payCurveName = payCurveNames.iterator().next(); final String receiveCurveName = receiveCurveNames.iterator().next(); final String payCurveCalculationConfig = payCurveConfigNames.iterator().next(); final String receiveCurveCalculationConfig = receiveCurveConfigNames.iterator().next(); final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency payCurrency = security.accept(ForexVisitors.getPayCurrencyVisitor()); final Currency receiveCurrency = security.accept(ForexVisitors.getReceiveCurrencyVisitor()); final ValueRequirement payFundingCurve = getPayCurveRequirement(payCurveName, payCurrency, payCurveCalculationConfig); final ValueRequirement receiveFundingCurve = getReceiveCurveRequirement(receiveCurveName, receiveCurrency, receiveCurveCalculationConfig); final ValueRequirement pairQuoteRequirement = new ValueRequirement(ValueRequirementNames.CURRENCY_PAIRS, ComputationTargetSpecification.NULL); return Sets.newHashSet(payFundingCurve, receiveFundingCurve, pairQuoteRequirement); } /** * Gets the general result properties. * @param target The target * @return The result properties */ protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target); /** * Gets the result properties. * @param target The target * @param desiredValue The desired value * @return The result properties */ protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target, final ValueRequirement desiredValue); /** * Gets the value requirement name. * @return The value requirement name */ protected String getValueRequirementName() { return _valueRequirementName; } /** * Gets the requirement for the pay curve. * @param curveName The pay curve name * @param currency The pay currency * @param curveCalculationConfigName The pay curve calculation configuration name * @return The pay curve requirement */ protected static ValueRequirement getPayCurveRequirement(final String curveName, final Currency currency, final String curveCalculationConfigName) { final ValueProperties.Builder properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, curveName) .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName) .withOptional(ValuePropertyNames.PAY_CURVE); return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetSpecification.of(currency), properties.get()); } /** * Gets the pay curve. * @param inputs The function inputs * @param currency The pay currency * @param curveName The pay curve name * @param curveCalculationConfig The pay curve calculation configuration name * @return The pay curve */ protected static YieldAndDiscountCurve getPayCurve(final FunctionInputs inputs, final Currency currency, final String curveName, final String curveCalculationConfig) { final Object curveObject = inputs.getValue(getPayCurveRequirement(curveName, currency, curveCalculationConfig)); if (curveObject == null) { throw new OpenGammaRuntimeException("Could not get " + curveName + " curve"); } final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject; return curve; } /** * Gets the requirement for the receive curve. * @param curveName The receive curve name * @param currency The receive currency * @param curveCalculationConfigName The receive curve calculation configuration name * @return The receive curve requirement */ protected static ValueRequirement getReceiveCurveRequirement(final String curveName, final Currency currency, final String curveCalculationConfigName) { final ValueProperties.Builder properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, curveName) .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName) .withOptional(ValuePropertyNames.RECEIVE_CURVE); return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetSpecification.of(currency), properties.get()); } /** * Gets the receive curve. * @param inputs The function inputs * @param currency The receive currency * @param curveName The receive curve name * @param curveCalculationConfig The receive curve calculation configuration name * @return The receive curve */ protected static YieldAndDiscountCurve getReceiveCurve(final FunctionInputs inputs, final Currency currency, final String curveName, final String curveCalculationConfig) { final Object curveObject = inputs.getValue(getReceiveCurveRequirement(curveName, currency, curveCalculationConfig)); if (curveObject == null) { throw new OpenGammaRuntimeException("Could not get " + curveName + " curve"); } final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject; return curve; } }
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/forward/FXForwardFunction.java
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.forex.forward; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.threeten.bp.Clock; import org.threeten.bp.ZonedDateTime; import com.google.common.collect.Sets; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.forex.derivative.Forex; import com.opengamma.analytics.financial.instrument.InstrumentDefinition; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.conversion.ForexSecurityConverter; import com.opengamma.financial.analytics.model.forex.ForexVisitors; import com.opengamma.financial.currency.CurrencyPairs; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * */ public abstract class FXForwardFunction extends AbstractFunction.NonCompiledInvoker { /** The value requirement produced by this function */ private final String _valueRequirementName; /** * @param valueRequirementName The value requirement name, not null */ public FXForwardFunction(final String valueRequirementName) { ArgumentChecker.notNull(valueRequirementName, "value requirement name"); _valueRequirementName = valueRequirementName; } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final Clock snapshotClock = executionContext.getValuationClock(); final ZonedDateTime now = ZonedDateTime.now(snapshotClock); final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency payCurrency = security.accept(ForexVisitors.getPayCurrencyVisitor()); final Currency receiveCurrency = security.accept(ForexVisitors.getReceiveCurrencyVisitor()); if (now.isAfter(security.accept(ForexVisitors.getExpiryVisitor()))) { throw new OpenGammaRuntimeException("FX forward " + payCurrency.getCode() + "/" + receiveCurrency + " has expired"); } final ValueRequirement desiredValue = desiredValues.iterator().next(); final String payCurveName = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE); final String receiveCurveName = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE); final String payCurveConfig = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG); final String receiveCurveConfig = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG); final String fullPayCurveName = payCurveName + "_" + payCurrency.getCode(); final String fullReceiveCurveName = receiveCurveName + "_" + receiveCurrency.getCode(); final YieldAndDiscountCurve payCurve = getPayCurve(inputs, payCurrency, payCurveName, payCurveConfig); final YieldAndDiscountCurve receiveCurve = getReceiveCurve(inputs, receiveCurrency, receiveCurveName, receiveCurveConfig); final Map<String, Currency> curveCurrency = new HashMap<>(); curveCurrency.put(fullPayCurveName, payCurrency); curveCurrency.put(fullReceiveCurveName, receiveCurrency); final Object baseQuotePairsObject = inputs.getValue(ValueRequirementNames.CURRENCY_PAIRS); if (baseQuotePairsObject == null) { throw new OpenGammaRuntimeException("Could not get base/quote pair data"); } final CurrencyPairs baseQuotePairs = (CurrencyPairs) baseQuotePairsObject; final YieldAndDiscountCurve[] curves; final String[] allCurveNames; curves = new YieldAndDiscountCurve[] {payCurve, receiveCurve}; allCurveNames = new String[] {fullPayCurveName, fullReceiveCurveName}; // Implementation note: The ForexSecurityConverter create the Forex with currency order pay/receive. The curve are passed in the same order. final ForexSecurityConverter converter = new ForexSecurityConverter(baseQuotePairs); final InstrumentDefinition<?> definition = security.accept(converter); final Forex forex = (Forex) definition.toDerivative(now, allCurveNames); final YieldCurveBundle yieldCurves = new YieldCurveBundle(allCurveNames, curves); final ValueProperties.Builder properties = getResultProperties(target, desiredValue); final ValueSpecification spec = new ValueSpecification(_valueRequirementName, target.toSpecification(), properties.get()); return getResult(forex, yieldCurves, target, desiredValues, inputs, spec, executionContext); } //TODO clumsy. Push the execute() method down into the functions and have getForward() and getData() methods /** * Performs the calculation. * @param fxForward The FX forward * @param data The yield curve data * @param target The computation target * @param desiredValues The desired values * @param inputs The function inputs * @param spec The specification of the result * @param executionContext The execution context * @return A set of computed values */ protected abstract Set<ComputedValue> getResult(final Forex fxForward, final YieldCurveBundle data, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec, final FunctionExecutionContext executionContext); @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.FX_FORWARD_SECURITY.or(FinancialSecurityTypes.NON_DELIVERABLE_FX_FORWARD_SECURITY); } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = getResultProperties(target).get(); return Collections.singleton(new ValueSpecification(_valueRequirementName, target.toSpecification(), properties)); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> payCurveNames = constraints.getValues(ValuePropertyNames.PAY_CURVE); if (payCurveNames == null || payCurveNames.size() != 1) { return null; } final Set<String> receiveCurveNames = constraints.getValues(ValuePropertyNames.RECEIVE_CURVE); if (receiveCurveNames == null || receiveCurveNames.size() != 1) { return null; } final Set<String> payCurveConfigNames = constraints.getValues(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG); if (payCurveConfigNames == null || payCurveConfigNames.size() != 1) { return null; } final Set<String> receiveCurveConfigNames = constraints.getValues(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG); if (receiveCurveConfigNames == null || receiveCurveConfigNames.size() != 1) { return null; } final String payCurveName = payCurveNames.iterator().next(); final String receiveCurveName = receiveCurveNames.iterator().next(); final String payCurveCalculationConfig = payCurveConfigNames.iterator().next(); final String receiveCurveCalculationConfig = receiveCurveConfigNames.iterator().next(); final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency payCurrency = security.accept(ForexVisitors.getPayCurrencyVisitor()); final Currency receiveCurrency = security.accept(ForexVisitors.getReceiveCurrencyVisitor()); final ValueRequirement payFundingCurve = getPayCurveRequirement(payCurveName, payCurrency, payCurveCalculationConfig); final ValueRequirement receiveFundingCurve = getReceiveCurveRequirement(receiveCurveName, receiveCurrency, receiveCurveCalculationConfig); final ValueRequirement pairQuoteRequirement = new ValueRequirement(ValueRequirementNames.CURRENCY_PAIRS, ComputationTargetSpecification.NULL); return Sets.newHashSet(payFundingCurve, receiveFundingCurve, pairQuoteRequirement); } /** * Gets the general result properties. * @param target The target * @return The result properties */ protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target); /** * Gets the result properties. * @param target The target * @param desiredValue The desired value * @return The result properties */ protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target, final ValueRequirement desiredValue); /** * Gets the value requirement name. * @return The value requirement name */ protected String getValueRequirementName() { return _valueRequirementName; } /** * Gets the requirement for the pay curve. * @param curveName The pay curve name * @param currency The pay currency * @param curveCalculationConfigName The pay curve calculation configuration name * @return The pay curve requirement */ protected static ValueRequirement getPayCurveRequirement(final String curveName, final Currency currency, final String curveCalculationConfigName) { final ValueProperties.Builder properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, curveName) .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName) .withOptional(ValuePropertyNames.PAY_CURVE); return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetSpecification.of(currency), properties.get()); } /** * Gets the pay curve. * @param inputs The function inputs * @param currency The pay currency * @param curveName The pay curve name * @param curveCalculationConfig The pay curve calculation configuration name * @return The pay curve */ protected static YieldAndDiscountCurve getPayCurve(final FunctionInputs inputs, final Currency currency, final String curveName, final String curveCalculationConfig) { final Object curveObject = inputs.getValue(getPayCurveRequirement(curveName, currency, curveCalculationConfig)); if (curveObject == null) { throw new OpenGammaRuntimeException("Could not get " + curveName + " curve"); } final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject; return curve; } /** * Gets the requirement for the receive curve. * @param curveName The receive curve name * @param currency The receive currency * @param curveCalculationConfigName The receive curve calculation configuration name * @return The receive curve requirement */ protected static ValueRequirement getReceiveCurveRequirement(final String curveName, final Currency currency, final String curveCalculationConfigName) { final ValueProperties.Builder properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, curveName) .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName) .withOptional(ValuePropertyNames.RECEIVE_CURVE); return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetSpecification.of(currency), properties.get()); } /** * Gets the receive curve. * @param inputs The function inputs * @param currency The receive currency * @param curveName The receive curve name * @param curveCalculationConfig The receive curve calculation configuration name * @return The receive curve */ protected static YieldAndDiscountCurve getReceiveCurve(final FunctionInputs inputs, final Currency currency, final String curveName, final String curveCalculationConfig) { final Object curveObject = inputs.getValue(getReceiveCurveRequirement(curveName, currency, curveCalculationConfig)); if (curveObject == null) { throw new OpenGammaRuntimeException("Could not get " + curveName + " curve"); } final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject; return curve; } }
Preserving backwards compatibility
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/forward/FXForwardFunction.java
Preserving backwards compatibility
Java
apache-2.0
452ee64466553ebef38eb08451a1cbf98eb9ee5e
0
rcarrillocruz/openstackdroid
package com.rcarrillocruz.android.openstackdroid; import android.database.sqlite.SQLiteDatabase; public class ConnectionProfileTable { public static final String TABLE_CONNECTION_PROFILE = "connectionProfile"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_PROFILE_NAME = "profileName"; public static final String COLUMN_ENDPOINT = "endpoint"; public static final String COLUMN_USERNAME = "username"; public static final String COLUMN_PASSWORD = "password"; public static final String COLUMN_TENANT_ID = "tenantId"; private static final String DATABASE_CREATE = "create table " + TABLE_CONNECTION_PROFILE + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_PROFILE_NAME + " text not null, " + COLUMN_ENDPOINT + " text not null," + COLUMN_USERNAME + " text not null," + COLUMN_PASSWORD + " text not null," + COLUMN_TENANT_ID + " text not null" + ");"; public static void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { database.execSQL("DROP TABLE IF EXISTS " + TABLE_CONNECTION_PROFILE); onCreate(database); } }
com.rcarrillocruz.android.openstackdroid/src/com/rcarrillocruz/android/openstackdroid/ConnectionProfileTable.java
package com.rcarrillocruz.android.openstackdroid; import android.database.sqlite.SQLiteDatabase; public class ConnectionProfileTable { public static final String TABLE_CONNECTION_PROFILE = "connectionProfile"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_PROFILE_NAME = "profileName"; public static final String COLUMN_ENDPOINT = "endpoint"; public static final String COLUMN_USERNAME = "username"; public static final String COLUMN_PASSWORD = "password"; public static final String COLUMN_TENANT_ID = "tenantId"; private static final String DATABASE_CREATE = "create table " + TABLE_CONNECTION_PROFILE + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_PROFILE_NAME + " text not null, " + COLUMN_ENDPOINT + " text not null," + COLUMN_USERNAME + " text not null" + COLUMN_PASSWORD + " text not null" + COLUMN_TENANT_ID + " text not null" + ");"; public static void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { database.execSQL("DROP TABLE IF EXISTS " + TABLE_CONNECTION_PROFILE); onCreate(database); } }
Fix create table statement It was lacking commas
com.rcarrillocruz.android.openstackdroid/src/com/rcarrillocruz/android/openstackdroid/ConnectionProfileTable.java
Fix create table statement
Java
apache-2.0
0888982c7fe5f5458a5f2e5e0297836c9310a0f5
0
gstevey/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,gstevey/gradle
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.tasks.testing.detection; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.gradle.api.GradleException; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.tasks.testing.DefaultTestClassRunInfo; import org.gradle.api.internal.tasks.testing.TestClassProcessor; import org.gradle.util.internal.Java9ClassReader; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.gradle.internal.FileUtils.hasExtension; public abstract class AbstractTestFrameworkDetector<T extends TestClassVisitor> implements TestFrameworkDetector { protected static final String TEST_CASE = "junit/framework/TestCase"; protected static final String GROOVY_TEST_CASE = "groovy/util/GroovyTestCase"; protected static final String JAVA_LANG_OBJECT = "java/lang/Object"; private List<File> testClassDirectories; private final ClassFileExtractionManager classFileExtractionManager; private final Map<File, Boolean> superClasses; private TestClassProcessor testClassProcessor; private final List<String> knownTestCaseClassNames; private File testClassesDirectory; private FileCollection testClasspath; protected AbstractTestFrameworkDetector(ClassFileExtractionManager classFileExtractionManager) { assert classFileExtractionManager != null; this.classFileExtractionManager = classFileExtractionManager; this.superClasses = new HashMap<File, Boolean>(); this.knownTestCaseClassNames = new ArrayList<String>(); addKnownTestCaseClassNames(TEST_CASE, GROOVY_TEST_CASE); } protected abstract T createClassVisitor(); protected File getSuperTestClassFile(String superClassName) { prepareClasspath(); if (StringUtils.isEmpty(superClassName)) { throw new IllegalArgumentException("superClassName is empty!"); } final Iterator<File> testClassDirectoriesIt = testClassDirectories.iterator(); File superTestClassFile = null; while (superTestClassFile == null && testClassDirectoriesIt.hasNext()) { final File testClassDirectory = testClassDirectoriesIt.next(); final File superTestClassFileCandidate = new File(testClassDirectory, superClassName + ".class"); if (superTestClassFileCandidate.exists()) { superTestClassFile = superTestClassFileCandidate; } } if (superTestClassFile != null) { return superTestClassFile; } else if (AbstractTestFrameworkDetector.JAVA_LANG_OBJECT.equals(superClassName)) { // java.lang.Object found, which is not a test class return null; } else { // super test class file not in test class directories return classFileExtractionManager.getLibraryClassFile(superClassName); } } private void prepareClasspath() { if (testClassDirectories != null) { return; } testClassDirectories = new ArrayList<File>(); if (testClassesDirectory != null) { testClassDirectories.add(testClassesDirectory); } if (testClasspath != null) { for (File file : testClasspath) { if (file.isDirectory()) { testClassDirectories.add(file); } else if (file.isFile() && hasExtension(file, ".jar")) { classFileExtractionManager.addLibraryJar(file); } } } } @Override public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override public void setTestClasspath(FileCollection testClasspath) { this.testClasspath = testClasspath; } protected TestClassVisitor classVisitor(final File testClassFile) { final TestClassVisitor classVisitor = createClassVisitor(); InputStream classStream = null; try { classStream = new BufferedInputStream(new FileInputStream(testClassFile)); final ClassReader classReader = new Java9ClassReader(IOUtils.toByteArray(classStream)); classReader.accept(classVisitor, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); } catch (Throwable e) { throw new GradleException("failed to read class file " + testClassFile.getAbsolutePath(), e); } finally { IOUtils.closeQuietly(classStream); } return classVisitor; } @Override public boolean processTestClass(File testClassFile) { return processTestClass(testClassFile, false); } protected abstract boolean processTestClass(File testClassFile, boolean superClass); protected boolean processSuperClass(File testClassFile) { boolean isTest = false; Boolean isSuperTest = superClasses.get(testClassFile); if (isSuperTest == null) { isTest = processTestClass(testClassFile, true); superClasses.put(testClassFile, isTest); } else { isTest = isSuperTest; } return isTest; } /** * In none super class mode a test class is published when the class is a test and it is not abstract. In super class mode it must not publish the class otherwise it will get published multiple * times (for each extending class). */ protected void publishTestClass(boolean isTest, TestClassVisitor classVisitor, boolean superClass) { if (isTest && !classVisitor.isAbstract() && !superClass) { String className = Type.getObjectType(classVisitor.getClassName()).getClassName(); testClassProcessor.processTestClass(new DefaultTestClassRunInfo(className)); } } @Override public void startDetection(TestClassProcessor testClassProcessor) { this.testClassProcessor = testClassProcessor; } public void addKnownTestCaseClassNames(String... knownTestCaseClassNames) { if (knownTestCaseClassNames != null && knownTestCaseClassNames.length != 0) { for (String knownTestCaseClassName : knownTestCaseClassNames) { if (StringUtils.isNotEmpty(knownTestCaseClassName)) { this.knownTestCaseClassNames.add(knownTestCaseClassName.replaceAll("\\.", "/")); } } } } protected boolean isKnownTestCaseClassName(String testCaseClassName) { boolean isKnownTestCase = false; if (StringUtils.isNotEmpty(testCaseClassName)) { isKnownTestCase = knownTestCaseClassNames.contains(testCaseClassName); } return isKnownTestCase; } }
subprojects/testing-jvm/src/main/java/org/gradle/api/internal/tasks/testing/detection/AbstractTestFrameworkDetector.java
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.tasks.testing.detection; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.gradle.api.GradleException; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.tasks.testing.DefaultTestClassRunInfo; import org.gradle.api.internal.tasks.testing.TestClassProcessor; import org.gradle.util.internal.Java9ClassReader; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Type; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.gradle.internal.FileUtils.hasExtension; public abstract class AbstractTestFrameworkDetector<T extends TestClassVisitor> implements TestFrameworkDetector { protected static final String TEST_CASE = "junit/framework/TestCase"; protected static final String GROOVY_TEST_CASE = "groovy/util/GroovyTestCase"; private List<File> testClassDirectories; private final ClassFileExtractionManager classFileExtractionManager; private final Map<File, Boolean> superClasses; private TestClassProcessor testClassProcessor; private final List<String> knownTestCaseClassNames; private File testClassesDirectory; private FileCollection testClasspath; protected AbstractTestFrameworkDetector(ClassFileExtractionManager classFileExtractionManager) { assert classFileExtractionManager != null; this.classFileExtractionManager = classFileExtractionManager; this.superClasses = new HashMap<File, Boolean>(); this.knownTestCaseClassNames = new ArrayList<String>(); addKnownTestCaseClassNames(TEST_CASE, GROOVY_TEST_CASE); } protected abstract T createClassVisitor(); protected File getSuperTestClassFile(String superClassName) { prepareClasspath(); if (StringUtils.isEmpty(superClassName)) { throw new IllegalArgumentException("superClassName is empty!"); } final Iterator<File> testClassDirectoriesIt = testClassDirectories.iterator(); File superTestClassFile = null; while (superTestClassFile == null && testClassDirectoriesIt.hasNext()) { final File testClassDirectory = testClassDirectoriesIt.next(); final File superTestClassFileCandidate = new File(testClassDirectory, superClassName + ".class"); if (superTestClassFileCandidate.exists()) { superTestClassFile = superTestClassFileCandidate; } } if (superTestClassFile != null) { return superTestClassFile; } else if ("java/lang/Object".equals(superClassName)) { // GRADLE-1682 return null; } else { // super test class file not in test class directories return classFileExtractionManager.getLibraryClassFile(superClassName); } } private void prepareClasspath() { if (testClassDirectories != null) { return; } testClassDirectories = new ArrayList<File>(); if (testClassesDirectory != null) { testClassDirectories.add(testClassesDirectory); } if (testClasspath != null) { for (File file : testClasspath) { if (file.isDirectory()) { testClassDirectories.add(file); } else if (file.isFile() && hasExtension(file, ".jar")) { classFileExtractionManager.addLibraryJar(file); } } } } @Override public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override public void setTestClasspath(FileCollection testClasspath) { this.testClasspath = testClasspath; } protected TestClassVisitor classVisitor(final File testClassFile) { final TestClassVisitor classVisitor = createClassVisitor(); InputStream classStream = null; try { classStream = new BufferedInputStream(new FileInputStream(testClassFile)); final ClassReader classReader = new Java9ClassReader(IOUtils.toByteArray(classStream)); classReader.accept(classVisitor, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); } catch (Throwable e) { throw new GradleException("failed to read class file " + testClassFile.getAbsolutePath(), e); } finally { IOUtils.closeQuietly(classStream); } return classVisitor; } @Override public boolean processTestClass(File testClassFile) { return processTestClass(testClassFile, false); } protected abstract boolean processTestClass(File testClassFile, boolean superClass); protected boolean processSuperClass(File testClassFile) { boolean isTest = false; Boolean isSuperTest = superClasses.get(testClassFile); if (isSuperTest == null) { isTest = processTestClass(testClassFile, true); superClasses.put(testClassFile, isTest); } else { isTest = isSuperTest; } return isTest; } /** * In none super class mode a test class is published when the class is a test and it is not abstract. In super class mode it must not publish the class otherwise it will get published multiple * times (for each extending class). */ protected void publishTestClass(boolean isTest, TestClassVisitor classVisitor, boolean superClass) { if (isTest && !classVisitor.isAbstract() && !superClass) { String className = Type.getObjectType(classVisitor.getClassName()).getClassName(); testClassProcessor.processTestClass(new DefaultTestClassRunInfo(className)); } } @Override public void startDetection(TestClassProcessor testClassProcessor) { this.testClassProcessor = testClassProcessor; } public void addKnownTestCaseClassNames(String... knownTestCaseClassNames) { if (knownTestCaseClassNames != null && knownTestCaseClassNames.length != 0) { for (String knownTestCaseClassName : knownTestCaseClassNames) { if (StringUtils.isNotEmpty(knownTestCaseClassName)) { this.knownTestCaseClassNames.add(knownTestCaseClassName.replaceAll("\\.", "/")); } } } } protected boolean isKnownTestCaseClassName(String testCaseClassName) { boolean isKnownTestCase = false; if (StringUtils.isNotEmpty(testCaseClassName)) { isKnownTestCase = knownTestCaseClassNames.contains(testCaseClassName); } return isKnownTestCase; } }
Introduced constant and improved comment (#676) Addresses review comments +review REVIEW-6234
subprojects/testing-jvm/src/main/java/org/gradle/api/internal/tasks/testing/detection/AbstractTestFrameworkDetector.java
Introduced constant and improved comment (#676)
Java
apache-2.0
0e7808e2b92ce45a39bf83d92f7382507a6a7791
0
gameontext/gameon-auth,gameontext/gameon-auth
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package gameontext.auth.common; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Handle generation of JWT auth credentials for the GameOn environment. */ @Component public class JWTSigner { @Value("${jwt.keystore.location}") protected String keyStore; @Value("${jwt.keystore.password}") protected String keyStorePW; @Value("${jwt.keystore.alias}") protected String keyStoreAlias; protected static PrivateKey signingKey = null; /** * Obtain the key we'll use to sign the jwts we issue. * * @throws IOException * if there are any issues with the keystore processing. */ private synchronized void getKeyStoreInfo() throws IOException { try { // load up the keystore.. FileInputStream is = new FileInputStream(keyStore); KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); signingKeystore.load(is, keyStorePW.toCharArray()); // grab the key we'll use to sign signingKey = (PrivateKey) signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray()); } catch (KeyStoreException e) { throw new IOException(e); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } catch (CertificateException e) { throw new IOException(e); } catch (UnrecoverableKeyException e) { throw new IOException(e); } } /** * Obtain a JWT with the details passed, signed appropriately * * @param id UserID to encode. * @param name Human Readable Name for User * @return jwt encoded as string, ready to send to http. * @throws IOException * if there are keystore issues. */ public String createJwt(String id, String name)throws IOException, JOSEException { return createJwt(id, name, null, null); } public String createJwt(String id, String name, String playerMode, String storyid) throws IOException, JOSEException { if (signingKey == null) { getKeyStoreInfo(); } Instant issuedAt = Instant.now().minus(12,ChronoUnit.HOURS); Instant expiresAt = Instant.now().plus(12,ChronoUnit.HOURS); // Spring API to build Jwt, no signing/serializing possible? // Jwt jwt = Jwt.withTokenValue("FISH") // .header("kid","playerssl") // .subject(id) // .claim("id",id) // .claim("name",name) // .audience(Collections.singleton("client")) // .issuedAt(issuedAt) // .expiresAt(expiresAt) // .build(); JWTClaimsSet.Builder claimsBuilder = new JWTClaimsSet.Builder() .subject(id) .claim("id",id) .claim("name",name); if(storyid!=null) { claimsBuilder = claimsBuilder.claim("story", storyid); } if(playerMode!=null) { claimsBuilder = claimsBuilder.claim("playerMode", playerMode); } JWTClaimsSet claims = claimsBuilder.audience("client") .issueTime(Date.from(issuedAt)) .expirationTime(Date.from(expiresAt)) .build(); SignedJWT jwt = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("playerssl").build(), claims); JWSSigner signer = new RSASSASigner(signingKey); jwt.sign(signer); return jwt.serialize(); } }
auth-app/src/main/java/gameontext/auth/common/JWTSigner.java
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package gameontext.auth.common; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Handle generation of JWT auth credentials for the GameOn environment. */ @Component public class JWTSigner { @Value("${jwt.keystore.location}") protected String keyStore; @Value("${jwt.keystore.password}") protected String keyStorePW; @Value("${jwt.keystore.alias}") protected String keyStoreAlias; protected static PrivateKey signingKey = null; /** * Obtain the key we'll use to sign the jwts we issue. * * @throws IOException * if there are any issues with the keystore processing. */ private synchronized void getKeyStoreInfo() throws IOException { try { // load up the keystore.. FileInputStream is = new FileInputStream(keyStore); KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); signingKeystore.load(is, keyStorePW.toCharArray()); // grab the key we'll use to sign signingKey = (PrivateKey) signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray()); } catch (KeyStoreException e) { throw new IOException(e); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } catch (CertificateException e) { throw new IOException(e); } catch (UnrecoverableKeyException e) { throw new IOException(e); } } /** * Obtain a JWT with the details passed, signed appropriately * * @param id UserID to encode. * @param name Human Readable Name for User * @return jwt encoded as string, ready to send to http. * @throws IOException * if there are keystore issues. */ public String createJwt(String id, String name)throws IOException, JOSEException { return createJwt(id, name, null, null); } public String createJwt(String id, String name, String storyid, String playerMode) throws IOException, JOSEException { if (signingKey == null) { getKeyStoreInfo(); } Instant issuedAt = Instant.now().minus(12,ChronoUnit.HOURS); Instant expiresAt = Instant.now().plus(12,ChronoUnit.HOURS); // Spring API to build Jwt, no signing/serializing possible? // Jwt jwt = Jwt.withTokenValue("FISH") // .header("kid","playerssl") // .subject(id) // .claim("id",id) // .claim("name",name) // .audience(Collections.singleton("client")) // .issuedAt(issuedAt) // .expiresAt(expiresAt) // .build(); JWTClaimsSet.Builder claimsBuilder = new JWTClaimsSet.Builder() .subject(id) .claim("id",id) .claim("name",name); if(storyid!=null) { claimsBuilder = claimsBuilder.claim("story", storyid); } if(playerMode!=null) { claimsBuilder = claimsBuilder.claim("playerMode", playerMode); } JWTClaimsSet claims = claimsBuilder.audience("client") .issueTime(Date.from(issuedAt)) .expirationTime(Date.from(expiresAt)) .build(); SignedJWT jwt = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("playerssl").build(), claims); JWSSigner signer = new RSASSASigner(signingKey); jwt.sign(signer); return jwt.serialize(); } }
playermode<>storyid value!
auth-app/src/main/java/gameontext/auth/common/JWTSigner.java
playermode<>storyid value!