lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 11f17f3f255b275e847ff694cd6f4ba0c88cbc7d | 0 | UIKit0/rhodes,watusi/rhodes,rhosilver/rhodes-1,tauplatform/tau,nosolosoftware/rhodes,louisatome/rhodes,tauplatform/tau,nosolosoftware/rhodes,rhosilver/rhodes-1,pslgoh/rhodes,rhosilver/rhodes-1,rhomobile/rhodes,pslgoh/rhodes,pslgoh/rhodes,jdrider/rhodes,UIKit0/rhodes,louisatome/rhodes,watusi/rhodes,rhosilver/rhodes-1,rhomobile/rhodes,rhomobile/rhodes,watusi/rhodes,tauplatform/tau,rhosilver/rhodes-1,watusi/rhodes,jdrider/rhodes,pslgoh/rhodes,UIKit0/rhodes,louisatome/rhodes,watusi/rhodes,rhomobile/rhodes,jdrider/rhodes,louisatome/rhodes,pslgoh/rhodes,UIKit0/rhodes,tauplatform/tau,tauplatform/tau,watusi/rhodes,louisatome/rhodes,nosolosoftware/rhodes,louisatome/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,nosolosoftware/rhodes,tauplatform/tau,pslgoh/rhodes,pslgoh/rhodes,nosolosoftware/rhodes,jdrider/rhodes,watusi/rhodes,UIKit0/rhodes,jdrider/rhodes,UIKit0/rhodes,louisatome/rhodes,UIKit0/rhodes,UIKit0/rhodes,jdrider/rhodes,rhomobile/rhodes,rhosilver/rhodes-1,rhomobile/rhodes,rhomobile/rhodes,pslgoh/rhodes,nosolosoftware/rhodes,nosolosoftware/rhodes,nosolosoftware/rhodes,jdrider/rhodes,watusi/rhodes,tauplatform/tau,rhosilver/rhodes-1,pslgoh/rhodes,watusi/rhodes,watusi/rhodes,louisatome/rhodes,tauplatform/tau,jdrider/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,jdrider/rhodes,rhomobile/rhodes,tauplatform/tau,tauplatform/tau,louisatome/rhodes,pslgoh/rhodes,rhomobile/rhodes,rhomobile/rhodes | /*
* rhodes
*
* Copyright (C) 2008 Rhomobile, Inc. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.rho.sync;
import com.rho.*;
import com.rho.db.*;
import com.xruby.runtime.builtin.RubyArray;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.lang.*;
public class SyncThread extends RhoThread
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Sync");
private static final int SYNC_POLL_INTERVAL_SECONDS = 300;
private static final int SYNC_POLL_INTERVAL_INFINITE = Integer.MAX_VALUE/1000;
private static final int SYNC_WAIT_BEFOREKILL_SECONDS = 3;
static SyncThread m_pInstance;
public final static int scNone = 0, scResetDB = 1, scSyncAll = 2, scSyncOne = 3, scChangePollInterval=4, scExit=5;
SyncEngine m_oSyncEngine;
RhoClassFactory m_ptrFactory;
int m_curCommand;
int m_nPollInterval;
public static SyncThread Create(RhoClassFactory factory)
{
if ( m_pInstance != null)
return m_pInstance;
m_pInstance = new SyncThread(factory);
return m_pInstance;
}
public void Destroy()
{
m_oSyncEngine.exitSync();
stop(SYNC_WAIT_BEFOREKILL_SECONDS);
LOG.INFO( "Sync engine thread shutdown" );
m_pInstance = null;
}
SyncThread(RhoClassFactory factory)
{
super(factory);
m_oSyncEngine = new SyncEngine(DBAdapter.getInstance());
m_curCommand = scNone;
m_nPollInterval = SYNC_POLL_INTERVAL_SECONDS;
m_ptrFactory = factory;
m_oSyncEngine.setFactory(factory);
start(epLow);
}
public static SyncThread getInstance(){ return m_pInstance; }
static SyncEngine getSyncEngine(){ return m_pInstance.m_oSyncEngine; }
static DBAdapter getDBAdapter(){ return DBAdapter.getInstance(); }
void addSyncCommand(int curCommand){ m_curCommand = curCommand; stopWait(); }
public void run()
{
LOG.INFO( "Starting sync engine main routine..." );
while( m_oSyncEngine.getState() != SyncEngine.esExit )
{
int nWait = m_nPollInterval > 0 ? m_nPollInterval : SYNC_POLL_INTERVAL_INFINITE;
LOG.INFO( "Sync engine blocked for " + nWait + " seconds..." );
wait(nWait);
if ( m_oSyncEngine.getState() != SyncEngine.esExit )
{
try{
processCommand();
}catch(Exception e)
{
LOG.ERROR("processCommand failed", e);
}
}
}
}
void processCommand()throws Exception
{
//TODO: implement stack of commands
switch(m_curCommand)
{
case scNone:
if ( m_nPollInterval > 0 )
m_oSyncEngine.doSyncAllSources();
break;
case scSyncAll:
m_oSyncEngine.doSyncAllSources();
break;
case scChangePollInterval:
break;
case scSyncOne:
//TODO:scSyncOne
break;
case scResetDB:
m_oSyncEngine.resetSyncDB();
break;
}
m_curCommand = scNone;
}
public void setPollInterval(int nInterval)
{
m_nPollInterval = nInterval;
if ( m_nPollInterval == 0 )
m_oSyncEngine.stopSync();
addSyncCommand(scChangePollInterval);
}
public static void doSyncAllSources()
{
getInstance().addSyncCommand(SyncThread.scSyncAll);
}
public static void initMethods(RubyClass klass) {
klass.getSingletonClass().defineMethod("dosync", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
doSyncAllSources();
}catch(Exception e)
{
LOG.ERROR("dosync failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("lock_sync_mutex",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = getDBAdapter();
db.setUnlockDB(true);
db.Lock();
}catch(Exception e)
{
LOG.ERROR("lock_sync_mutex failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("unlock_sync_mutex",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = getDBAdapter();
db.Unlock();
}catch(Exception e)
{
LOG.ERROR("unlock_sync_mutex failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("login",
new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) {
try{
String name = arg1.toStr();
String password = arg2.toStr();
//TODO: stop sync
return getSyncEngine().login(name,password) ?
ObjectFactory.createInteger(1) : ObjectFactory.createInteger(0);
}catch(Exception e)
{
LOG.ERROR("login failed", e);
//throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return ObjectFactory.createInteger(0);
}
});
klass.getSingletonClass().defineMethod("logged_in",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = getDBAdapter();
db.setUnlockDB(true);
return getSyncEngine().isLoggedIn() ?
ObjectFactory.createInteger(1) : ObjectFactory.createInteger(0);
}catch(Exception e)
{
LOG.ERROR("logged_in failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("logout",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
//TODO: stop sync
DBAdapter db = getDBAdapter();
db.setUnlockDB(true);
getSyncEngine().logout();
}catch(Exception e)
{
LOG.ERROR("logout failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("trigger_sync_db_reset",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
getInstance().addSyncCommand(SyncThread.scResetDB);
}catch(Exception e)
{
LOG.ERROR("trigger_sync_db_reset failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("set_notification",
new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
try{
int source_id = args.get(0).toInt();
String url = args.get(1).toStr();
String params = args.get(2).toStr();
getSyncEngine().setNotification(source_id, url, params);
}catch(Exception e)
{
LOG.ERROR("set_notification failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("clear_notification",
new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyBlock block) {
try{
int source_id = arg1.toInt();
getSyncEngine().clearNotification(source_id);
}catch(Exception e)
{
LOG.ERROR("clear_notification failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("set_pollinterval",
new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyBlock block) {
try{
int nInterval = arg1.toInt();
getInstance().setPollInterval(nInterval);
}catch(Exception e)
{
LOG.ERROR("set_pollinterval failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
}
}
| platform/shared/rubyJVM/src/com/rho/sync/SyncThread.java | /*
* rhodes
*
* Copyright (C) 2008 Rhomobile, Inc. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.rho.sync;
import com.rho.*;
import com.rho.db.*;
import com.xruby.runtime.builtin.RubyArray;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.lang.*;
public class SyncThread extends RhoThread
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Sync");
private static final int SYNC_POLL_INTERVAL_SECONDS = 300;
private static final int SYNC_POLL_INTERVAL_INFINITE = -1;
private static final int SYNC_WAIT_BEFOREKILL_SECONDS = 3;
static SyncThread m_pInstance;
public final static int scNone = 0, scResetDB = 1, scSyncAll = 2, scSyncOne = 3, scChangePollInterval=4, scExit=5;
SyncEngine m_oSyncEngine;
RhoClassFactory m_ptrFactory;
int m_curCommand;
int m_nPollInterval;
public static SyncThread Create(RhoClassFactory factory)
{
if ( m_pInstance != null)
return m_pInstance;
m_pInstance = new SyncThread(factory);
return m_pInstance;
}
public void Destroy()
{
m_oSyncEngine.exitSync();
stop(SYNC_WAIT_BEFOREKILL_SECONDS);
LOG.INFO( "Sync engine thread shutdown" );
m_pInstance = null;
}
SyncThread(RhoClassFactory factory)
{
super(factory);
m_oSyncEngine = new SyncEngine(DBAdapter.getInstance());
m_curCommand = scNone;
m_nPollInterval = SYNC_POLL_INTERVAL_SECONDS;
m_ptrFactory = factory;
m_oSyncEngine.setFactory(factory);
start(epLow);
}
public static SyncThread getInstance(){ return m_pInstance; }
static SyncEngine getSyncEngine(){ return m_pInstance.m_oSyncEngine; }
static DBAdapter getDBAdapter(){ return DBAdapter.getInstance(); }
void addSyncCommand(int curCommand){ m_curCommand = curCommand; stopWait(); }
public void run()
{
LOG.INFO( "Starting sync engine main routine..." );
while( m_oSyncEngine.getState() != SyncEngine.esExit )
{
int nWait = m_nPollInterval > 0 ? m_nPollInterval : SYNC_POLL_INTERVAL_INFINITE;
LOG.INFO( "Sync engine blocked for " + nWait + " seconds..." );
wait(nWait);
if ( m_oSyncEngine.getState() != SyncEngine.esExit )
{
try{
processCommand();
}catch(Exception e)
{
LOG.ERROR("processCommand failed", e);
}
}
}
}
void processCommand()throws Exception
{
//TODO: implement stack of commands
switch(m_curCommand)
{
case scNone:
if ( m_nPollInterval > 0 )
m_oSyncEngine.doSyncAllSources();
break;
case scSyncAll:
m_oSyncEngine.doSyncAllSources();
break;
case scChangePollInterval:
break;
case scSyncOne:
//TODO:scSyncOne
break;
case scResetDB:
m_oSyncEngine.resetSyncDB();
break;
}
m_curCommand = scNone;
}
void setPollInterval(int nInterval)
{
m_nPollInterval = nInterval;
if ( m_nPollInterval == 0 )
m_oSyncEngine.stopSync();
addSyncCommand(scChangePollInterval);
}
public static void doSyncAllSources()
{
getInstance().addSyncCommand(SyncThread.scSyncAll);
}
public static void initMethods(RubyClass klass) {
klass.getSingletonClass().defineMethod("dosync", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
doSyncAllSources();
}catch(Exception e)
{
LOG.ERROR("dosync failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("lock_sync_mutex",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = getDBAdapter();
db.setUnlockDB(true);
db.Lock();
}catch(Exception e)
{
LOG.ERROR("lock_sync_mutex failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("unlock_sync_mutex",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = getDBAdapter();
db.Unlock();
}catch(Exception e)
{
LOG.ERROR("unlock_sync_mutex failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("login",
new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block) {
try{
String name = arg1.toStr();
String password = arg2.toStr();
//TODO: stop sync
return getSyncEngine().login(name,password) ?
ObjectFactory.createInteger(1) : ObjectFactory.createInteger(0);
}catch(Exception e)
{
LOG.ERROR("login failed", e);
//throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return ObjectFactory.createInteger(0);
}
});
klass.getSingletonClass().defineMethod("logged_in",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = getDBAdapter();
db.setUnlockDB(true);
return getSyncEngine().isLoggedIn() ?
ObjectFactory.createInteger(1) : ObjectFactory.createInteger(0);
}catch(Exception e)
{
LOG.ERROR("logged_in failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("logout",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
//TODO: stop sync
DBAdapter db = getDBAdapter();
db.setUnlockDB(true);
getSyncEngine().logout();
}catch(Exception e)
{
LOG.ERROR("logout failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("trigger_sync_db_reset",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
getInstance().addSyncCommand(SyncThread.scResetDB);
}catch(Exception e)
{
LOG.ERROR("trigger_sync_db_reset failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("set_notification",
new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
try{
int source_id = args.get(0).toInt();
String url = args.get(1).toStr();
String params = args.get(2).toStr();
getSyncEngine().setNotification(source_id, url, params);
}catch(Exception e)
{
LOG.ERROR("set_notification failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("clear_notification",
new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyBlock block) {
try{
int source_id = arg1.toInt();
getSyncEngine().clearNotification(source_id);
}catch(Exception e)
{
LOG.ERROR("clear_notification failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("set_pollinterval",
new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyBlock block) {
try{
int nInterval = arg1.toInt();
getInstance().setPollInterval(nInterval);
}catch(Exception e)
{
LOG.ERROR("set_pollinterval failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
}
}
| [#516] - Background sync on for Blackberry
| platform/shared/rubyJVM/src/com/rho/sync/SyncThread.java | [#516] - Background sync on for Blackberry | <ide><path>latform/shared/rubyJVM/src/com/rho/sync/SyncThread.java
<ide> private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
<ide> new RhoLogger("Sync");
<ide> private static final int SYNC_POLL_INTERVAL_SECONDS = 300;
<del> private static final int SYNC_POLL_INTERVAL_INFINITE = -1;
<add> private static final int SYNC_POLL_INTERVAL_INFINITE = Integer.MAX_VALUE/1000;
<ide> private static final int SYNC_WAIT_BEFOREKILL_SECONDS = 3;
<ide>
<ide> static SyncThread m_pInstance;
<ide> m_curCommand = scNone;
<ide> }
<ide>
<del> void setPollInterval(int nInterval)
<add> public void setPollInterval(int nInterval)
<ide> {
<ide> m_nPollInterval = nInterval;
<ide> if ( m_nPollInterval == 0 ) |
|
Java | mit | bcd691eb3ab220fecdb5f3078b9fd9630ecdfbfc | 0 | pholser/junit-quickcheck | /*
The MIT License
Copyright (c) 2010-2020 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pholser.junit.quickcheck;
import static com.pholser.junit.quickcheck.Classes.currentMethodName;
import static com.pholser.junit.quickcheck.Classes.resourceAsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import static org.junit.runners.MethodSorters.NAME_ASCENDING;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import com.pholser.junit.quickcheck.test.generator.Foo;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
public class UsualJUnitMachineryOnTraitBasedPropertyTest {
private static final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
private static final PrintStream fakeOut =
new PrintStream(bytesOut, true);
@ClassRule public static final ExternalResource sysoutRedirection =
new ExternalResource() {
@Override protected void before() {
System.setOut(fakeOut);
}
@Override protected void after() {
System.setOut(System.out);
}
};
@After public void clearBytesOut() throws Exception {
bytesOut.reset();
}
@Test public void expectedOrderingOfMethods() throws Exception {
assertThat(testResult(Leaf.class), isSuccessful());
assertEquals(
resourceAsString("trait-property-test-expected.txt"),
bytesOut.toString().replaceAll(System.lineSeparator(), "\r\n"));
}
public interface TraitA {
@ClassRule ExternalResource firstTraitAClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::firstTraitAClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitA::firstTraitAClassRuleField::after");
}
};
@ClassRule ExternalResource secondTraitAClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::secondTraitAClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitA::secondTraitAClassRuleField::after");
}
};
@ClassRule static ExternalResource firstTraitAClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::firstTraitAClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitA::firstTraitAClassRuleMethod::after");
}
};
}
@ClassRule static ExternalResource secondTraitAClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::secondTraitAClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitA::secondTraitAClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitARule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitA::firstTraitARule::before");
}
@Override protected void after() {
System.out.println("TraitA::firstTraitARule::after");
}
};
}
@Rule default ExternalResource secondTraitARule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitA::secondTraitARule::before");
}
@Override protected void after() {
System.out.println("TraitA::secondTraitARule::after");
}
};
}
@BeforeClass static void traitAClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitAClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitAInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitASetUp() {
System.out.println(currentMethodName());
}
@After default void traitATearDown() {
System.out.println(currentMethodName());
}
@After default void traitAReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitAClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitAClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitAProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitATest() {
System.out.println(currentMethodName());
}
}
public interface TraitB extends TraitA {
@ClassRule ExternalResource firstTraitBClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::firstTraitBClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitB::firstTraitBClassRuleField::after");
}
};
@ClassRule ExternalResource secondTraitBClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::secondTraitBClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitB::secondTraitBClassRuleField::after");
}
};
@ClassRule static ExternalResource firstTraitBClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::firstTraitBClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitB::firstTraitBClassRuleMethod::after");
}
};
}
@ClassRule static ExternalResource secondTraitBClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::secondTraitBClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitB::secondTraitBClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitBRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitB::firstTraitBRule::before");
}
@Override protected void after() {
System.out.println("TraitB::firstTraitBRule::after");
}
};
}
@Rule default ExternalResource secondTraitBRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitB::secondTraitBRule::before");
}
@Override protected void after() {
System.out.println("TraitB::secondTraitBRule::after");
}
};
}
@BeforeClass static void traitBClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitBClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitBInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitBSetUp() {
System.out.println(currentMethodName());
}
@After default void traitBTearDown() {
System.out.println(currentMethodName());
}
@After default void traitBReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitBClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitBClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitBProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitBTest() {
System.out.println(currentMethodName());
}
}
public interface TraitC {
@ClassRule ExternalResource firstTraitCClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::firstTraitCClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitC::firstTraitCClassRuleField::after");
}
};
@ClassRule ExternalResource secondTraitCClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::secondTraitCClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitC::secondTraitCClassRuleField::after");
}
};
@ClassRule static ExternalResource firstTraitCClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::firstTraitCClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitC::firstTraitCClassRuleMethod::after");
}
};
}
@ClassRule static ExternalResource secondTraitCClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::secondTraitCClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitC::secondTraitCClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitCRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitC::firstTraitCRule::before");
}
@Override protected void after() {
System.out.println("TraitC::firstTraitCRule::after");
}
};
}
@Rule default ExternalResource secondTraitCRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitC::secondTraitCRule::before");
}
@Override protected void after() {
System.out.println("TraitC::secondTraitCRule::after");
}
};
}
@BeforeClass static void traitCClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitCClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitCInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitCSetUp() {
System.out.println(currentMethodName());
}
@After default void traitCTearDown() {
System.out.println(currentMethodName());
}
@After default void traitCReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitCClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitCClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitCProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitCTest() {
System.out.println(currentMethodName());
}
}
public interface TraitD {
@ClassRule ExternalResource traitDClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("TraitD::traitDClassRuleField::before");
}
@Override protected void after() {
System.out.println("TraitD::traitDClassRuleField::after");
}
};
@ClassRule static ExternalResource traitDClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitD::traitDClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitD::traitDClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitDRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitD::firstTraitDRule::before");
}
@Override protected void after() {
System.out.println("TraitD::firstTraitDRule::after");
}
};
}
@Rule default ExternalResource secondTraitDRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitD::secondTraitDRule::before");
}
@Override protected void after() {
System.out.println("TraitD::secondTraitDRule::after");
}
};
}
@BeforeClass static void traitDClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitDClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitDInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitDSetUp() {
System.out.println(currentMethodName());
}
@After default void traitDTearDown() {
System.out.println(currentMethodName());
}
@After default void traitDReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitDClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitDClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitDProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitDTest() {
System.out.println(currentMethodName());
}
}
public interface TraitE {
@ClassRule ExternalResource traitEClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("TraitE::traitEClassRuleField::before");
}
@Override protected void after() {
System.out.println("TraitE::traitEClassRuleField::after");
}
};
@ClassRule static ExternalResource traitEClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitE::traitEClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitE::traitEClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitERule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitE::firstTraitERule::before");
}
@Override protected void after() {
System.out.println("TraitE::firstTraitERule::after");
}
};
}
@Rule default ExternalResource secondTraitERule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitE::secondTraitERule::before");
}
@Override protected void after() {
System.out.println("TraitE::secondTraitERule::after");
}
};
}
@BeforeClass static void traitEClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitEClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitEInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitESetUp() {
System.out.println(currentMethodName());
}
@After default void traitETearDown() {
System.out.println(currentMethodName());
}
@After default void traitEReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitEClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitEClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitEProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitETest() {
System.out.println(currentMethodName());
}
}
public static abstract class Root implements TraitB {
@ClassRule
public static final ExternalResource firstRootClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::firstRootClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Root::firstRootClassRuleField::after");
}
};
@ClassRule
public static final ExternalResource secondRootClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::secondRootClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Root::secondRootClassRuleField::after");
}
};
@ClassRule public static ExternalResource firstRootClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::firstRootClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Root::firstRootClassRuleMethod::after");
}
};
}
@ClassRule
public static ExternalResource secondRootClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::secondRootClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Root::secondRootClassRuleMethod::after");
}
};
}
@Rule public final ExternalResource firstRootRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Root::firstRootRuleField::before");
}
@Override protected void after() {
System.out.println("Root::firstRootRuleField::after");
}
};
@Rule public final ExternalResource secondRootRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Root::secondRootRuleField::before");
}
@Override protected void after() {
System.out.println("Root::secondRootRuleField::after");
}
};
@Rule public final ExternalResource firstRootRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Root::firstRootRuleMethod::before");
}
@Override protected void after() {
System.out.println("Root::firstRootRuleMethod::after");
}
};
}
@Rule public final ExternalResource secondRootRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Root::secondRootRuleMethod::before");
}
@Override protected void after() {
System.out.println("Root::secondRootRuleMethod::after");
}
};
}
@BeforeClass public static void rootClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass public static void rootClassSetUp() {
System.out.println(currentMethodName());
}
@Before public void rootInitialize() {
System.out.println(currentMethodName());
}
@Before public void rootSetUp() {
System.out.println(currentMethodName());
}
@After public void rootTearDown() {
System.out.println(currentMethodName());
}
@After public void rootReset() {
System.out.println(currentMethodName());
}
@AfterClass public static void rootClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass public static void rootClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) public void rootProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test public void rootTest() {
System.out.println(currentMethodName());
}
}
public static class Internal extends Root implements TraitD, TraitE {
@ClassRule
public static final ExternalResource firstInternalClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalClassRuleField::after");
}
};
@ClassRule
public static final ExternalResource secondInternalClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalClassRuleField::after");
}
};
@ClassRule
public static ExternalResource firstInternalClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalClassRuleMethod::after");
}
};
}
@ClassRule
public static ExternalResource secondInternalClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalClassRuleMethod::after");
}
};
}
@Rule public final ExternalResource firstInternalRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalRuleField::after");
}
};
@Rule public final ExternalResource secondInternalRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalRuleField::after");
}
};
@Rule public final ExternalResource firstInternalRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalRuleMethod::after");
}
};
}
@Rule public final ExternalResource secondInternalRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalRuleMethod::after");
}
};
}
@BeforeClass public static void internalClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass public static void internalClassSetUp() {
System.out.println(currentMethodName());
}
@Before public void internalInitialize() {
System.out.println(currentMethodName());
}
@Before public void internalSetUp() {
System.out.println(currentMethodName());
}
@After public void internalTearDown() {
System.out.println(currentMethodName());
}
@After public void internalReset() {
System.out.println(currentMethodName());
}
@AfterClass public static void internalClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass public static void internalClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) public void internalProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test public void internalTest() {
System.out.println(currentMethodName());
}
}
@RunWith(JUnitQuickcheck.class)
@FixMethodOrder(NAME_ASCENDING)
public static class Leaf extends Internal implements TraitC {
@ClassRule
public static final ExternalResource firstLeafClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::firstLeafClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Leaf::firstLeafClassRuleField::after");
}
};
@ClassRule
public static final ExternalResource secondLeafClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::secondLeafClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Leaf::secondLeafClassRuleField::after");
}
};
@ClassRule public static ExternalResource firstLeafClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::firstLeafClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Leaf::firstLeafClassRuleMethod::after");
}
};
}
@ClassRule
public static ExternalResource secondLeafClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::secondLeafClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Leaf::secondLeafClassRuleMethod::after");
}
};
}
@Rule public final ExternalResource firstLeafRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::firstLeafRuleField::before");
}
@Override protected void after() {
System.out.println("Leaf::firstLeafRuleField::after");
}
};
@Rule public final ExternalResource secondLeafRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::secondLeafRuleField::before");
}
@Override protected void after() {
System.out.println("Leaf::secondLeafRuleField::after");
}
};
@Rule public final ExternalResource firstLeafRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::firstLeafRuleMethod::before");
}
@Override protected void after() {
System.out.println("Leaf::firstLeafRuleMethod::after");
}
};
}
@Rule public final ExternalResource secondLeafRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::secondLeafRuleMethod::before");
}
@Override protected void after() {
System.out.println("Leaf::secondLeafRuleMethod::after");
}
};
}
@BeforeClass public static void leafClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass public static void leafClassSetUp() {
System.out.println(currentMethodName());
}
@Before public void leafInitialize() {
System.out.println(currentMethodName());
}
@Before public void leafSetUp() {
System.out.println(currentMethodName());
}
@After public void leafTearDown() {
System.out.println(currentMethodName());
}
@After public void leafReset() {
System.out.println(currentMethodName());
}
@AfterClass public static void leafClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass public static void leafClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) public void leafProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test public void leafTest() {
System.out.println(currentMethodName());
}
}
}
| core/src/test/java/com/pholser/junit/quickcheck/UsualJUnitMachineryOnTraitBasedPropertyTest.java | /*
The MIT License
Copyright (c) 2010-2020 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pholser.junit.quickcheck;
import static com.pholser.junit.quickcheck.Classes.currentMethodName;
import static com.pholser.junit.quickcheck.Classes.resourceAsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import static org.junit.runners.MethodSorters.NAME_ASCENDING;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import com.pholser.junit.quickcheck.test.generator.Foo;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
public class UsualJUnitMachineryOnTraitBasedPropertyTest {
private static final OutputStream bytesOut = new ByteArrayOutputStream();
private static final PrintStream fakeOut =
new PrintStream(bytesOut, true);
@ClassRule public static final ExternalResource sysoutRedirection =
new ExternalResource() {
@Override protected void before() {
System.setOut(fakeOut);
}
@Override protected void after() {
System.setOut(System.out);
}
};
@Test public void expectedOrderingOfMethods() throws Exception {
assertThat(testResult(Leaf.class), isSuccessful());
assertEquals(
resourceAsString("trait-property-test-expected.txt"),
bytesOut.toString());
}
public interface TraitA {
@ClassRule ExternalResource firstTraitAClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::firstTraitAClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitA::firstTraitAClassRuleField::after");
}
};
@ClassRule ExternalResource secondTraitAClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::secondTraitAClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitA::secondTraitAClassRuleField::after");
}
};
@ClassRule static ExternalResource firstTraitAClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::firstTraitAClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitA::firstTraitAClassRuleMethod::after");
}
};
}
@ClassRule static ExternalResource secondTraitAClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitA::secondTraitAClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitA::secondTraitAClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitARule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitA::firstTraitARule::before");
}
@Override protected void after() {
System.out.println("TraitA::firstTraitARule::after");
}
};
}
@Rule default ExternalResource secondTraitARule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitA::secondTraitARule::before");
}
@Override protected void after() {
System.out.println("TraitA::secondTraitARule::after");
}
};
}
@BeforeClass static void traitAClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitAClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitAInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitASetUp() {
System.out.println(currentMethodName());
}
@After default void traitATearDown() {
System.out.println(currentMethodName());
}
@After default void traitAReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitAClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitAClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitAProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitATest() {
System.out.println(currentMethodName());
}
}
public interface TraitB extends TraitA {
@ClassRule ExternalResource firstTraitBClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::firstTraitBClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitB::firstTraitBClassRuleField::after");
}
};
@ClassRule ExternalResource secondTraitBClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::secondTraitBClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitB::secondTraitBClassRuleField::after");
}
};
@ClassRule static ExternalResource firstTraitBClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::firstTraitBClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitB::firstTraitBClassRuleMethod::after");
}
};
}
@ClassRule static ExternalResource secondTraitBClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitB::secondTraitBClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitB::secondTraitBClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitBRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitB::firstTraitBRule::before");
}
@Override protected void after() {
System.out.println("TraitB::firstTraitBRule::after");
}
};
}
@Rule default ExternalResource secondTraitBRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitB::secondTraitBRule::before");
}
@Override protected void after() {
System.out.println("TraitB::secondTraitBRule::after");
}
};
}
@BeforeClass static void traitBClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitBClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitBInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitBSetUp() {
System.out.println(currentMethodName());
}
@After default void traitBTearDown() {
System.out.println(currentMethodName());
}
@After default void traitBReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitBClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitBClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitBProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitBTest() {
System.out.println(currentMethodName());
}
}
public interface TraitC {
@ClassRule ExternalResource firstTraitCClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::firstTraitCClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitC::firstTraitCClassRuleField::after");
}
};
@ClassRule ExternalResource secondTraitCClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::secondTraitCClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"TraitC::secondTraitCClassRuleField::after");
}
};
@ClassRule static ExternalResource firstTraitCClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::firstTraitCClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitC::firstTraitCClassRuleMethod::after");
}
};
}
@ClassRule static ExternalResource secondTraitCClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitC::secondTraitCClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitC::secondTraitCClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitCRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitC::firstTraitCRule::before");
}
@Override protected void after() {
System.out.println("TraitC::firstTraitCRule::after");
}
};
}
@Rule default ExternalResource secondTraitCRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitC::secondTraitCRule::before");
}
@Override protected void after() {
System.out.println("TraitC::secondTraitCRule::after");
}
};
}
@BeforeClass static void traitCClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitCClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitCInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitCSetUp() {
System.out.println(currentMethodName());
}
@After default void traitCTearDown() {
System.out.println(currentMethodName());
}
@After default void traitCReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitCClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitCClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitCProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitCTest() {
System.out.println(currentMethodName());
}
}
public interface TraitD {
@ClassRule ExternalResource traitDClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("TraitD::traitDClassRuleField::before");
}
@Override protected void after() {
System.out.println("TraitD::traitDClassRuleField::after");
}
};
@ClassRule static ExternalResource traitDClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitD::traitDClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitD::traitDClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitDRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitD::firstTraitDRule::before");
}
@Override protected void after() {
System.out.println("TraitD::firstTraitDRule::after");
}
};
}
@Rule default ExternalResource secondTraitDRule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitD::secondTraitDRule::before");
}
@Override protected void after() {
System.out.println("TraitD::secondTraitDRule::after");
}
};
}
@BeforeClass static void traitDClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitDClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitDInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitDSetUp() {
System.out.println(currentMethodName());
}
@After default void traitDTearDown() {
System.out.println(currentMethodName());
}
@After default void traitDReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitDClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitDClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitDProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitDTest() {
System.out.println(currentMethodName());
}
}
public interface TraitE {
@ClassRule ExternalResource traitEClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("TraitE::traitEClassRuleField::before");
}
@Override protected void after() {
System.out.println("TraitE::traitEClassRuleField::after");
}
};
@ClassRule static ExternalResource traitEClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"TraitE::traitEClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"TraitE::traitEClassRuleMethod::after");
}
};
}
@Rule default ExternalResource firstTraitERule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitE::firstTraitERule::before");
}
@Override protected void after() {
System.out.println("TraitE::firstTraitERule::after");
}
};
}
@Rule default ExternalResource secondTraitERule() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("TraitE::secondTraitERule::before");
}
@Override protected void after() {
System.out.println("TraitE::secondTraitERule::after");
}
};
}
@BeforeClass static void traitEClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass static void traitEClassSetUp() {
System.out.println(currentMethodName());
}
@Before default void traitEInitialize() {
System.out.println(currentMethodName());
}
@Before default void traitESetUp() {
System.out.println(currentMethodName());
}
@After default void traitETearDown() {
System.out.println(currentMethodName());
}
@After default void traitEReset() {
System.out.println(currentMethodName());
}
@AfterClass static void traitEClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass static void traitEClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) default void traitEProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test default void traitETest() {
System.out.println(currentMethodName());
}
}
public static abstract class Root implements TraitB {
@ClassRule
public static final ExternalResource firstRootClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::firstRootClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Root::firstRootClassRuleField::after");
}
};
@ClassRule
public static final ExternalResource secondRootClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::secondRootClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Root::secondRootClassRuleField::after");
}
};
@ClassRule public static ExternalResource firstRootClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::firstRootClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Root::firstRootClassRuleMethod::after");
}
};
}
@ClassRule
public static ExternalResource secondRootClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Root::secondRootClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Root::secondRootClassRuleMethod::after");
}
};
}
@Rule public final ExternalResource firstRootRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Root::firstRootRuleField::before");
}
@Override protected void after() {
System.out.println("Root::firstRootRuleField::after");
}
};
@Rule public final ExternalResource secondRootRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Root::secondRootRuleField::before");
}
@Override protected void after() {
System.out.println("Root::secondRootRuleField::after");
}
};
@Rule public final ExternalResource firstRootRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Root::firstRootRuleMethod::before");
}
@Override protected void after() {
System.out.println("Root::firstRootRuleMethod::after");
}
};
}
@Rule public final ExternalResource secondRootRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Root::secondRootRuleMethod::before");
}
@Override protected void after() {
System.out.println("Root::secondRootRuleMethod::after");
}
};
}
@BeforeClass public static void rootClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass public static void rootClassSetUp() {
System.out.println(currentMethodName());
}
@Before public void rootInitialize() {
System.out.println(currentMethodName());
}
@Before public void rootSetUp() {
System.out.println(currentMethodName());
}
@After public void rootTearDown() {
System.out.println(currentMethodName());
}
@After public void rootReset() {
System.out.println(currentMethodName());
}
@AfterClass public static void rootClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass public static void rootClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) public void rootProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test public void rootTest() {
System.out.println(currentMethodName());
}
}
public static class Internal extends Root implements TraitD, TraitE {
@ClassRule
public static final ExternalResource firstInternalClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalClassRuleField::after");
}
};
@ClassRule
public static final ExternalResource secondInternalClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalClassRuleField::after");
}
};
@ClassRule
public static ExternalResource firstInternalClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalClassRuleMethod::after");
}
};
}
@ClassRule
public static ExternalResource secondInternalClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalClassRuleMethod::after");
}
};
}
@Rule public final ExternalResource firstInternalRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalRuleField::after");
}
};
@Rule public final ExternalResource secondInternalRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalRuleField::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalRuleField::after");
}
};
@Rule public final ExternalResource firstInternalRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::firstInternalRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::firstInternalRuleMethod::after");
}
};
}
@Rule public final ExternalResource secondInternalRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Internal::secondInternalRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Internal::secondInternalRuleMethod::after");
}
};
}
@BeforeClass public static void internalClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass public static void internalClassSetUp() {
System.out.println(currentMethodName());
}
@Before public void internalInitialize() {
System.out.println(currentMethodName());
}
@Before public void internalSetUp() {
System.out.println(currentMethodName());
}
@After public void internalTearDown() {
System.out.println(currentMethodName());
}
@After public void internalReset() {
System.out.println(currentMethodName());
}
@AfterClass public static void internalClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass public static void internalClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) public void internalProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test public void internalTest() {
System.out.println(currentMethodName());
}
}
@RunWith(JUnitQuickcheck.class)
@FixMethodOrder(NAME_ASCENDING)
public static class Leaf extends Internal implements TraitC {
@ClassRule
public static final ExternalResource firstLeafClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::firstLeafClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Leaf::firstLeafClassRuleField::after");
}
};
@ClassRule
public static final ExternalResource secondLeafClassRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::secondLeafClassRuleField::before");
}
@Override protected void after() {
System.out.println(
"Leaf::secondLeafClassRuleField::after");
}
};
@ClassRule public static ExternalResource firstLeafClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::firstLeafClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Leaf::firstLeafClassRuleMethod::after");
}
};
}
@ClassRule
public static ExternalResource secondLeafClassRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println(
"Leaf::secondLeafClassRuleMethod::before");
}
@Override protected void after() {
System.out.println(
"Leaf::secondLeafClassRuleMethod::after");
}
};
}
@Rule public final ExternalResource firstLeafRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::firstLeafRuleField::before");
}
@Override protected void after() {
System.out.println("Leaf::firstLeafRuleField::after");
}
};
@Rule public final ExternalResource secondLeafRuleField =
new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::secondLeafRuleField::before");
}
@Override protected void after() {
System.out.println("Leaf::secondLeafRuleField::after");
}
};
@Rule public final ExternalResource firstLeafRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::firstLeafRuleMethod::before");
}
@Override protected void after() {
System.out.println("Leaf::firstLeafRuleMethod::after");
}
};
}
@Rule public final ExternalResource secondLeafRuleMethod() {
return new ExternalResource() {
@Override protected void before() {
System.out.println("Leaf::secondLeafRuleMethod::before");
}
@Override protected void after() {
System.out.println("Leaf::secondLeafRuleMethod::after");
}
};
}
@BeforeClass public static void leafClassInitialize() {
System.out.println(currentMethodName());
}
@BeforeClass public static void leafClassSetUp() {
System.out.println(currentMethodName());
}
@Before public void leafInitialize() {
System.out.println(currentMethodName());
}
@Before public void leafSetUp() {
System.out.println(currentMethodName());
}
@After public void leafTearDown() {
System.out.println(currentMethodName());
}
@After public void leafReset() {
System.out.println(currentMethodName());
}
@AfterClass public static void leafClassTearDown() {
System.out.println(currentMethodName());
}
@AfterClass public static void leafClassReset() {
System.out.println(currentMethodName());
}
@Property(trials = 2) public void leafProperty(Foo f) {
System.out.println(currentMethodName());
}
@Test public void leafTest() {
System.out.println(currentMethodName());
}
}
}
| Fix flakiness in UsualJUnitMachineryOnTraitBasedPropertyTest (#287)
| core/src/test/java/com/pholser/junit/quickcheck/UsualJUnitMachineryOnTraitBasedPropertyTest.java | Fix flakiness in UsualJUnitMachineryOnTraitBasedPropertyTest (#287) | <ide><path>ore/src/test/java/com/pholser/junit/quickcheck/UsualJUnitMachineryOnTraitBasedPropertyTest.java
<ide> import org.junit.runner.RunWith;
<ide>
<ide> public class UsualJUnitMachineryOnTraitBasedPropertyTest {
<del> private static final OutputStream bytesOut = new ByteArrayOutputStream();
<add> private static final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
<ide> private static final PrintStream fakeOut =
<ide> new PrintStream(bytesOut, true);
<ide>
<ide> }
<ide> };
<ide>
<add> @After public void clearBytesOut() throws Exception {
<add> bytesOut.reset();
<add> }
<add>
<ide> @Test public void expectedOrderingOfMethods() throws Exception {
<ide> assertThat(testResult(Leaf.class), isSuccessful());
<ide> assertEquals(
<ide> resourceAsString("trait-property-test-expected.txt"),
<del> bytesOut.toString());
<add> bytesOut.toString().replaceAll(System.lineSeparator(), "\r\n"));
<ide> }
<ide>
<ide> public interface TraitA { |
|
Java | apache-2.0 | d19ffa0ba83e7eaafc828a7ab7d9a943b8f792a6 | 0 | PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.pdxfinder.services;
//import org.apache.commons.cli.Option;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.ogm.json.JSONArray;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.graph.dao.*;
import org.pdxfinder.graph.repositories.*;
import org.pdxfinder.services.ds.Harmonizer;
import org.pdxfinder.services.ds.Standardizer;
import org.pdxfinder.services.dto.LoaderDTO;
import org.pdxfinder.services.dto.NodeSuggestionDTO;
import org.pdxfinder.services.reporting.LogEntity;
import org.pdxfinder.services.reporting.LogEntityType;
import org.pdxfinder.services.reporting.MarkerLogEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.cache.annotation.Cacheable;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The hope was to put a lot of reused repository actions into one place ie find
* or create a node or create a node with that requires a number of 'child'
* nodes that are terms
*
* @author sbn
*/
@Component
public class DataImportService {
//public static Option loadAll = new Option("LoadAll", false, "Load all PDX Finder data");
private TumorTypeRepository tumorTypeRepository;
private HostStrainRepository hostStrainRepository;
private EngraftmentTypeRepository engraftmentTypeRepository;
private EngraftmentSiteRepository engraftmentSiteRepository;
private EngraftmentMaterialRepository engraftmentMaterialRepository;
private GroupRepository groupRepository;
private PatientRepository patientRepository;
private ModelCreationRepository modelCreationRepository;
private TissueRepository tissueRepository;
private PatientSnapshotRepository patientSnapshotRepository;
private SampleRepository sampleRepository;
private MarkerRepository markerRepository;
private MarkerAssociationRepository markerAssociationRepository;
private MolecularCharacterizationRepository molecularCharacterizationRepository;
private QualityAssuranceRepository qualityAssuranceRepository;
private OntologyTermRepository ontologyTermRepository;
private SpecimenRepository specimenRepository;
private PlatformRepository platformRepository;
private PlatformAssociationRepository platformAssociationRepository;
private DataProjectionRepository dataProjectionRepository;
private TreatmentSummaryRepository treatmentSummaryRepository;
private TreatmentProtocolRepository treatmentProtocolRepository;
private CurrentTreatmentRepository currentTreatmentRepository;
private ExternalUrlRepository externalUrlRepository;
private final static Logger log = LoggerFactory.getLogger(DataImportService.class);
private HashMap<String, Marker> markersBySymbol;
private HashMap<String, Marker> markersByPrevSymbol;
private HashMap<String, Marker> markersBySynonym;
public DataImportService(TumorTypeRepository tumorTypeRepository,
HostStrainRepository hostStrainRepository,
EngraftmentTypeRepository engraftmentTypeRepository,
EngraftmentSiteRepository engraftmentSiteRepository,
EngraftmentMaterialRepository engraftmentMaterialRepository,
GroupRepository groupRepository,
PatientRepository patientRepository,
ModelCreationRepository modelCreationRepository,
TissueRepository tissueRepository,
PatientSnapshotRepository patientSnapshotRepository,
SampleRepository sampleRepository,
MarkerRepository markerRepository,
MarkerAssociationRepository markerAssociationRepository,
MolecularCharacterizationRepository molecularCharacterizationRepository,
QualityAssuranceRepository qualityAssuranceRepository,
OntologyTermRepository ontologyTermRepository,
SpecimenRepository specimenRepository,
PlatformRepository platformRepository,
PlatformAssociationRepository platformAssociationRepository,
DataProjectionRepository dataProjectionRepository,
TreatmentSummaryRepository treatmentSummaryRepository,
TreatmentProtocolRepository treatmentProtocolRepository,
CurrentTreatmentRepository currentTreatmentRepository,
ExternalUrlRepository externalUrlRepository) {
Assert.notNull(tumorTypeRepository, "tumorTypeRepository cannot be null");
Assert.notNull(hostStrainRepository, "hostStrainRepository cannot be null");
Assert.notNull(engraftmentTypeRepository, "implantationTypeRepository cannot be null");
Assert.notNull(engraftmentSiteRepository, "implantationSiteRepository cannot be null");
Assert.notNull(engraftmentMaterialRepository, "engraftmentMaterialRepository cannot be null");
Assert.notNull(groupRepository, "GroupRepository cannot be null");
Assert.notNull(patientRepository, "patientRepository cannot be null");
Assert.notNull(modelCreationRepository, "modelCreationRepository cannot be null");
Assert.notNull(tissueRepository, "tissueRepository cannot be null");
Assert.notNull(patientSnapshotRepository, "patientSnapshotRepository cannot be null");
Assert.notNull(sampleRepository, "sampleRepository cannot be null");
Assert.notNull(markerRepository, "markerRepository cannot be null");
Assert.notNull(markerAssociationRepository, "markerAssociationRepository cannot be null");
Assert.notNull(molecularCharacterizationRepository, "molecularCharacterizationRepository cannot be null");
Assert.notNull(externalUrlRepository, "externalUrlRepository cannot be null");
this.tumorTypeRepository = tumorTypeRepository;
this.hostStrainRepository = hostStrainRepository;
this.engraftmentTypeRepository = engraftmentTypeRepository;
this.engraftmentSiteRepository = engraftmentSiteRepository;
this.engraftmentMaterialRepository = engraftmentMaterialRepository;
this.groupRepository = groupRepository;
this.patientRepository = patientRepository;
this.modelCreationRepository = modelCreationRepository;
this.tissueRepository = tissueRepository;
this.patientSnapshotRepository = patientSnapshotRepository;
this.sampleRepository = sampleRepository;
this.markerRepository = markerRepository;
this.markerAssociationRepository = markerAssociationRepository;
this.molecularCharacterizationRepository = molecularCharacterizationRepository;
this.qualityAssuranceRepository = qualityAssuranceRepository;
this.ontologyTermRepository = ontologyTermRepository;
this.specimenRepository = specimenRepository;
this.platformRepository = platformRepository;
this.platformAssociationRepository = platformAssociationRepository;
this.dataProjectionRepository = dataProjectionRepository;
this.treatmentSummaryRepository = treatmentSummaryRepository;
this.treatmentProtocolRepository = treatmentProtocolRepository;
this.currentTreatmentRepository = currentTreatmentRepository;
this.externalUrlRepository = externalUrlRepository;
this.markersBySymbol = new HashMap<>();
this.markersByPrevSymbol = new HashMap<>();
this.markersBySynonym = new HashMap<>();
}
public Group getGroup(String name, String abbrev, String type){
Group g = groupRepository.findByNameAndType(name, type);
if(g == null){
log.info("Group not found. Creating", name);
g = new Group(name, abbrev, type);
groupRepository.save(g);
}
return g;
}
public Group getProviderGroup(String name, String abbrev, String description, String providerType, String accessibility,
String accessModalities, String contact, String url){
Group g = groupRepository.findByNameAndType(name, "Provider");
if(g == null){
log.info("Provider group not found. Creating", name);
g = new Group(name, abbrev, description, providerType, accessibility, accessModalities, contact, url);
groupRepository.save(g);
}
return g;
}
public Group getPublicationGroup(String publicationId){
Group g = groupRepository.findByPubmedIdAndType(publicationId, "Publication");
if(g == null){
log.info("Publication group not found. Creating", publicationId);
g = new Group();
g.setType("Publication");
g.setPubMedId(publicationId);
groupRepository.save(g);
}
return g;
}
public Group getProjectGroup(String groupName){
Group g = groupRepository.findByNameAndType(groupName, "Project");
if(g == null){
log.info("Project group not found. Creating", groupName);
g = new Group();
g.setType("Project");
g.setName(groupName);
groupRepository.save(g);
}
return g;
}
public List<Group> getAllProviderGroups(){
return groupRepository.findAllByType("Provider");
}
public void saveGroup(Group g){
groupRepository.save(g);
}
public ExternalUrl getExternalUrl(ExternalUrl.Type type, String url) {
ExternalUrl externalUrl = externalUrlRepository.findByTypeAndUrl(type.getValue(), url);
if (externalUrl == null) {
log.info("External URL '{}' not found. Creating", type);
externalUrl = new ExternalUrl(
type,
url);
externalUrlRepository.save(externalUrl);
}
return externalUrl;
}
public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, QualityAssurance qa, List<ExternalUrl> externalUrls) {
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls);
modelCreation.addRelatedSample(sample);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, List<QualityAssurance> qa, List<ExternalUrl> externalUrls) {
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls);
modelCreation.addRelatedSample(sample);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public boolean isExistingModel(String dataSource, String modelId){
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(modelId, dataSource);
if(modelCreation == null) return false;
return true;
}
public Collection<ModelCreation> findAllModelsPlatforms(){
return modelCreationRepository.findAllModelsPlatforms();
}
public int countMarkerAssociationBySourcePdxId(String modelId, String dataSource, String platformName){
return modelCreationRepository.countMarkerAssociationBySourcePdxId(modelId, dataSource, platformName);
}
public Collection<ModelCreation> findModelsWithPatientData(){
return modelCreationRepository.findModelsWithPatientData();
}
public Collection<ModelCreation> findAllModels(){
return this.modelCreationRepository.findAllModels();
}
public ModelCreation findModelByIdAndDataSource(String modelId, String dataSource){
return modelCreationRepository.findBySourcePdxIdAndDataSource(modelId, dataSource);
}
public ModelCreation findModelByIdAndDataSourceWithSpecimensAndHostStrain(String modelId, String dataSource){
return modelCreationRepository.findBySourcePdxIdAndDataSourceWithSpecimensAndHostStrain(modelId, dataSource);
}
public void saveModelCreation(ModelCreation modelCreation){
this.modelCreationRepository.save(modelCreation);
}
public ModelCreation findModelByMolChar(MolecularCharacterization mc){
return modelCreationRepository.findByMolChar(mc);
}
public ModelCreation findModelWithSampleByMolChar(MolecularCharacterization mc){
return modelCreationRepository.findModelWithSampleByMolChar(mc);
}
public Patient createPatient(String patientId, Group dataSource, String sex, String race, String ethnicity){
Patient patient = findPatient(patientId, dataSource);
if(patient == null){
patient = this.getPatient(patientId, sex, race, ethnicity, dataSource);
patientRepository.save(patient);
}
return patient;
}
public Patient getPatientWithSnapshots(String patientId, Group group){
return patientRepository.findByExternalIdAndGroupWithSnapshots(patientId, group);
}
public void savePatient(Patient patient){
patientRepository.save(patient);
}
public Patient findPatient(String patientId, Group dataSource){
return patientRepository.findByExternalIdAndGroupWithSnapshots(patientId, dataSource);
}
public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, Group group) {
Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group);
PatientSnapshot patientSnapshot;
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = this.getPatient(externalId, sex, race, ethnicity, group);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
} else {
patientSnapshot = this.getPatientSnapshot(patient, age);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(Patient patient, String age) {
PatientSnapshot patientSnapshot = null;
Set<PatientSnapshot> pSnaps = patientSnapshotRepository.findByPatient(patient.getExternalId());
loop:
for (PatientSnapshot ps : pSnaps) {
if (ps.getAgeAtCollection().equals(age)) {
patientSnapshot = ps;
break loop;
}
}
if (patientSnapshot == null) {
//log.info("PatientSnapshot for patient '{}' at age '{}' not found. Creating", patient.getExternalId(), age);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(Patient patient, String ageAtCollection, String collectionDate, String collectionEvent, String ellapsedTime){
PatientSnapshot ps;
if(patient.getSnapshots() != null){
for(PatientSnapshot psnap : patient.getSnapshots()){
if(psnap.getAgeAtCollection().equals(ageAtCollection) && psnap.getDateAtCollection().equals(collectionDate) &&
psnap.getCollectionEvent().equals(collectionEvent) && psnap.getElapsedTime().equals(ellapsedTime)){
return psnap;
}
}
//ps = patient.getSnapShotByCollection(ageAtCollection, collectionDate, collectionEvent, ellapsedTime);
}
//create new snapshot and save it with the patient
ps = new PatientSnapshot(patient, ageAtCollection, collectionDate, collectionEvent, ellapsedTime);
patient.hasSnapshot(ps);
ps.setPatient(patient);
patientRepository.save(patient);
patientSnapshotRepository.save(ps);
return ps;
}
public PatientSnapshot getPatientSnapshot(String patientId, String age, String dataSource){
PatientSnapshot ps = patientSnapshotRepository.findByPatientIdAndDataSourceAndAge(patientId, dataSource, age);
return ps;
}
public PatientSnapshot findLastPatientSnapshot(String patientId, Group ds){
Patient patient = patientRepository.findByExternalIdAndGroupWithSnapshots(patientId, ds);
PatientSnapshot ps = null;
if(patient != null){
ps = patient.getLastSnapshot();
}
return ps;
}
public Patient getPatient(String externalId, String sex, String race, String ethnicity, Group group) {
Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group);
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = new Patient(externalId, sex, race, ethnicity, group);
patientRepository.save(patient);
}
return patient;
}
public Sample getSample(String sourceSampleId, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, String classification, Boolean normalTissue, String dataSource) {
TumorType type = this.getTumorType(typeStr);
Tissue origin = this.getTissue(originStr);
Tissue sampleSite = this.getTissue(sampleSiteStr);
Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource);
String updatedDiagnosis = diagnosis;
// Changes Malignant * Neoplasm to * Cancer
String pattern = "(.*)Malignant(.*)Neoplasm(.*)";
if (diagnosis.matches(pattern)) {
updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim();
log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis);
}
updatedDiagnosis = updatedDiagnosis.replaceAll(",", "");
if (sample == null) {
sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, classification, normalTissue, dataSource);
sampleRepository.save(sample);
}
return sample;
}
public Sample getSample(String sourceSampleId, String dataSource, String typeStr, String diagnosis, String originStr,
String sampleSiteStr, String extractionMethod, Boolean normalTissue, String stage, String stageClassification,
String grade, String gradeClassification){
TumorType type = this.getTumorType(typeStr);
Tissue origin = this.getTissue(originStr);
Tissue sampleSite = this.getTissue(sampleSiteStr);
Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource);
String updatedDiagnosis = diagnosis;
// Changes Malignant * Neoplasm to * Cancer
String pattern = "(.*)Malignant(.*)Neoplasm(.*)";
if (diagnosis.matches(pattern)) {
updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim();
log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis);
}
updatedDiagnosis = updatedDiagnosis.replaceAll(",", "");
if (sample == null) {
//String sourceSampleId, TumorType type, String diagnosis, Tissue originTissue, Tissue sampleSite, String extractionMethod,
// String stage, String stageClassification, String grade, String gradeClassification, Boolean normalTissue, String dataSource
sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, stage, stageClassification, grade, gradeClassification, normalTissue, dataSource);
sampleRepository.save(sample);
}
return sample;
}
public Sample findSampleByDataSourceAndSourceSampleId(String dataSource, String sampleId){
return sampleRepository.findBySourceSampleIdAndDataSource(sampleId, dataSource);
}
public Collection<Sample> findSamplesWithoutOntologyMapping(){
return sampleRepository.findSamplesWithoutOntologyMapping();
}
public Sample getMouseSample(ModelCreation model, String specimenId, String dataSource, String passage, String sampleId){
Specimen specimen = this.getSpecimen(model, specimenId, dataSource, passage);
Sample sample = null;
if(specimen.getSample() == null){
sample = new Sample();
sample.setSourceSampleId(sampleId);
sample.setDataSource(dataSource);
sampleRepository.save(sample);
}
else{
sample = specimen.getSample();
}
return sample;
}
//public findSampleWithMolcharBySpecimen
public Sample findMouseSampleWithMolcharByModelIdAndDataSourceAndSampleId(String modelId, String dataSource, String sampleId){
return sampleRepository.findMouseSampleWithMolcharByModelIdAndDataSourceAndSampleId(modelId, dataSource, sampleId);
}
public Sample findHumanSampleWithMolcharByModelIdAndDataSource(String modelId, String dataSource){
return sampleRepository.findHumanSampleWithMolcharByModelIdAndDataSource(modelId, dataSource);
}
public Sample getHumanSample(String sampleId, String dataSource){
return sampleRepository.findHumanSampleBySampleIdAndDataSource(sampleId, dataSource);
}
public Sample findHumanSample(String modelId, String dsAbbrev){
return sampleRepository.findHumanSampleByModelIdAndDS(modelId, dsAbbrev);
}
public Sample findXenograftSample(String modelId, String dataSource, String specimenId){
return sampleRepository.findMouseSampleByModelIdAndDataSourceAndSpecimenId(modelId, dataSource, specimenId);
}
public Sample findXenograftSample(String modelId, String dataSource, String passage, String nomenclature){
return sampleRepository.findMouseSampleByModelIdAndDataSourceAndPassageAndNomenclature(modelId, dataSource, passage, nomenclature);
}
public int getHumanSamplesNumber(){
return sampleRepository.findHumanSamplesNumber();
}
public Collection<Sample> findHumanSamplesFromTo(int from, int to){
return sampleRepository.findHumanSamplesFromTo(from, to);
}
public void saveSample(Sample sample){
sampleRepository.save(sample);
}
public EngraftmentSite getImplantationSite(String iSite) {
EngraftmentSite site = engraftmentSiteRepository.findByName(iSite);
if (site == null) {
log.info("Implantation Site '{}' not found. Creating.", iSite);
site = new EngraftmentSite(iSite);
engraftmentSiteRepository.save(site);
}
return site;
}
public EngraftmentType getImplantationType(String iType) {
EngraftmentType type = engraftmentTypeRepository.findByName(iType);
if (type == null) {
log.info("Implantation Type '{}' not found. Creating.", iType);
type = new EngraftmentType(iType);
engraftmentTypeRepository.save(type);
}
return type;
}
public EngraftmentMaterial getEngraftmentMaterial(String eMat){
EngraftmentMaterial em = engraftmentMaterialRepository.findByName(eMat);
if(em == null){
em = new EngraftmentMaterial();
em.setName(eMat);
engraftmentMaterialRepository.save(em);
}
return em;
}
public EngraftmentMaterial createEngraftmentMaterial(String material, String status){
EngraftmentMaterial em = new EngraftmentMaterial();
em.setName(material);
em.setState(status);
engraftmentMaterialRepository.save(em);
return em;
}
public Tissue getTissue(String t) {
Tissue tissue = tissueRepository.findByName(t);
if (tissue == null) {
log.info("Tissue '{}' not found. Creating.", t);
tissue = new Tissue(t);
tissueRepository.save(tissue);
}
return tissue;
}
public TumorType getTumorType(String name) {
TumorType tumorType = tumorTypeRepository.findByName(name);
if (tumorType == null) {
log.info("TumorType '{}' not found. Creating.", name);
tumorType = new TumorType(name);
tumorTypeRepository.save(tumorType);
}
return tumorType;
}
public HostStrain getHostStrain(String name, String symbol, String url, String description) throws Exception{
if(name == null || symbol == null || symbol.isEmpty()) throw new Exception("Symbol or name is null");
HostStrain hostStrain = hostStrainRepository.findBySymbol(symbol);
if (hostStrain == null) {
log.info("Background Strain '{}' not found. Creating", name);
hostStrain = new HostStrain(name, symbol, description, url);
hostStrainRepository.save(hostStrain);
}
else {
//if the saved hoststrain's name is empty update the name
if(!StringUtils.equals(hostStrain.getName(), name) ){
hostStrain.setName(name);
hostStrainRepository.save(hostStrain);
}
}
return hostStrain;
}
/*
// is this bad? ... probably..
public Marker getMarker(String symbol) {
log.error("MARKER METHOD WAS CALLED!");
return this.getMarker(symbol, symbol);
}
public Marker getMarker(String symbol, String name) {
log.error("MARKER METHOD WAS CALLED!");
Marker marker = markerRepository.findByName(name);
if (marker == null && symbol != null) {
marker = markerRepository.findBySymbol(symbol);
}
if (marker == null) {
//log.info("Marker '{}' not found. Creating", name);
marker = new Marker(symbol, name);
marker = markerRepository.save(marker);
}
return marker;
}
public MarkerAssociation getMarkerAssociation(String type, String markerSymbol, String markerName) {
Marker m = this.getMarker(markerSymbol, markerName);
MarkerAssociation ma = markerAssociationRepository.findByTypeAndMarkerName(type, m.getName());
if (ma == null && m.getSymbol() != null) {
ma = markerAssociationRepository.findByTypeAndMarkerSymbol(type, m.getSymbol());
}
if (ma == null) {
ma = new MarkerAssociation(type, m);
markerAssociationRepository.save(ma);
}
return ma;
}
*/
public Set<MarkerAssociation> findMarkerAssocsByMolChar(MolecularCharacterization mc){
return markerAssociationRepository.findByMolChar(mc);
}
public Set<MarkerAssociation> findMutationByMolChar(MolecularCharacterization mc){
return markerAssociationRepository.findMutationByMolChar(mc);
}
public void savePatientSnapshot(PatientSnapshot ps) {
patientSnapshotRepository.save(ps);
}
public void saveMolecularCharacterization(MolecularCharacterization mc) {
molecularCharacterizationRepository.save(mc);
}
public void saveQualityAssurance(QualityAssurance qa) {
if (qa != null) {
if (null == qualityAssuranceRepository.findFirstByTechnologyAndDescription(qa.getTechnology(), qa.getDescription())) {
qualityAssuranceRepository.save(qa);
}
}
}
public Collection<MolecularCharacterization> findMolCharsByType(String type){
return molecularCharacterizationRepository.findAllByType(type);
}
public List<Specimen> findSpecimenByPassage(ModelCreation model, String passage){
return specimenRepository.findByModelIdAndDataSourceAndAndPassage(model.getSourcePdxId(), model.getDataSource(), passage);
}
public Specimen getSpecimen(ModelCreation model, String specimenId, String dataSource, String passage){
Specimen specimen = specimenRepository.findByModelIdAndDataSourceAndSpecimenIdAndPassage(model.getSourcePdxId(), dataSource, specimenId, passage);
if(specimen == null){
specimen = new Specimen();
specimen.setExternalId(specimenId);
specimen.setPassage(passage);
specimenRepository.save(specimen);
}
return specimen;
}
public Specimen findSpecimenByModelAndPassageAndNomenclature(ModelCreation modelCreation, String passage, String nomenclature){
return specimenRepository.findByModelAndPassageAndNomenClature(modelCreation, passage, nomenclature);
}
public List<Specimen> getAllSpecimenByModel(String modelId, String dataSource){
return specimenRepository.findByModelIdAndDataSource(modelId, dataSource);
}
public Specimen findSpecimenByMolChar(MolecularCharacterization mc){
return specimenRepository.findByMolChar(mc);
}
public void saveSpecimen(Specimen specimen){
specimenRepository.save(specimen);
}
public OntologyTerm getOntologyTerm(String url, String label){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
if(ot == null){
ot = new OntologyTerm(url, label);
ontologyTermRepository.save(ot);
}
return ot;
}
public OntologyTerm getOntologyTerm(String url){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
return ot;
}
public OntologyTerm findOntologyTermByLabel(String label){
OntologyTerm ot = ontologyTermRepository.findByLabel(label);
return ot;
}
public OntologyTerm findOntologyTermByUrl(String url){
return ontologyTermRepository.findByUrl(url);
}
public Collection<OntologyTerm> getAllOntologyTerms() {
return ontologyTermRepository.findAll();
}
public Collection<OntologyTerm> getAllOntologyTermsWithNotZeroDirectMapping(){
return ontologyTermRepository.findAllWithNotZeroDirectMappingNumber();
}
public Collection<OntologyTerm> getAllDirectParents(String termUrl){
return ontologyTermRepository.findAllDirectParents(termUrl);
}
public int getIndirectMappingNumber(String label) {
return ontologyTermRepository.getIndirectMappingNumber(label);
}
public int findDirectMappingNumber(String label) {
Set<OntologyTerm> otset = ontologyTermRepository.getDistinctSubTreeNodes(label);
int mapNum = 0;
for (OntologyTerm ot : otset) {
mapNum += ot.getDirectMappedSamplesNumber();
}
return mapNum;
}
public Collection<OntologyTerm> getAllOntologyTermsFromTo(int from, int to) {
return ontologyTermRepository.findAllFromTo(from, to);
}
public void saveOntologyTerm(OntologyTerm ot){
ontologyTermRepository.save(ot);
}
public void deleteOntologyTermsWithoutMapping(){
ontologyTermRepository.deleteTermsWithZeroMappings();
}
public void saveMarker(Marker marker) {
markerRepository.save(marker);
}
public Collection<Marker> getAllMarkers() {
return markerRepository.findAllMarkers();
}
public Collection<Marker> getAllHumanMarkers() {
return markerRepository.findAllHumanMarkers();
}
public Platform getPlatform(String name, Group group) {
//remove special characters from platform name
name = name.replaceAll("[^A-Za-z0-9 _-]", "");
Platform p = platformRepository.findByNameAndDataSource(name, group.getName());
if (p == null) {
p = new Platform();
p.setName(name);
p.setGroup(group);
platformRepository.save(p);
}
return p;
}
public Platform getPlatform(String name, Group group, String platformUrl) {
//remove special characters from platform name
name = name.replaceAll("[^A-Za-z0-9 _-]", "");
Platform p = platformRepository.findByNameAndDataSourceAndUrl(name, group.getName(), platformUrl);
if (p == null) {
p = new Platform();
p.setName(name);
p.setGroup(group);
p.setUrl(platformUrl);
}
return p;
}
public void savePlatform(Platform p){
platformRepository.save(p);
}
public PlatformAssociation createPlatformAssociation(Platform p, Marker m) {
if (platformAssociationRepository == null) {
System.out.println("PAR is null");
}
if (p == null) {
System.out.println("Platform is null");
}
if (p.getGroup() == null) {
System.out.println("P.EDS is null");
}
if (m == null) {
System.out.println("Marker is null");
}
PlatformAssociation pa = platformAssociationRepository.findByPlatformAndMarker(p.getName(), p.getGroup().getName(), m.getSymbol());
if (pa == null) {
pa = new PlatformAssociation();
pa.setPlatform(p);
pa.setMarker(m);
//platformAssociationRepository.save(pa);
}
return pa;
}
public void savePlatformAssociation(PlatformAssociation pa){
platformAssociationRepository.save(pa);
}
public void saveDataProjection(DataProjection dp){
dataProjectionRepository.save(dp);
}
public DataProjection findDataProjectionByLabel(String label){
return dataProjectionRepository.findByLabel(label);
}
public boolean isTreatmentSummaryAvailableOnModel(String dataSource, String modelId){
TreatmentSummary ts = treatmentSummaryRepository.findModelTreatmentByDataSourceAndModelId(dataSource, modelId);
if(ts != null && ts.getTreatmentProtocols() != null){
return true;
}
return false;
}
public boolean isTreatmentSummaryAvailableOnPatient(String dataSource, String modelId){
TreatmentSummary ts = treatmentSummaryRepository.findPatientTreatmentByDataSourceAndModelId(dataSource, modelId);
if(ts != null && ts.getTreatmentProtocols() != null){
return true;
}
return false;
}
public ModelCreation findModelByTreatmentSummary(TreatmentSummary ts){
return modelCreationRepository.findByTreatmentSummary(ts);
}
public Drug getStandardizedDrug(String drugString){
Drug d = new Drug();
d.setName(Standardizer.getDrugName(drugString));
return d;
}
public CurrentTreatment getCurrentTreatment(String name){
CurrentTreatment ct = currentTreatmentRepository.findByName(name);
if(ct == null){
ct = new CurrentTreatment(name);
currentTreatmentRepository.save(ct);
}
return ct;
}
/**
*
* @param drugString
* @param doseString
* @param response
* @return
*
* Creates a (tp:TreatmentProtocol)--(tc:TreatmentComponent)--(d:Drug)
* (tp)--(r:Response) node
*
* If drug names are separated with + it will create multiple components to represent drug combos
* Doses should be separated with either + or ;
*/
public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response, String responseClassification){
TreatmentProtocol tp = new TreatmentProtocol();
//combination of drugs?
if(drugString.contains("+") && doseString.contains(";")){
String[] drugArray = drugString.split("\\+");
String[] doseArray = doseString.split(";");
if(drugArray.length == doseArray.length){
for(int i=0;i<drugArray.length;i++){
Drug d = getStandardizedDrug(drugArray[i].trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugArray[i]));
tc.setDose(doseArray[i].trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
}
else{
//TODO: deal with the case when there are more drugs than doses or vice versa
}
}
else if(drugString.contains("+") && !doseString.contains(";")){
if(doseString.contains("+")){
//this data is coming from the universal loader, dose combinations are separated with + instead of ;
String[] drugArray = drugString.split("\\+");
String[] doseArray = doseString.split("\\+");
if(drugArray.length == doseArray.length){
for(int i=0;i<drugArray.length;i++){
Drug d = getStandardizedDrug(drugArray[i].trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugArray[i]));
tc.setDose(doseArray[i].trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
}
}
else{
String[] drugArray = drugString.split("\\+");
for(int i=0;i<drugArray.length;i++){
Drug d = getStandardizedDrug(drugArray[i].trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugArray[i]));
tc.setDose(doseString.trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
}
}
//one drug only
else{
Drug d = getStandardizedDrug(drugString.trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugString));
tc.setDrug(d);
tc.setDose(doseString.trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
Response r = new Response();
r.setDescription(Standardizer.getDrugResponse(response));
r.setDescriptionClassification(responseClassification);
tp.setResponse(r);
if(tp.getComponents() == null || tp.getComponents().size() == 0) return null;
return tp;
}
public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response, boolean currentTreatment){
TreatmentProtocol tp = getTreatmentProtocol(drugString, doseString, response, "");
if(currentTreatment && tp.getCurrentTreatment() == null){
CurrentTreatment ct = getCurrentTreatment("Current Treatment");
tp.setCurrentTreatment(ct);
}
return tp;
}
public TreatmentSummary findTreatmentSummaryByPatientSnapshot(PatientSnapshot ps){
return treatmentSummaryRepository.findByPatientSnapshot(ps);
}
public Set<Object> findUnlinkedNodes(){
return dataProjectionRepository.findUnlinkedNodes();
}
public Set<Object> findPatientsWithMultipleSummaries(){
return dataProjectionRepository.findPatientsWithMultipleTreatmentSummaries();
}
public Set<Object> findPlatformsWithoutUrl(){
return dataProjectionRepository.findPlatformsWithoutUrl();
}
public QualityAssurance getQualityAssurance(JSONObject data, String ds) throws Exception{
QualityAssurance qa = new QualityAssurance();
String qaType = Standardizer.NOT_SPECIFIED;
if (ds.equals("JAX")){
String qaPassages = Standardizer.NOT_SPECIFIED;
// Pending or Complete
String qc = data.getString("QC");
if("Pending".equals(qc)){
qc = Standardizer.NOT_SPECIFIED;
}else{
qc = "QC is "+qc;
}
// the validation techniques are more than just fingerprint, we don't have a way to capture that
qa = new QualityAssurance("Fingerprint", qc, qaPassages);
saveQualityAssurance(qa);
}
if (ds.equals("PDXNet-HCI-BCM")){
// This multiple QA approach only works because Note and Passage are the same for all QAs
qa = new QualityAssurance(Standardizer.NOT_SPECIFIED,Standardizer.NOT_SPECIFIED,Standardizer.NOT_SPECIFIED);
StringBuilder technology = new StringBuilder();
if(data.has("QA")){
JSONArray qas = data.getJSONArray("QA");
for (int i = 0; i < qas.length(); i++) {
if (qas.getJSONObject(i).getString("Technology").equalsIgnoreCase("histology")) {
qa.setTechnology(qas.getJSONObject(i).getString("Technology"));
qa.setDescription(qas.getJSONObject(i).getString("Note"));
qa.setPassages(qas.getJSONObject(i).getString("Passage"));
}
}
}
}
if (ds.equals("PDXNet-MDAnderson") || ds.equals("PDXNet-WUSTL")) {
try {
qaType = data.getString("QA") + " on passage " + data.getString("QA Passage");
} catch (Exception e) {
// not all groups supplied QA
}
String qaPassage = data.has("QA Passage") ? data.getString("QA Passage") : null;
qa = new QualityAssurance(qaType, Standardizer.NOT_SPECIFIED, qaPassage);
saveQualityAssurance(qa);
}
if (ds.equals("IRCC-CRC")) {
String FINGERPRINT_DESCRIPTION = "Model validated against patient germline.";
if ("TRUE".equals(data.getString("Fingerprinting").toUpperCase())) {
qa.setTechnology("Fingerprint");
qa.setDescription(FINGERPRINT_DESCRIPTION);
// If the model includes which passages have had QA performed, set the passages on the QA node
if (data.has("QA Passage") && !data.getString("QA Passage").isEmpty()) {
List<String> passages = Stream.of(data.getString("QA Passage").split(","))
.map(String::trim)
.distinct()
.collect(Collectors.toList());
List<Integer> passageInts = new ArrayList<>();
// NOTE: IRCC uses passage 0 to mean Patient Tumor, so we need to harmonize according to the other
// sources. Subtract 1 from every passage.
for (String p : passages) {
Integer intPassage = Integer.parseInt(p);
passageInts.add(intPassage - 1);
}
qa.setPassages(StringUtils.join(passageInts, ", "));
}
}
}
return qa;
}
@Cacheable
public Marker getMarkerBySymbol(String symbol){
return markerRepository.findBySymbol(symbol);
}
@Cacheable
public List<Marker> getMarkerByPrevSymbol(String symbol){
return markerRepository.findByPrevSymbol(symbol);
}
@Cacheable
public List<Marker> getMarkerBySynonym(String symbol){
return markerRepository.findBySynonym(symbol);
}
public NodeSuggestionDTO getSuggestedMarker(String reporter, String dataSource, String modelId, String symbol){
NodeSuggestionDTO nsdto = new NodeSuggestionDTO();
LogEntity le;
Marker m;
List<Marker> markerSuggestionList = null;
boolean ready = false;
//check if marker is cached
if(markersBySymbol.containsKey(symbol)){
m = markersBySymbol.get(symbol);
nsdto.setNode(m);
ready = true;
}
else if(markersByPrevSymbol.containsKey(symbol)){
m = markersByPrevSymbol.get(symbol);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Previous symbol");
nsdto.setLogEntity(le);
ready = true;
}
else if(markersBySynonym.containsKey(symbol)){
m = markersBySynonym.get(symbol);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Synonym");
nsdto.setLogEntity(le);
ready = true;
}
if(ready) return nsdto;
m = getMarkerBySymbol(symbol);
if(m != null){
//good, pass the marker
//no message
nsdto.setNode(m);
markersBySymbol.put(symbol, m);
}
else{
markerSuggestionList = getMarkerByPrevSymbol(symbol);
if(markerSuggestionList != null && markerSuggestionList.size() > 0){
if(markerSuggestionList.size() == 1){
//symbol found in prev symbols
m = markerSuggestionList.get(0);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Previous symbol");
nsdto.setNode(m);
nsdto.setLogEntity(le);
markersByPrevSymbol.put(symbol, m);
}
else{
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, "","");
le.setMessage("Previous symbol for multiple terms");
le.setType("ERROR");
nsdto.setNode(null);
nsdto.setLogEntity(le);
}
}
else{
markerSuggestionList = getMarkerBySynonym(symbol);
if(markerSuggestionList != null && markerSuggestionList.size() > 0){
if(markerSuggestionList.size() == 1){
//symbol found in synonym
m = markerSuggestionList.get(0);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Synonym");
nsdto.setNode(m);
nsdto.setLogEntity(le);
markersBySynonym.put(symbol, m);
}
else{
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, "","");
le.setMessage("Synonym for multiple terms");
le.setType("ERROR");
nsdto.setNode(null);
nsdto.setLogEntity(le);
}
}
else{
//error, didn't find the symbol anywhere
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, "","");
le.setMessage(symbol +" is an unrecognised symbol, skipping");
le.setType("ERROR");
nsdto.setLogEntity(le);
}
}
}
return nsdto;
}
}
| data-services/src/main/java/org/pdxfinder/services/DataImportService.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.pdxfinder.services;
//import org.apache.commons.cli.Option;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.ogm.json.JSONArray;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.graph.dao.*;
import org.pdxfinder.graph.repositories.*;
import org.pdxfinder.services.ds.Harmonizer;
import org.pdxfinder.services.ds.Standardizer;
import org.pdxfinder.services.dto.LoaderDTO;
import org.pdxfinder.services.dto.NodeSuggestionDTO;
import org.pdxfinder.services.reporting.LogEntity;
import org.pdxfinder.services.reporting.LogEntityType;
import org.pdxfinder.services.reporting.MarkerLogEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.cache.annotation.Cacheable;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The hope was to put a lot of reused repository actions into one place ie find
* or create a node or create a node with that requires a number of 'child'
* nodes that are terms
*
* @author sbn
*/
@Component
public class DataImportService {
//public static Option loadAll = new Option("LoadAll", false, "Load all PDX Finder data");
private TumorTypeRepository tumorTypeRepository;
private HostStrainRepository hostStrainRepository;
private EngraftmentTypeRepository engraftmentTypeRepository;
private EngraftmentSiteRepository engraftmentSiteRepository;
private EngraftmentMaterialRepository engraftmentMaterialRepository;
private GroupRepository groupRepository;
private PatientRepository patientRepository;
private ModelCreationRepository modelCreationRepository;
private TissueRepository tissueRepository;
private PatientSnapshotRepository patientSnapshotRepository;
private SampleRepository sampleRepository;
private MarkerRepository markerRepository;
private MarkerAssociationRepository markerAssociationRepository;
private MolecularCharacterizationRepository molecularCharacterizationRepository;
private QualityAssuranceRepository qualityAssuranceRepository;
private OntologyTermRepository ontologyTermRepository;
private SpecimenRepository specimenRepository;
private PlatformRepository platformRepository;
private PlatformAssociationRepository platformAssociationRepository;
private DataProjectionRepository dataProjectionRepository;
private TreatmentSummaryRepository treatmentSummaryRepository;
private TreatmentProtocolRepository treatmentProtocolRepository;
private CurrentTreatmentRepository currentTreatmentRepository;
private ExternalUrlRepository externalUrlRepository;
private final static Logger log = LoggerFactory.getLogger(DataImportService.class);
private HashMap<String, Marker> markersBySymbol;
private HashMap<String, Marker> markersByPrevSymbol;
private HashMap<String, Marker> markersBySynonym;
public DataImportService(TumorTypeRepository tumorTypeRepository,
HostStrainRepository hostStrainRepository,
EngraftmentTypeRepository engraftmentTypeRepository,
EngraftmentSiteRepository engraftmentSiteRepository,
EngraftmentMaterialRepository engraftmentMaterialRepository,
GroupRepository groupRepository,
PatientRepository patientRepository,
ModelCreationRepository modelCreationRepository,
TissueRepository tissueRepository,
PatientSnapshotRepository patientSnapshotRepository,
SampleRepository sampleRepository,
MarkerRepository markerRepository,
MarkerAssociationRepository markerAssociationRepository,
MolecularCharacterizationRepository molecularCharacterizationRepository,
QualityAssuranceRepository qualityAssuranceRepository,
OntologyTermRepository ontologyTermRepository,
SpecimenRepository specimenRepository,
PlatformRepository platformRepository,
PlatformAssociationRepository platformAssociationRepository,
DataProjectionRepository dataProjectionRepository,
TreatmentSummaryRepository treatmentSummaryRepository,
TreatmentProtocolRepository treatmentProtocolRepository,
CurrentTreatmentRepository currentTreatmentRepository,
ExternalUrlRepository externalUrlRepository) {
Assert.notNull(tumorTypeRepository, "tumorTypeRepository cannot be null");
Assert.notNull(hostStrainRepository, "hostStrainRepository cannot be null");
Assert.notNull(engraftmentTypeRepository, "implantationTypeRepository cannot be null");
Assert.notNull(engraftmentSiteRepository, "implantationSiteRepository cannot be null");
Assert.notNull(engraftmentMaterialRepository, "engraftmentMaterialRepository cannot be null");
Assert.notNull(groupRepository, "GroupRepository cannot be null");
Assert.notNull(patientRepository, "patientRepository cannot be null");
Assert.notNull(modelCreationRepository, "modelCreationRepository cannot be null");
Assert.notNull(tissueRepository, "tissueRepository cannot be null");
Assert.notNull(patientSnapshotRepository, "patientSnapshotRepository cannot be null");
Assert.notNull(sampleRepository, "sampleRepository cannot be null");
Assert.notNull(markerRepository, "markerRepository cannot be null");
Assert.notNull(markerAssociationRepository, "markerAssociationRepository cannot be null");
Assert.notNull(molecularCharacterizationRepository, "molecularCharacterizationRepository cannot be null");
Assert.notNull(externalUrlRepository, "externalUrlRepository cannot be null");
this.tumorTypeRepository = tumorTypeRepository;
this.hostStrainRepository = hostStrainRepository;
this.engraftmentTypeRepository = engraftmentTypeRepository;
this.engraftmentSiteRepository = engraftmentSiteRepository;
this.engraftmentMaterialRepository = engraftmentMaterialRepository;
this.groupRepository = groupRepository;
this.patientRepository = patientRepository;
this.modelCreationRepository = modelCreationRepository;
this.tissueRepository = tissueRepository;
this.patientSnapshotRepository = patientSnapshotRepository;
this.sampleRepository = sampleRepository;
this.markerRepository = markerRepository;
this.markerAssociationRepository = markerAssociationRepository;
this.molecularCharacterizationRepository = molecularCharacterizationRepository;
this.qualityAssuranceRepository = qualityAssuranceRepository;
this.ontologyTermRepository = ontologyTermRepository;
this.specimenRepository = specimenRepository;
this.platformRepository = platformRepository;
this.platformAssociationRepository = platformAssociationRepository;
this.dataProjectionRepository = dataProjectionRepository;
this.treatmentSummaryRepository = treatmentSummaryRepository;
this.treatmentProtocolRepository = treatmentProtocolRepository;
this.currentTreatmentRepository = currentTreatmentRepository;
this.externalUrlRepository = externalUrlRepository;
this.markersBySymbol = new HashMap<>();
this.markersByPrevSymbol = new HashMap<>();
this.markersBySynonym = new HashMap<>();
}
public Group getGroup(String name, String abbrev, String type){
Group g = groupRepository.findByNameAndType(name, type);
if(g == null){
log.info("Group not found. Creating", name);
g = new Group(name, abbrev, type);
groupRepository.save(g);
}
return g;
}
public Group getProviderGroup(String name, String abbrev, String description, String providerType, String accessibility,
String accessModalities, String contact, String url){
Group g = groupRepository.findByNameAndType(name, "Provider");
if(g == null){
log.info("Provider group not found. Creating", name);
g = new Group(name, abbrev, description, providerType, accessibility, accessModalities, contact, url);
groupRepository.save(g);
}
return g;
}
public Group getPublicationGroup(String publicationId){
Group g = groupRepository.findByPubmedIdAndType(publicationId, "Publication");
if(g == null){
log.info("Publication group not found. Creating", publicationId);
g = new Group();
g.setType("Publication");
g.setPubMedId(publicationId);
groupRepository.save(g);
}
return g;
}
public Group getProjectGroup(String groupName){
Group g = groupRepository.findByNameAndType(groupName, "Project");
if(g == null){
log.info("Project group not found. Creating", groupName);
g = new Group();
g.setType("Project");
g.setName(groupName);
groupRepository.save(g);
}
return g;
}
public List<Group> getAllProviderGroups(){
return groupRepository.findAllByType("Provider");
}
public void saveGroup(Group g){
groupRepository.save(g);
}
public ExternalUrl getExternalUrl(ExternalUrl.Type type, String url) {
ExternalUrl externalUrl = externalUrlRepository.findByTypeAndUrl(type.getValue(), url);
if (externalUrl == null) {
log.info("External URL '{}' not found. Creating", type);
externalUrl = new ExternalUrl(
type,
url);
externalUrlRepository.save(externalUrl);
}
return externalUrl;
}
public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, QualityAssurance qa, List<ExternalUrl> externalUrls) {
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls);
modelCreation.addRelatedSample(sample);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, List<QualityAssurance> qa, List<ExternalUrl> externalUrls) {
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls);
modelCreation.addRelatedSample(sample);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public boolean isExistingModel(String dataSource, String modelId){
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(modelId, dataSource);
if(modelCreation == null) return false;
return true;
}
public Collection<ModelCreation> findAllModelsPlatforms(){
return modelCreationRepository.findAllModelsPlatforms();
}
public int countMarkerAssociationBySourcePdxId(String modelId, String dataSource, String platformName){
return modelCreationRepository.countMarkerAssociationBySourcePdxId(modelId, dataSource, platformName);
}
public Collection<ModelCreation> findModelsWithPatientData(){
return modelCreationRepository.findModelsWithPatientData();
}
public Collection<ModelCreation> findAllModels(){
return this.modelCreationRepository.findAllModels();
}
public ModelCreation findModelByIdAndDataSource(String modelId, String dataSource){
return modelCreationRepository.findBySourcePdxIdAndDataSource(modelId, dataSource);
}
public ModelCreation findModelByIdAndDataSourceWithSpecimensAndHostStrain(String modelId, String dataSource){
return modelCreationRepository.findBySourcePdxIdAndDataSourceWithSpecimensAndHostStrain(modelId, dataSource);
}
public void saveModelCreation(ModelCreation modelCreation){
this.modelCreationRepository.save(modelCreation);
}
public ModelCreation findModelByMolChar(MolecularCharacterization mc){
return modelCreationRepository.findByMolChar(mc);
}
public ModelCreation findModelWithSampleByMolChar(MolecularCharacterization mc){
return modelCreationRepository.findModelWithSampleByMolChar(mc);
}
public Patient createPatient(String patientId, Group dataSource, String sex, String race, String ethnicity){
Patient patient = findPatient(patientId, dataSource);
if(patient == null){
patient = this.getPatient(patientId, sex, race, ethnicity, dataSource);
patientRepository.save(patient);
}
return patient;
}
public Patient getPatientWithSnapshots(String patientId, Group group){
return patientRepository.findByExternalIdAndGroupWithSnapshots(patientId, group);
}
public void savePatient(Patient patient){
patientRepository.save(patient);
}
public Patient findPatient(String patientId, Group dataSource){
return patientRepository.findByExternalIdAndGroupWithSnapshots(patientId, dataSource);
}
public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, Group group) {
Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group);
PatientSnapshot patientSnapshot;
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = this.getPatient(externalId, sex, race, ethnicity, group);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
} else {
patientSnapshot = this.getPatientSnapshot(patient, age);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(Patient patient, String age) {
PatientSnapshot patientSnapshot = null;
Set<PatientSnapshot> pSnaps = patientSnapshotRepository.findByPatient(patient.getExternalId());
loop:
for (PatientSnapshot ps : pSnaps) {
if (ps.getAgeAtCollection().equals(age)) {
patientSnapshot = ps;
break loop;
}
}
if (patientSnapshot == null) {
//log.info("PatientSnapshot for patient '{}' at age '{}' not found. Creating", patient.getExternalId(), age);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(Patient patient, String ageAtCollection, String collectionDate, String collectionEvent, String ellapsedTime){
PatientSnapshot ps;
if(patient.getSnapshots() != null){
for(PatientSnapshot psnap : patient.getSnapshots()){
if(psnap.getAgeAtCollection().equals(ageAtCollection) && psnap.getDateAtCollection().equals(collectionDate) &&
psnap.getCollectionEvent().equals(collectionEvent) && psnap.getElapsedTime().equals(ellapsedTime)){
return psnap;
}
}
//ps = patient.getSnapShotByCollection(ageAtCollection, collectionDate, collectionEvent, ellapsedTime);
}
//create new snapshot and save it with the patient
ps = new PatientSnapshot(patient, ageAtCollection, collectionDate, collectionEvent, ellapsedTime);
patient.hasSnapshot(ps);
ps.setPatient(patient);
patientRepository.save(patient);
patientSnapshotRepository.save(ps);
return ps;
}
public PatientSnapshot getPatientSnapshot(String patientId, String age, String dataSource){
PatientSnapshot ps = patientSnapshotRepository.findByPatientIdAndDataSourceAndAge(patientId, dataSource, age);
return ps;
}
public PatientSnapshot findLastPatientSnapshot(String patientId, Group ds){
Patient patient = patientRepository.findByExternalIdAndGroupWithSnapshots(patientId, ds);
PatientSnapshot ps = null;
if(patient != null){
ps = patient.getLastSnapshot();
}
return ps;
}
public Patient getPatient(String externalId, String sex, String race, String ethnicity, Group group) {
Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group);
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = new Patient(externalId, sex, race, ethnicity, group);
patientRepository.save(patient);
}
return patient;
}
public Sample getSample(String sourceSampleId, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, String classification, Boolean normalTissue, String dataSource) {
TumorType type = this.getTumorType(typeStr);
Tissue origin = this.getTissue(originStr);
Tissue sampleSite = this.getTissue(sampleSiteStr);
Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource);
String updatedDiagnosis = diagnosis;
// Changes Malignant * Neoplasm to * Cancer
String pattern = "(.*)Malignant(.*)Neoplasm(.*)";
if (diagnosis.matches(pattern)) {
updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim();
log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis);
}
updatedDiagnosis = updatedDiagnosis.replaceAll(",", "");
if (sample == null) {
sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, classification, normalTissue, dataSource);
sampleRepository.save(sample);
}
return sample;
}
public Sample getSample(String sourceSampleId, String dataSource, String typeStr, String diagnosis, String originStr,
String sampleSiteStr, String extractionMethod, Boolean normalTissue, String stage, String stageClassification,
String grade, String gradeClassification){
TumorType type = this.getTumorType(typeStr);
Tissue origin = this.getTissue(originStr);
Tissue sampleSite = this.getTissue(sampleSiteStr);
Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource);
String updatedDiagnosis = diagnosis;
// Changes Malignant * Neoplasm to * Cancer
String pattern = "(.*)Malignant(.*)Neoplasm(.*)";
if (diagnosis.matches(pattern)) {
updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim();
log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis);
}
updatedDiagnosis = updatedDiagnosis.replaceAll(",", "");
if (sample == null) {
//String sourceSampleId, TumorType type, String diagnosis, Tissue originTissue, Tissue sampleSite, String extractionMethod,
// String stage, String stageClassification, String grade, String gradeClassification, Boolean normalTissue, String dataSource
sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, stage, stageClassification, grade, gradeClassification, normalTissue, dataSource);
sampleRepository.save(sample);
}
return sample;
}
public Sample findSampleByDataSourceAndSourceSampleId(String dataSource, String sampleId){
return sampleRepository.findBySourceSampleIdAndDataSource(sampleId, dataSource);
}
public Collection<Sample> findSamplesWithoutOntologyMapping(){
return sampleRepository.findSamplesWithoutOntologyMapping();
}
public Sample getMouseSample(ModelCreation model, String specimenId, String dataSource, String passage, String sampleId){
Specimen specimen = this.getSpecimen(model, specimenId, dataSource, passage);
Sample sample = null;
if(specimen.getSample() == null){
sample = new Sample();
sample.setSourceSampleId(sampleId);
sample.setDataSource(dataSource);
sampleRepository.save(sample);
}
else{
sample = specimen.getSample();
}
return sample;
}
//public findSampleWithMolcharBySpecimen
public Sample findMouseSampleWithMolcharByModelIdAndDataSourceAndSampleId(String modelId, String dataSource, String sampleId){
return sampleRepository.findMouseSampleWithMolcharByModelIdAndDataSourceAndSampleId(modelId, dataSource, sampleId);
}
public Sample findHumanSampleWithMolcharByModelIdAndDataSource(String modelId, String dataSource){
return sampleRepository.findHumanSampleWithMolcharByModelIdAndDataSource(modelId, dataSource);
}
public Sample getHumanSample(String sampleId, String dataSource){
return sampleRepository.findHumanSampleBySampleIdAndDataSource(sampleId, dataSource);
}
public Sample findHumanSample(String modelId, String dsAbbrev){
return sampleRepository.findHumanSampleByModelIdAndDS(modelId, dsAbbrev);
}
public Sample findXenograftSample(String modelId, String dataSource, String specimenId){
return sampleRepository.findMouseSampleByModelIdAndDataSourceAndSpecimenId(modelId, dataSource, specimenId);
}
public Sample findXenograftSample(String modelId, String dataSource, String passage, String nomenclature){
return sampleRepository.findMouseSampleByModelIdAndDataSourceAndPassageAndNomenclature(modelId, dataSource, passage, nomenclature);
}
public int getHumanSamplesNumber(){
return sampleRepository.findHumanSamplesNumber();
}
public Collection<Sample> findHumanSamplesFromTo(int from, int to){
return sampleRepository.findHumanSamplesFromTo(from, to);
}
public void saveSample(Sample sample){
sampleRepository.save(sample);
}
public EngraftmentSite getImplantationSite(String iSite) {
EngraftmentSite site = engraftmentSiteRepository.findByName(iSite);
if (site == null) {
log.info("Implantation Site '{}' not found. Creating.", iSite);
site = new EngraftmentSite(iSite);
engraftmentSiteRepository.save(site);
}
return site;
}
public EngraftmentType getImplantationType(String iType) {
EngraftmentType type = engraftmentTypeRepository.findByName(iType);
if (type == null) {
log.info("Implantation Type '{}' not found. Creating.", iType);
type = new EngraftmentType(iType);
engraftmentTypeRepository.save(type);
}
return type;
}
public EngraftmentMaterial getEngraftmentMaterial(String eMat){
EngraftmentMaterial em = engraftmentMaterialRepository.findByName(eMat);
if(em == null){
em = new EngraftmentMaterial();
em.setName(eMat);
engraftmentMaterialRepository.save(em);
}
return em;
}
public EngraftmentMaterial createEngraftmentMaterial(String material, String status){
EngraftmentMaterial em = new EngraftmentMaterial();
em.setName(material);
em.setState(status);
engraftmentMaterialRepository.save(em);
return em;
}
public Tissue getTissue(String t) {
Tissue tissue = tissueRepository.findByName(t);
if (tissue == null) {
log.info("Tissue '{}' not found. Creating.", t);
tissue = new Tissue(t);
tissueRepository.save(tissue);
}
return tissue;
}
public TumorType getTumorType(String name) {
TumorType tumorType = tumorTypeRepository.findByName(name);
if (tumorType == null) {
log.info("TumorType '{}' not found. Creating.", name);
tumorType = new TumorType(name);
tumorTypeRepository.save(tumorType);
}
return tumorType;
}
public HostStrain getHostStrain(String name, String symbol, String url, String description) throws Exception{
if(name == null || symbol == null || symbol.isEmpty()) throw new Exception("Symbol or name is null");
HostStrain hostStrain = hostStrainRepository.findBySymbol(symbol);
if (hostStrain == null) {
log.info("Background Strain '{}' not found. Creating", name);
hostStrain = new HostStrain(name, symbol, description, url);
hostStrainRepository.save(hostStrain);
}
else {
//if the saved hoststrain's name is empty update the name
if(!StringUtils.equals(hostStrain.getName(), name) ){
hostStrain.setName(name);
hostStrainRepository.save(hostStrain);
}
}
return hostStrain;
}
// is this bad? ... probably..
public Marker getMarker(String symbol) {
return this.getMarker(symbol, symbol);
}
public Marker getMarker(String symbol, String name) {
Marker marker = markerRepository.findByName(name);
if (marker == null && symbol != null) {
marker = markerRepository.findBySymbol(symbol);
}
if (marker == null) {
//log.info("Marker '{}' not found. Creating", name);
marker = new Marker(symbol, name);
marker = markerRepository.save(marker);
}
return marker;
}
public MarkerAssociation getMarkerAssociation(String type, String markerSymbol, String markerName) {
Marker m = this.getMarker(markerSymbol, markerName);
MarkerAssociation ma = markerAssociationRepository.findByTypeAndMarkerName(type, m.getName());
if (ma == null && m.getSymbol() != null) {
ma = markerAssociationRepository.findByTypeAndMarkerSymbol(type, m.getSymbol());
}
if (ma == null) {
ma = new MarkerAssociation(type, m);
markerAssociationRepository.save(ma);
}
return ma;
}
public Set<MarkerAssociation> findMarkerAssocsByMolChar(MolecularCharacterization mc){
return markerAssociationRepository.findByMolChar(mc);
}
public Set<MarkerAssociation> findMutationByMolChar(MolecularCharacterization mc){
return markerAssociationRepository.findMutationByMolChar(mc);
}
public void savePatientSnapshot(PatientSnapshot ps) {
patientSnapshotRepository.save(ps);
}
public void saveMolecularCharacterization(MolecularCharacterization mc) {
molecularCharacterizationRepository.save(mc);
}
public void saveQualityAssurance(QualityAssurance qa) {
if (qa != null) {
if (null == qualityAssuranceRepository.findFirstByTechnologyAndDescription(qa.getTechnology(), qa.getDescription())) {
qualityAssuranceRepository.save(qa);
}
}
}
public Collection<MolecularCharacterization> findMolCharsByType(String type){
return molecularCharacterizationRepository.findAllByType(type);
}
public List<Specimen> findSpecimenByPassage(ModelCreation model, String passage){
return specimenRepository.findByModelIdAndDataSourceAndAndPassage(model.getSourcePdxId(), model.getDataSource(), passage);
}
public Specimen getSpecimen(ModelCreation model, String specimenId, String dataSource, String passage){
Specimen specimen = specimenRepository.findByModelIdAndDataSourceAndSpecimenIdAndPassage(model.getSourcePdxId(), dataSource, specimenId, passage);
if(specimen == null){
specimen = new Specimen();
specimen.setExternalId(specimenId);
specimen.setPassage(passage);
specimenRepository.save(specimen);
}
return specimen;
}
public Specimen findSpecimenByModelAndPassageAndNomenclature(ModelCreation modelCreation, String passage, String nomenclature){
return specimenRepository.findByModelAndPassageAndNomenClature(modelCreation, passage, nomenclature);
}
public List<Specimen> getAllSpecimenByModel(String modelId, String dataSource){
return specimenRepository.findByModelIdAndDataSource(modelId, dataSource);
}
public Specimen findSpecimenByMolChar(MolecularCharacterization mc){
return specimenRepository.findByMolChar(mc);
}
public void saveSpecimen(Specimen specimen){
specimenRepository.save(specimen);
}
public OntologyTerm getOntologyTerm(String url, String label){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
if(ot == null){
ot = new OntologyTerm(url, label);
ontologyTermRepository.save(ot);
}
return ot;
}
public OntologyTerm getOntologyTerm(String url){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
return ot;
}
public OntologyTerm findOntologyTermByLabel(String label){
OntologyTerm ot = ontologyTermRepository.findByLabel(label);
return ot;
}
public OntologyTerm findOntologyTermByUrl(String url){
return ontologyTermRepository.findByUrl(url);
}
public Collection<OntologyTerm> getAllOntologyTerms() {
return ontologyTermRepository.findAll();
}
public Collection<OntologyTerm> getAllOntologyTermsWithNotZeroDirectMapping(){
return ontologyTermRepository.findAllWithNotZeroDirectMappingNumber();
}
public Collection<OntologyTerm> getAllDirectParents(String termUrl){
return ontologyTermRepository.findAllDirectParents(termUrl);
}
public int getIndirectMappingNumber(String label) {
return ontologyTermRepository.getIndirectMappingNumber(label);
}
public int findDirectMappingNumber(String label) {
Set<OntologyTerm> otset = ontologyTermRepository.getDistinctSubTreeNodes(label);
int mapNum = 0;
for (OntologyTerm ot : otset) {
mapNum += ot.getDirectMappedSamplesNumber();
}
return mapNum;
}
public Collection<OntologyTerm> getAllOntologyTermsFromTo(int from, int to) {
return ontologyTermRepository.findAllFromTo(from, to);
}
public void saveOntologyTerm(OntologyTerm ot){
ontologyTermRepository.save(ot);
}
public void deleteOntologyTermsWithoutMapping(){
ontologyTermRepository.deleteTermsWithZeroMappings();
}
public void saveMarker(Marker marker) {
markerRepository.save(marker);
}
public Collection<Marker> getAllMarkers() {
return markerRepository.findAllMarkers();
}
public Collection<Marker> getAllHumanMarkers() {
return markerRepository.findAllHumanMarkers();
}
public Platform getPlatform(String name, Group group) {
//remove special characters from platform name
name = name.replaceAll("[^A-Za-z0-9 _-]", "");
Platform p = platformRepository.findByNameAndDataSource(name, group.getName());
if (p == null) {
p = new Platform();
p.setName(name);
p.setGroup(group);
platformRepository.save(p);
}
return p;
}
public Platform getPlatform(String name, Group group, String platformUrl) {
//remove special characters from platform name
name = name.replaceAll("[^A-Za-z0-9 _-]", "");
Platform p = platformRepository.findByNameAndDataSourceAndUrl(name, group.getName(), platformUrl);
if (p == null) {
p = new Platform();
p.setName(name);
p.setGroup(group);
p.setUrl(platformUrl);
}
return p;
}
public void savePlatform(Platform p){
platformRepository.save(p);
}
public PlatformAssociation createPlatformAssociation(Platform p, Marker m) {
if (platformAssociationRepository == null) {
System.out.println("PAR is null");
}
if (p == null) {
System.out.println("Platform is null");
}
if (p.getGroup() == null) {
System.out.println("P.EDS is null");
}
if (m == null) {
System.out.println("Marker is null");
}
PlatformAssociation pa = platformAssociationRepository.findByPlatformAndMarker(p.getName(), p.getGroup().getName(), m.getSymbol());
if (pa == null) {
pa = new PlatformAssociation();
pa.setPlatform(p);
pa.setMarker(m);
//platformAssociationRepository.save(pa);
}
return pa;
}
public void savePlatformAssociation(PlatformAssociation pa){
platformAssociationRepository.save(pa);
}
public void saveDataProjection(DataProjection dp){
dataProjectionRepository.save(dp);
}
public DataProjection findDataProjectionByLabel(String label){
return dataProjectionRepository.findByLabel(label);
}
public boolean isTreatmentSummaryAvailableOnModel(String dataSource, String modelId){
TreatmentSummary ts = treatmentSummaryRepository.findModelTreatmentByDataSourceAndModelId(dataSource, modelId);
if(ts != null && ts.getTreatmentProtocols() != null){
return true;
}
return false;
}
public boolean isTreatmentSummaryAvailableOnPatient(String dataSource, String modelId){
TreatmentSummary ts = treatmentSummaryRepository.findPatientTreatmentByDataSourceAndModelId(dataSource, modelId);
if(ts != null && ts.getTreatmentProtocols() != null){
return true;
}
return false;
}
public ModelCreation findModelByTreatmentSummary(TreatmentSummary ts){
return modelCreationRepository.findByTreatmentSummary(ts);
}
public Drug getStandardizedDrug(String drugString){
Drug d = new Drug();
d.setName(Standardizer.getDrugName(drugString));
return d;
}
public CurrentTreatment getCurrentTreatment(String name){
CurrentTreatment ct = currentTreatmentRepository.findByName(name);
if(ct == null){
ct = new CurrentTreatment(name);
currentTreatmentRepository.save(ct);
}
return ct;
}
/**
*
* @param drugString
* @param doseString
* @param response
* @return
*
* Creates a (tp:TreatmentProtocol)--(tc:TreatmentComponent)--(d:Drug)
* (tp)--(r:Response) node
*
* If drug names are separated with + it will create multiple components to represent drug combos
* Doses should be separated with either + or ;
*/
public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response, String responseClassification){
TreatmentProtocol tp = new TreatmentProtocol();
//combination of drugs?
if(drugString.contains("+") && doseString.contains(";")){
String[] drugArray = drugString.split("\\+");
String[] doseArray = doseString.split(";");
if(drugArray.length == doseArray.length){
for(int i=0;i<drugArray.length;i++){
Drug d = getStandardizedDrug(drugArray[i].trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugArray[i]));
tc.setDose(doseArray[i].trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
}
else{
//TODO: deal with the case when there are more drugs than doses or vice versa
}
}
else if(drugString.contains("+") && !doseString.contains(";")){
if(doseString.contains("+")){
//this data is coming from the universal loader, dose combinations are separated with + instead of ;
String[] drugArray = drugString.split("\\+");
String[] doseArray = doseString.split("\\+");
if(drugArray.length == doseArray.length){
for(int i=0;i<drugArray.length;i++){
Drug d = getStandardizedDrug(drugArray[i].trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugArray[i]));
tc.setDose(doseArray[i].trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
}
}
else{
String[] drugArray = drugString.split("\\+");
for(int i=0;i<drugArray.length;i++){
Drug d = getStandardizedDrug(drugArray[i].trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugArray[i]));
tc.setDose(doseString.trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
}
}
//one drug only
else{
Drug d = getStandardizedDrug(drugString.trim());
TreatmentComponent tc = new TreatmentComponent();
tc.setType(Standardizer.getTreatmentComponentType(drugString));
tc.setDrug(d);
tc.setDose(doseString.trim());
//don't load unknown drugs
if(!d.getName().equals("Not Specified")){
tc.setDrug(d);
tp.addTreatmentComponent(tc);
}
}
Response r = new Response();
r.setDescription(Standardizer.getDrugResponse(response));
r.setDescriptionClassification(responseClassification);
tp.setResponse(r);
if(tp.getComponents() == null || tp.getComponents().size() == 0) return null;
return tp;
}
public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response, boolean currentTreatment){
TreatmentProtocol tp = getTreatmentProtocol(drugString, doseString, response, "");
if(currentTreatment && tp.getCurrentTreatment() == null){
CurrentTreatment ct = getCurrentTreatment("Current Treatment");
tp.setCurrentTreatment(ct);
}
return tp;
}
public TreatmentSummary findTreatmentSummaryByPatientSnapshot(PatientSnapshot ps){
return treatmentSummaryRepository.findByPatientSnapshot(ps);
}
public Set<Object> findUnlinkedNodes(){
return dataProjectionRepository.findUnlinkedNodes();
}
public Set<Object> findPatientsWithMultipleSummaries(){
return dataProjectionRepository.findPatientsWithMultipleTreatmentSummaries();
}
public Set<Object> findPlatformsWithoutUrl(){
return dataProjectionRepository.findPlatformsWithoutUrl();
}
public QualityAssurance getQualityAssurance(JSONObject data, String ds) throws Exception{
QualityAssurance qa = new QualityAssurance();
String qaType = Standardizer.NOT_SPECIFIED;
if (ds.equals("JAX")){
String qaPassages = Standardizer.NOT_SPECIFIED;
// Pending or Complete
String qc = data.getString("QC");
if("Pending".equals(qc)){
qc = Standardizer.NOT_SPECIFIED;
}else{
qc = "QC is "+qc;
}
// the validation techniques are more than just fingerprint, we don't have a way to capture that
qa = new QualityAssurance("Fingerprint", qc, qaPassages);
saveQualityAssurance(qa);
}
if (ds.equals("PDXNet-HCI-BCM")){
// This multiple QA approach only works because Note and Passage are the same for all QAs
qa = new QualityAssurance(Standardizer.NOT_SPECIFIED,Standardizer.NOT_SPECIFIED,Standardizer.NOT_SPECIFIED);
StringBuilder technology = new StringBuilder();
if(data.has("QA")){
JSONArray qas = data.getJSONArray("QA");
for (int i = 0; i < qas.length(); i++) {
if (qas.getJSONObject(i).getString("Technology").equalsIgnoreCase("histology")) {
qa.setTechnology(qas.getJSONObject(i).getString("Technology"));
qa.setDescription(qas.getJSONObject(i).getString("Note"));
qa.setPassages(qas.getJSONObject(i).getString("Passage"));
}
}
}
}
if (ds.equals("PDXNet-MDAnderson") || ds.equals("PDXNet-WUSTL")) {
try {
qaType = data.getString("QA") + " on passage " + data.getString("QA Passage");
} catch (Exception e) {
// not all groups supplied QA
}
String qaPassage = data.has("QA Passage") ? data.getString("QA Passage") : null;
qa = new QualityAssurance(qaType, Standardizer.NOT_SPECIFIED, qaPassage);
saveQualityAssurance(qa);
}
if (ds.equals("IRCC-CRC")) {
String FINGERPRINT_DESCRIPTION = "Model validated against patient germline.";
if ("TRUE".equals(data.getString("Fingerprinting").toUpperCase())) {
qa.setTechnology("Fingerprint");
qa.setDescription(FINGERPRINT_DESCRIPTION);
// If the model includes which passages have had QA performed, set the passages on the QA node
if (data.has("QA Passage") && !data.getString("QA Passage").isEmpty()) {
List<String> passages = Stream.of(data.getString("QA Passage").split(","))
.map(String::trim)
.distinct()
.collect(Collectors.toList());
List<Integer> passageInts = new ArrayList<>();
// NOTE: IRCC uses passage 0 to mean Patient Tumor, so we need to harmonize according to the other
// sources. Subtract 1 from every passage.
for (String p : passages) {
Integer intPassage = Integer.parseInt(p);
passageInts.add(intPassage - 1);
}
qa.setPassages(StringUtils.join(passageInts, ", "));
}
}
}
return qa;
}
@Cacheable
public Marker getMarkerBySymbol(String symbol){
return markerRepository.findBySymbol(symbol);
}
@Cacheable
public List<Marker> getMarkerByPrevSymbol(String symbol){
return markerRepository.findByPrevSymbol(symbol);
}
@Cacheable
public List<Marker> getMarkerBySynonym(String symbol){
return markerRepository.findBySynonym(symbol);
}
public NodeSuggestionDTO getSuggestedMarker(String reporter, String dataSource, String modelId, String symbol){
NodeSuggestionDTO nsdto = new NodeSuggestionDTO();
LogEntity le;
Marker m;
List<Marker> markerSuggestionList = null;
boolean ready = false;
//check if marker is cached
if(markersBySymbol.containsKey(symbol)){
m = markersBySymbol.get(symbol);
nsdto.setNode(m);
ready = true;
}
else if(markersByPrevSymbol.containsKey(symbol)){
m = markersByPrevSymbol.get(symbol);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Previous symbol");
nsdto.setLogEntity(le);
ready = true;
}
else if(markersBySynonym.containsKey(symbol)){
m = markersBySynonym.get(symbol);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Synonym");
nsdto.setLogEntity(le);
ready = true;
}
if(ready) return nsdto;
m = getMarkerBySymbol(symbol);
if(m != null){
//good, pass the marker
//no message
nsdto.setNode(m);
markersBySymbol.put(symbol, m);
}
else{
markerSuggestionList = getMarkerByPrevSymbol(symbol);
if(markerSuggestionList != null && markerSuggestionList.size() > 0){
if(markerSuggestionList.size() == 1){
//symbol found in prev symbols
m = markerSuggestionList.get(0);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Previous symbol");
nsdto.setNode(m);
nsdto.setLogEntity(le);
markersByPrevSymbol.put(symbol, m);
}
else{
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, "","");
le.setMessage("Previous symbol for multiple terms");
le.setType("ERROR");
nsdto.setNode(null);
nsdto.setLogEntity(le);
}
}
else{
markerSuggestionList = getMarkerBySynonym(symbol);
if(markerSuggestionList != null && markerSuggestionList.size() > 0){
if(markerSuggestionList.size() == 1){
//symbol found in synonym
m = markerSuggestionList.get(0);
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, m.getSymbol(),"Synonym");
nsdto.setNode(m);
nsdto.setLogEntity(le);
markersBySynonym.put(symbol, m);
}
else{
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, "","");
le.setMessage("Synonym for multiple terms");
le.setType("ERROR");
nsdto.setNode(null);
nsdto.setLogEntity(le);
}
}
else{
//error, didn't find the symbol anywhere
le = new MarkerLogEntity(reporter,dataSource, modelId, symbol, "","");
le.setMessage(symbol +" is an unrecognised symbol, skipping");
le.setType("ERROR");
nsdto.setLogEntity(le);
}
}
}
return nsdto;
}
}
| Remove methods that directly create markers
| data-services/src/main/java/org/pdxfinder/services/DataImportService.java | Remove methods that directly create markers | <ide><path>ata-services/src/main/java/org/pdxfinder/services/DataImportService.java
<ide> }
<ide> return hostStrain;
<ide> }
<del>
<add>/*
<ide> // is this bad? ... probably..
<ide> public Marker getMarker(String symbol) {
<add> log.error("MARKER METHOD WAS CALLED!");
<ide> return this.getMarker(symbol, symbol);
<ide> }
<ide>
<ide> public Marker getMarker(String symbol, String name) {
<del>
<add> log.error("MARKER METHOD WAS CALLED!");
<ide> Marker marker = markerRepository.findByName(name);
<ide> if (marker == null && symbol != null) {
<ide> marker = markerRepository.findBySymbol(symbol);
<ide> return ma;
<ide> }
<ide>
<del>
<add>*/
<ide> public Set<MarkerAssociation> findMarkerAssocsByMolChar(MolecularCharacterization mc){
<ide>
<ide> return markerAssociationRepository.findByMolChar(mc); |
|
Java | apache-2.0 | error: pathspec 'opensources/src/onehao/threads/TraditionalThreadSynchronized.java' did not match any file(s) known to git
| 76841de1817b5643df8b7b7895413257a731c271 | 1 | onehao/opensource,onehao/opensource,onehao/opensource,onehao/opensource | package onehao.threads;
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
public void init(){
final Outputer out = new Outputer();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.output("hello----------------");
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.output("world");
}
}
}).start();
}
static class Outputer{
public synchronized void output(String name){ //lock this object, so sync with output3
int len = name.length();
for(int i = 0; i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
public static synchronized void output4(String name){ //lock this object
int len = name.length();
for(int i = 0; i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
public void output5(String name){ // sync with output4,字节码对象。
int len = name.length();
synchronized(Outputer.class){
for(int i = 0; i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public void output2(String name){
String sync = "";
int len = name.length();
synchronized(sync){
for(int i = 0; i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public void output3(String name){
int len = name.length();
synchronized(this){
for(int i = 0; i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
}
| opensources/src/onehao/threads/TraditionalThreadSynchronized.java | : 3-传统线程互斥技术
Task-Url: | opensources/src/onehao/threads/TraditionalThreadSynchronized.java | : 3-传统线程互斥技术 | <ide><path>pensources/src/onehao/threads/TraditionalThreadSynchronized.java
<add>package onehao.threads;
<add>
<add>public class TraditionalThreadSynchronized {
<add>
<add> public static void main(String[] args) {
<add>
<add> new TraditionalThreadSynchronized().init();
<add>
<add> }
<add>
<add> public void init(){
<add> final Outputer out = new Outputer();
<add> new Thread(new Runnable(){
<add> @Override
<add> public void run() {
<add> while(true){
<add> try {
<add> Thread.sleep(10);
<add> } catch (InterruptedException e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> }
<add> out.output("hello----------------");
<add> }
<add>
<add> }
<add> }).start();
<add>
<add> new Thread(new Runnable(){
<add> @Override
<add> public void run() {
<add> while(true){
<add> try {
<add> Thread.sleep(10);
<add> } catch (InterruptedException e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> }
<add> out.output("world");
<add> }
<add>
<add> }
<add> }).start();
<add> }
<add>
<add> static class Outputer{
<add> public synchronized void output(String name){ //lock this object, so sync with output3
<add> int len = name.length();
<add> for(int i = 0; i<len;i++){
<add> System.out.print(name.charAt(i));
<add> }
<add> System.out.println();
<add>
<add> }
<add>
<add> public static synchronized void output4(String name){ //lock this object
<add> int len = name.length();
<add> for(int i = 0; i<len;i++){
<add> System.out.print(name.charAt(i));
<add> }
<add> System.out.println();
<add>
<add> }
<add>
<add> public void output5(String name){ // sync with output4,字节码对象。
<add> int len = name.length();
<add> synchronized(Outputer.class){
<add> for(int i = 0; i<len;i++){
<add> System.out.print(name.charAt(i));
<add> }
<add> System.out.println();
<add> }
<add>
<add> }
<add>
<add> public void output2(String name){
<add> String sync = "";
<add> int len = name.length();
<add> synchronized(sync){
<add> for(int i = 0; i<len;i++){
<add> System.out.print(name.charAt(i));
<add> }
<add> System.out.println();
<add> }
<add>
<add> }
<add>
<add> public void output3(String name){
<add> int len = name.length();
<add> synchronized(this){
<add> for(int i = 0; i<len;i++){
<add> System.out.print(name.charAt(i));
<add> }
<add> System.out.println();
<add> }
<add>
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | 3337d7a9d23d58402da9a339022eeb09c5860d80 | 0 | elastic/elasticsearch-hadoop,elastic/elasticsearch-hadoop,takezoe/elasticsearch-hadoop,xjrk58/elasticsearch-hadoop | mr/src/test/java/org/elasticsearch/hadoop/PartitionDefinitionTest.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.hadoop;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.hadoop.cfg.PropertiesSettings;
import org.elasticsearch.hadoop.serialization.dto.mapping.Field;
import org.elasticsearch.hadoop.util.FastByteArrayInputStream;
import org.elasticsearch.hadoop.util.FastByteArrayOutputStream;
import org.junit.Test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class PartitionDefinitionTest {
@Test
public void testWritable() throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory()
.createJsonParser(getClass().getResourceAsStream("serialization/dto/mapping/basic.json"));
Map<String, Object> map =
(Map<String, Object>) mapper.readValue(jsonParser, Map.class);
Field mapping = Field.parseField(map);
PropertiesSettings settings = new PropertiesSettings();
settings.setProperty("setting1", "value1");
settings.setProperty("setting2", "value2");
PartitionDefinition expected = new PartitionDefinition("foo", 12, new PartitionDefinition.Slice(10, 27), settings, mapping);
FastByteArrayOutputStream out = new FastByteArrayOutputStream();
DataOutputStream da = new DataOutputStream(out);
expected.write(da);
out.close();
FastByteArrayInputStream in = new FastByteArrayInputStream(out.bytes());
DataInputStream di = new DataInputStream(in);
PartitionDefinition def = new PartitionDefinition(di);
assertEquals(def, expected);
// the settings and the mapping are ignored in PartitionDefinition#equals
// we need to test them separately
assertEquals(def.getSerializedSettings(), expected.getSerializedSettings());
assertEquals(def.getSerializedMapping(), expected.getSerializedMapping());
}
@Test
public void testSerializable() throws IOException, ClassNotFoundException {
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory()
.createJsonParser(getClass().getResourceAsStream("serialization/dto/mapping/basic.json"));
Map<String, Object> map =
(Map<String, Object>) mapper.readValue(jsonParser, Map.class);
Field mapping = Field.parseField(map);
PropertiesSettings settings = new PropertiesSettings();
settings.setProperty("setting1", "value1");
settings.setProperty("setting2", "value2");
PartitionDefinition expected = new PartitionDefinition("bar", 37, new PartitionDefinition.Slice(13, 35), settings, mapping);
FastByteArrayOutputStream out = new FastByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(expected);
oos.close();
FastByteArrayInputStream in = new FastByteArrayInputStream(out.bytes());
ObjectInputStream ois = new ObjectInputStream(in);
PartitionDefinition def = (PartitionDefinition) ois.readObject();
assertEquals(def, expected);
// the settings and the mapping are ignored in PartitionDefinition#equals
// we need to test them separately
assertEquals(def.getSerializedSettings(), expected.getSerializedSettings());
assertEquals(def.getSerializedMapping(), expected.getSerializedMapping());
}
}
| Fix test
| mr/src/test/java/org/elasticsearch/hadoop/PartitionDefinitionTest.java | Fix test | <ide><path>r/src/test/java/org/elasticsearch/hadoop/PartitionDefinitionTest.java
<del>/*
<del> * Licensed to Elasticsearch under one or more contributor
<del> * license agreements. See the NOTICE file distributed with
<del> * this work for additional information regarding copyright
<del> * ownership. Elasticsearch licenses this file to you under
<del> * the Apache License, Version 2.0 (the "License"); you may
<del> * not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing,
<del> * software distributed under the License is distributed on an
<del> * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<del> * KIND, either express or implied. See the License for the
<del> * specific language governing permissions and limitations
<del> * under the License.
<del> */
<del>package org.elasticsearch.hadoop;
<del>
<del>import org.codehaus.jackson.JsonParser;
<del>import org.codehaus.jackson.map.ObjectMapper;
<del>import org.elasticsearch.hadoop.cfg.PropertiesSettings;
<del>import org.elasticsearch.hadoop.serialization.dto.mapping.Field;
<del>import org.elasticsearch.hadoop.util.FastByteArrayInputStream;
<del>import org.elasticsearch.hadoop.util.FastByteArrayOutputStream;
<del>import org.junit.Test;
<del>
<del>import java.io.DataInputStream;
<del>import java.io.DataOutputStream;
<del>import java.io.IOException;
<del>import java.io.ObjectInputStream;
<del>import java.io.ObjectOutputStream;
<del>import java.util.Map;
<del>
<del>import static org.junit.Assert.assertEquals;
<del>
<del>public class PartitionDefinitionTest {
<del> @Test
<del> public void testWritable() throws IOException {
<del> ObjectMapper mapper = new ObjectMapper();
<del> JsonParser jsonParser = mapper.getJsonFactory()
<del> .createJsonParser(getClass().getResourceAsStream("serialization/dto/mapping/basic.json"));
<del> Map<String, Object> map =
<del> (Map<String, Object>) mapper.readValue(jsonParser, Map.class);
<del> Field mapping = Field.parseField(map);
<del> PropertiesSettings settings = new PropertiesSettings();
<del> settings.setProperty("setting1", "value1");
<del> settings.setProperty("setting2", "value2");
<del> PartitionDefinition expected = new PartitionDefinition("foo", 12, new PartitionDefinition.Slice(10, 27), settings, mapping);
<del> FastByteArrayOutputStream out = new FastByteArrayOutputStream();
<del> DataOutputStream da = new DataOutputStream(out);
<del> expected.write(da);
<del> out.close();
<del>
<del> FastByteArrayInputStream in = new FastByteArrayInputStream(out.bytes());
<del> DataInputStream di = new DataInputStream(in);
<del> PartitionDefinition def = new PartitionDefinition(di);
<del> assertEquals(def, expected);
<del> // the settings and the mapping are ignored in PartitionDefinition#equals
<del> // we need to test them separately
<del> assertEquals(def.getSerializedSettings(), expected.getSerializedSettings());
<del> assertEquals(def.getSerializedMapping(), expected.getSerializedMapping());
<del>
<del> }
<del>
<del> @Test
<del> public void testSerializable() throws IOException, ClassNotFoundException {
<del> ObjectMapper mapper = new ObjectMapper();
<del> JsonParser jsonParser = mapper.getJsonFactory()
<del> .createJsonParser(getClass().getResourceAsStream("serialization/dto/mapping/basic.json"));
<del> Map<String, Object> map =
<del> (Map<String, Object>) mapper.readValue(jsonParser, Map.class);
<del> Field mapping = Field.parseField(map);
<del> PropertiesSettings settings = new PropertiesSettings();
<del> settings.setProperty("setting1", "value1");
<del> settings.setProperty("setting2", "value2");
<del> PartitionDefinition expected = new PartitionDefinition("bar", 37, new PartitionDefinition.Slice(13, 35), settings, mapping);
<del> FastByteArrayOutputStream out = new FastByteArrayOutputStream();
<del> ObjectOutputStream oos = new ObjectOutputStream(out);
<del> oos.writeObject(expected);
<del> oos.close();
<del>
<del> FastByteArrayInputStream in = new FastByteArrayInputStream(out.bytes());
<del> ObjectInputStream ois = new ObjectInputStream(in);
<del> PartitionDefinition def = (PartitionDefinition) ois.readObject();
<del> assertEquals(def, expected);
<del> // the settings and the mapping are ignored in PartitionDefinition#equals
<del> // we need to test them separately
<del> assertEquals(def.getSerializedSettings(), expected.getSerializedSettings());
<del> assertEquals(def.getSerializedMapping(), expected.getSerializedMapping());
<del> }
<del>} |
||
Java | apache-2.0 | 42c31584fc691f1c08f6e600d806892e16882101 | 0 | Netflix/conductor,Netflix/conductor,Netflix/conductor,Netflix/conductor,Netflix/conductor | package com.netflix.conductor.zookeeper;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.netflix.conductor.core.utils.Lock;
import com.netflix.conductor.zookeeper.config.ZookeeperConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.concurrent.TimeUnit;
public class ZookeeperLock implements Lock {
public static final int CACHE_MAXSIZE = 20000;
public static final int CACHE_EXPIRY_TIME = 10;
private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperLock.class);
private CuratorFramework client;
private LoadingCache<String, InterProcessMutex> zkLocks;
private String zkPath;
@Inject
public ZookeeperLock(ZookeeperConfiguration config, String namespace) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.newClient(
config.getZkConnection(),
config.getZkSessiontimeoutMs(),
config.getZkConnectiontimeoutMs(),
retryPolicy
);
client.start();
zkLocks = CacheBuilder.newBuilder()
.maximumSize(CACHE_MAXSIZE)
.expireAfterAccess(CACHE_EXPIRY_TIME, TimeUnit.MINUTES)
.build(new CacheLoader<String, InterProcessMutex>() {
@Override
public InterProcessMutex load(String key) throws Exception {
return new InterProcessMutex(client, zkPath.concat(key));
}
}
);
zkPath = StringUtils.isEmpty(namespace)
? ("/conductor/")
: ("/conductor/" + namespace + "/");
}
public void acquireLock(String lockId) {
if (StringUtils.isEmpty(lockId)) {
throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
}
try {
InterProcessMutex mutex = zkLocks.get(lockId);
mutex.acquire();
} catch (Exception e) {
LOGGER.debug("Failed in acquireLock: ", e);
}
}
public boolean acquireLock(String lockId, long timeToTry, TimeUnit unit) {
if (StringUtils.isEmpty(lockId)) {
throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
}
try {
InterProcessMutex mutex = zkLocks.get(lockId);
return mutex.acquire(timeToTry, unit);
} catch (Exception e) {
LOGGER.debug("Failed in acquireLock: ", e);
}
return false;
}
public void releaseLock(String lockId) {
if (StringUtils.isEmpty(lockId)) {
throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
}
try {
InterProcessMutex lock = zkLocks.getIfPresent(lockId);
if (lock != null) {
lock.release();
}
} catch (Exception e) {
LOGGER.debug("Failed in releaseLock: ", e);
}
}
public void deleteLock(String lockId) {
try {
LOGGER.debug("Deleting lock {}", zkPath.concat(lockId));
client.delete().guaranteed().forPath(zkPath.concat(lockId));
} catch (Exception e) {
LOGGER.debug("Failed to removeLock: ", e);
}
}
}
| zookeeper-lock/src/main/java/com/netflix/conductor/zookeeper/ZookeeperLock.java | package com.netflix.conductor.zookeeper;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.netflix.conductor.core.utils.Lock;
import com.netflix.conductor.zookeeper.config.ZookeeperConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.concurrent.TimeUnit;
public class ZookeeperLock implements Lock {
public static final int CACHE_MAXSIZE = 20000;
public static final int CACHE_EXPIRY_TIME = 10;
private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperLock.class);
private CuratorFramework client;
private LoadingCache<String, InterProcessMutex> zkLocks;
private String zkPath;
@Inject
public ZookeeperLock(ZookeeperConfiguration config, String namespace) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.newClient(
config.getZkConnection(),
config.getZkSessiontimeoutMs(),
config.getZkConnectiontimeoutMs(),
retryPolicy
);
client.start();
zkLocks = CacheBuilder.newBuilder()
.maximumSize(CACHE_MAXSIZE)
.expireAfterAccess(CACHE_EXPIRY_TIME, TimeUnit.MINUTES)
.build(new CacheLoader<String, InterProcessMutex>() {
@Override
public InterProcessMutex load(String key) throws Exception {
return new InterProcessMutex(client, zkPath.concat(key));
}
}
);
zkPath = StringUtils.isEmpty(namespace)
? ("/conductor/")
: ("/conductor/" + namespace + "/");
}
public void acquireLock(String lockId) {
if (StringUtils.isEmpty(lockId)) {
throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
}
try {
InterProcessMutex mutex = zkLocks.get(lockId);
mutex.acquire();
} catch (Exception e) {
LOGGER.debug("Failed in acquireLock: ", e);
}
}
public boolean acquireLock(String lockId, long timeToTry, TimeUnit unit) {
if (StringUtils.isEmpty(lockId)) {
throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
}
try {
InterProcessMutex mutex = zkLocks.get(lockId);
return mutex.acquire(timeToTry, unit);
} catch (Exception e) {
LOGGER.debug("Failed in acquireLock: ", e);
}
return false;
}
public void releaseLock(String lockId) {
if (StringUtils.isEmpty(lockId)) {
throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId);
}
try {
InterProcessMutex lock = zkLocks.getIfPresent(lockId);
if (lock != null) {
lock.release();
}
} catch (Exception e) {
LOGGER.debug("Failed in releaseLock: ", e);
}
}
public void deleteLock(String lockId) {
try {
LOGGER.debug("Deleting lock {}", zkPath.concat(lockId));
client.delete().inBackground().forPath(zkPath.concat(lockId));
} catch (Exception e) {
LOGGER.debug("Failed to removeLock: ", e);
}
}
}
| Change to ZK nodes guaranteed delete instead of background delete.
| zookeeper-lock/src/main/java/com/netflix/conductor/zookeeper/ZookeeperLock.java | Change to ZK nodes guaranteed delete instead of background delete. | <ide><path>ookeeper-lock/src/main/java/com/netflix/conductor/zookeeper/ZookeeperLock.java
<ide> public void deleteLock(String lockId) {
<ide> try {
<ide> LOGGER.debug("Deleting lock {}", zkPath.concat(lockId));
<del> client.delete().inBackground().forPath(zkPath.concat(lockId));
<add> client.delete().guaranteed().forPath(zkPath.concat(lockId));
<ide> } catch (Exception e) {
<ide> LOGGER.debug("Failed to removeLock: ", e);
<ide> } |
|
JavaScript | mit | 4f5f8ce978bf5cc6c42d9dc5a35d57ab424409b7 | 0 | AanZee/generator-harbour | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.generators.Base.extend({
initializing: function () {
this.pkg = require('../package.json');
},
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'You\'re about to install ' + chalk.blue('Harbour') + '!'
));
var prompts = [{
type: 'confirm',
name: 'someOption',
message: 'Would you like to enable this option?',
default: true
}];
this.prompt(prompts, function (props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
},
writing: function() {
this.files = this.expandFiles('**/*', { cwd: this.sourceRoot(), dot: true });
var ignores = [
'.git',
'LICENSE',
'README.md',
];
this.files.forEach(function(file) {
if (ignores.indexOf(file) !== -1) {
return;
}
this.copy(file, file);
}, this);
},
install: function () {
this.installDependencies();
}
});
| app/index.js | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.generators.Base.extend({
initializing: function () {
this.pkg = require('../package.json');
},
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the world-class ' + chalk.red('Harbour') + ' generator!'
));
var prompts = [{
type: 'confirm',
name: 'someOption',
message: 'Would you like to enable this option?',
default: true
}];
this.prompt(prompts, function (props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
},
writing: {
app: function () {
this.fs.copy(
this.templatePath('_package.json'),
this.destinationPath('package.json')
);
this.fs.copy(
this.templatePath('_bower.json'),
this.destinationPath('bower.json')
);
},
projectfiles: function () {
this.fs.copy(
this.templatePath('editorconfig'),
this.destinationPath('.editorconfig')
);
this.fs.copy(
this.templatePath('jshintrc'),
this.destinationPath('.jshintrc')
);
}
},
install: function () {
this.installDependencies();
}
});
| Added directory copy
| app/index.js | Added directory copy | <ide><path>pp/index.js
<ide> var yosay = require('yosay');
<ide>
<ide> module.exports = yeoman.generators.Base.extend({
<del> initializing: function () {
<del> this.pkg = require('../package.json');
<del> },
<add> initializing: function () {
<add> this.pkg = require('../package.json');
<add> },
<ide>
<del> prompting: function () {
<del> var done = this.async();
<add> prompting: function () {
<add> var done = this.async();
<ide>
<del> // Have Yeoman greet the user.
<del> this.log(yosay(
<del> 'Welcome to the world-class ' + chalk.red('Harbour') + ' generator!'
<del> ));
<add> // Have Yeoman greet the user.
<add> this.log(yosay(
<add> 'You\'re about to install ' + chalk.blue('Harbour') + '!'
<add> ));
<ide>
<del> var prompts = [{
<del> type: 'confirm',
<del> name: 'someOption',
<del> message: 'Would you like to enable this option?',
<del> default: true
<del> }];
<add> var prompts = [{
<add> type: 'confirm',
<add> name: 'someOption',
<add> message: 'Would you like to enable this option?',
<add> default: true
<add> }];
<ide>
<del> this.prompt(prompts, function (props) {
<del> this.props = props;
<del> // To access props later use this.props.someOption;
<add> this.prompt(prompts, function (props) {
<add> this.props = props;
<add> // To access props later use this.props.someOption;
<ide>
<del> done();
<del> }.bind(this));
<del> },
<add> done();
<add> }.bind(this));
<add> },
<ide>
<del> writing: {
<del> app: function () {
<del> this.fs.copy(
<del> this.templatePath('_package.json'),
<del> this.destinationPath('package.json')
<del> );
<del> this.fs.copy(
<del> this.templatePath('_bower.json'),
<del> this.destinationPath('bower.json')
<del> );
<del> },
<add> writing: function() {
<add> this.files = this.expandFiles('**/*', { cwd: this.sourceRoot(), dot: true });
<ide>
<del> projectfiles: function () {
<del> this.fs.copy(
<del> this.templatePath('editorconfig'),
<del> this.destinationPath('.editorconfig')
<del> );
<del> this.fs.copy(
<del> this.templatePath('jshintrc'),
<del> this.destinationPath('.jshintrc')
<del> );
<del> }
<del> },
<add> var ignores = [
<add> '.git',
<add> 'LICENSE',
<add> 'README.md',
<add> ];
<ide>
<del> install: function () {
<del> this.installDependencies();
<del> }
<add> this.files.forEach(function(file) {
<add> if (ignores.indexOf(file) !== -1) {
<add> return;
<add> }
<add>
<add> this.copy(file, file);
<add> }, this);
<add> },
<add>
<add> install: function () {
<add> this.installDependencies();
<add> }
<ide> }); |
|
Java | mit | 0e0a4cdd52433534b16783991117ec4849af5632 | 0 | jbosboom/streamjit,jbosboom/streamjit | package edu.mit.streamjit.util.bytecode.insts;
import com.google.common.base.Function;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.ImmutableList;
import edu.mit.streamjit.util.bytecode.Value;
import edu.mit.streamjit.util.bytecode.types.PrimitiveType;
/**
* A binary mathematical operation.
* @author Jeffrey Bosboom <[email protected]>
* @since 4/15/2013
*/
public final class BinaryInst extends Instruction {
public enum Operation {
ADD("int", "long", "float", "double"),
SUB("int", "long", "float", "double"),
MUL("int", "long", "float", "double"),
DIV("int", "long", "float", "double"),
REM("int", "long", "float", "double"),
SHL("int", "long"),
SHR("int", "long"),
USHR("int", "long"),
AND("int", "long"),
OR("int", "long"),
XOR("int", "long"),
CMP("long", "float", "double"),
CMPG("float", "double");
private final ImmutableList<String> types;
private Operation(String... types) {
this.types = ImmutableList.copyOf(types);
}
public ImmutableList<String> applicableTypes() {
return types;
}
}
private final Operation operation;
public BinaryInst(Value left, Operation op, Value right) {
super(computeType(left, op, right), 2);
if (op == Operation.CMP || op == Operation.CMPG)
checkArgument(op.applicableTypes().contains(left.getType().toString()) &&
op.applicableTypes().contains(left.getType().toString()),
"%s %s %s", left.getType(), op, right.getType());
else
checkArgument(op.applicableTypes().contains(getType().toString()), "%s %s", op, getType());
setOperand(0, left);
setOperand(1, right);
this.operation = op;
}
@Override
public PrimitiveType getType() {
return (PrimitiveType)super.getType();
}
public Operation getOperation() {
return operation;
}
@Override
public BinaryInst clone(Function<Value, Value> operandMap) {
return new BinaryInst(operandMap.apply(getOperand(0)), operation, operandMap.apply(getOperand(1)));
}
private static PrimitiveType computeType(Value left, Operation operation, Value right) {
PrimitiveType intType = left.getType().getTypeFactory().getPrimitiveType(int.class);
//Comparisons are always int. (TODO: byte?)
if (operation == Operation.CMP || operation == Operation.CMPG)
return intType;
//If both promotable to int, result is int.
if (left.getType().isSubtypeOf(intType) && right.getType().isSubtypeOf(intType))
return intType;
//Else types must be primitive and equal.
if (left.getType().equals(right.getType()) && left.getType() instanceof PrimitiveType)
return (PrimitiveType)left.getType();
throw new IllegalArgumentException("type mismatch: "+left+" "+operation+" "+right);
}
@Override
public String toString() {
return String.format("%s (%s) = %s %s, %s",
getName(), getType(), getOperation(),
getOperand(0).getName(), getOperand(1).getName());
}
}
| src/edu/mit/streamjit/util/bytecode/insts/BinaryInst.java | package edu.mit.streamjit.util.bytecode.insts;
import com.google.common.base.Function;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.ImmutableList;
import edu.mit.streamjit.util.bytecode.Value;
import edu.mit.streamjit.util.bytecode.types.PrimitiveType;
/**
* A binary mathematical operation.
* @author Jeffrey Bosboom <[email protected]>
* @since 4/15/2013
*/
public final class BinaryInst extends Instruction {
public enum Operation {
ADD("int", "long", "float", "double"),
SUB("int", "long", "float", "double"),
MUL("int", "long", "float", "double"),
DIV("int", "long", "float", "double"),
REM("int", "long", "float", "double"),
SHL("int", "long"),
SHR("int", "long"),
USHR("int", "long"),
AND("int", "long"),
OR("int", "long"),
XOR("int", "long"),
CMP("long", "float", "double"),
CMPG("float", "double");
private final ImmutableList<String> types;
private Operation(String... types) {
this.types = ImmutableList.copyOf(types);
}
public ImmutableList<String> applicableTypes() {
return types;
}
}
private final Operation operation;
public BinaryInst(Value left, Operation op, Value right) {
super(computeType(left, op, right), 2);
if (op == Operation.CMP || op == Operation.CMPG)
checkArgument(op.applicableTypes().contains(left.getType().toString()) &&
op.applicableTypes().contains(left.getType().toString()),
"%s %s %s", left.getType(), op, right.getType());
else
checkArgument(op.applicableTypes().contains(getType().toString()), "%s %s", op, getType());
setOperand(0, left);
setOperand(1, right);
this.operation = op;
}
public Operation getOperation() {
return operation;
}
@Override
public BinaryInst clone(Function<Value, Value> operandMap) {
return new BinaryInst(operandMap.apply(getOperand(0)), operation, operandMap.apply(getOperand(1)));
}
private static PrimitiveType computeType(Value left, Operation operation, Value right) {
PrimitiveType intType = left.getType().getTypeFactory().getPrimitiveType(int.class);
//Comparisons are always int. (TODO: byte?)
if (operation == Operation.CMP || operation == Operation.CMPG)
return intType;
//If both promotable to int, result is int.
if (left.getType().isSubtypeOf(intType) && right.getType().isSubtypeOf(intType))
return intType;
//Else types must be primitive and equal.
if (left.getType().equals(right.getType()) && left.getType() instanceof PrimitiveType)
return (PrimitiveType)left.getType();
throw new IllegalArgumentException("type mismatch: "+left+" "+operation+" "+right);
}
@Override
public String toString() {
return String.format("%s (%s) = %s %s, %s",
getName(), getType(), getOperation(),
getOperand(0).getName(), getOperand(1).getName());
}
}
| Refine BinaryInst.getType() return type
| src/edu/mit/streamjit/util/bytecode/insts/BinaryInst.java | Refine BinaryInst.getType() return type | <ide><path>rc/edu/mit/streamjit/util/bytecode/insts/BinaryInst.java
<ide> this.operation = op;
<ide> }
<ide>
<add> @Override
<add> public PrimitiveType getType() {
<add> return (PrimitiveType)super.getType();
<add> }
<add>
<ide> public Operation getOperation() {
<ide> return operation;
<ide> } |
|
JavaScript | mit | 393bfe7a31197ad301c32b6bb79c4db605bc19b9 | 0 | andrewkshim/react-animatronics | // @flow
/**
* ControlsMachine: manages all of the component controls for withAnimatronics.
*
* @module internal/machines/controls-machine
*/
import Debug from 'debug'
import type { Styles, StyleUpdater, DOMNode, Controls } from '../flow-types'
const debug = Debug('animatronics:controls');
export const ControlsMachine = (): Controls => {
const _nodes: { [string]: DOMNode } = {};
const _styleUpdaters: { [string]: StyleUpdater } = {};
const registerComponent = (
componentName: string,
node: DOMNode,
styleUpdater: StyleUpdater,
) => {
debug('registering component "%s"', componentName,);
_nodes[componentName] = node;
_styleUpdaters[componentName] = styleUpdater;
};
const unregisterComponent = (componentName: string) => {
delete _nodes[componentName];
delete _styleUpdaters[componentName];
};
const updateStyles = (componentName: string, styles: Styles) => {
if (!_styleUpdaters[componentName]) {
// TODO: if the style updater doesn't exist, user might have misspelled rig name
// TODO: better error message
console.warn('_styleUpdates does not have componentName', componentName);
} else {
_styleUpdaters[componentName](styles);
}
};
const getNodes = () => _nodes;
const machine: Controls = {
registerComponent,
unregisterComponent,
updateStyles,
getNodes,
};
return machine;
}
| src/internal/machines/controls-machine.js | // @flow
/**
* ControlsMachine: manages all of the component controls for withAnimatronics.
*
* @module internal/machines/controls-machine
*/
import Debug from 'debug'
import type { Styles, StyleUpdater, DOMNode, Controls } from '../flow-types'
const debug = Debug('animatronics:controls');
export const ControlsMachine = (): Controls => {
const _nodes: { [string]: DOMNode } = {};
const _styleUpdaters: { [string]: StyleUpdater } = {};
const registerComponent = (
componentName: string,
node: DOMNode,
styleUpdater: StyleUpdater,
) => {
debug('registering component "%s"', componentName,);
_nodes[componentName] = node;
_styleUpdaters[componentName] = styleUpdater;
};
const unregisterComponent = (componentName: string) => {
delete _nodes[componentName];
delete _styleUpdaters[componentName];
};
const updateStyles = (componentName: string, styles: Styles) => {
// TODO: if the style updater doesn't exist, user might have misspelled rig name
_styleUpdaters[componentName](styles);
};
const getNodes = () => _nodes;
const machine: Controls = {
registerComponent,
unregisterComponent,
updateStyles,
getNodes,
};
return machine;
}
| :bug: [controls-machine] put styleUpdater behind if check
| src/internal/machines/controls-machine.js | :bug: [controls-machine] put styleUpdater behind if check | <ide><path>rc/internal/machines/controls-machine.js
<ide> };
<ide>
<ide> const updateStyles = (componentName: string, styles: Styles) => {
<del> // TODO: if the style updater doesn't exist, user might have misspelled rig name
<del> _styleUpdaters[componentName](styles);
<add> if (!_styleUpdaters[componentName]) {
<add> // TODO: if the style updater doesn't exist, user might have misspelled rig name
<add> // TODO: better error message
<add> console.warn('_styleUpdates does not have componentName', componentName);
<add> } else {
<add> _styleUpdaters[componentName](styles);
<add> }
<ide> };
<ide>
<ide> const getNodes = () => _nodes; |
|
Java | mit | 577ed7724b467af7d30cfee4523f2f4d0ca8f0f0 | 0 | CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab | package org.xcolab.entity.utils;
import org.json.JSONObject;
import org.xcolab.client.admin.AdminClient;
import org.xcolab.client.admin.pojo.ConfigurationAttribute;
import org.xcolab.util.attributes.AttributeGetter;
import org.xcolab.util.i18n.I18nUtils;
import java.util.ArrayList;
import java.util.List;
public abstract class WidgetPreference {
private final static String DEFAULT_ID = "default";
private final static String PREFERENCES_JSON_OBJECT = "preferences";
private final static String UNDERSCOREDIVIDER = "_";
private final List<String> allPreferenceIds = new ArrayList<>();
protected String preferenceId;
protected String language;
protected JSONObject prefs;
public WidgetPreference() {
this(DEFAULT_ID, I18nUtils.DEFAULT_LANGUAGE);
}
public WidgetPreference(String id, String language) {
boolean idWasNull = false;
if(id==null){
id = DEFAULT_ID;
idWasNull = true;
}
if (!idWasNull && language != null&&!id.contains("_")) {
id += UNDERSCOREDIVIDER + language;
}
prefs = new JSONObject(getConfigurationAttribute().get());
if (prefs.has(PREFERENCES_JSON_OBJECT)) {
JSONObject preferencesArray = prefs.getJSONObject(PREFERENCES_JSON_OBJECT);
//preferencesArray.keySet().stream().forEach(s -> allPreferenceIds.add(s));
for (int i = 0; i < preferencesArray.names().length(); i++) {
allPreferenceIds.add(preferencesArray.names().get(i).toString());
}
if (id != null) {
preferenceId = id;
} else {
preferenceId = UNDERSCOREDIVIDER + language;
//allPreferenceIds.add(DEFAULT_ID);
}
if (preferencesArray.has(preferenceId)) {
prefs = preferencesArray.getJSONObject(preferenceId);
} else {
prefs = preferencesArray.getJSONObject(DEFAULT_ID);
preferenceId = DEFAULT_ID + UNDERSCOREDIVIDER + language;
}
} else {
allPreferenceIds.add(DEFAULT_ID);
preferenceId = DEFAULT_ID;
}
}
public abstract AttributeGetter<String> getConfigurationAttribute();
protected void savePreferences(JSONObject prefsToSave, String id) {
id = (id == null ? (DEFAULT_ID) : (id));
JSONObject currentPreferences = new JSONObject(getConfigurationAttribute().get());
if (!currentPreferences.has(PREFERENCES_JSON_OBJECT)) {
JSONObject defaultPrefs = currentPreferences;
currentPreferences = new JSONObject();
JSONObject preferences = new JSONObject();
preferences.put(id, prefsToSave);
if (!id.equals(DEFAULT_ID)) {
preferences.put(DEFAULT_ID, defaultPrefs);
}
currentPreferences.put(PREFERENCES_JSON_OBJECT, preferences);
} else {
JSONObject preferences = currentPreferences.getJSONObject(PREFERENCES_JSON_OBJECT);
preferences.put(id, prefsToSave);
currentPreferences.put(PREFERENCES_JSON_OBJECT, preferences);
}
ConfigurationAttribute configurationAttribute = new ConfigurationAttribute();
configurationAttribute.setName(getConfigurationAttribute().name());
configurationAttribute.setStringValue(currentPreferences.toString());
AdminClient.updateConfigurationAttribute(configurationAttribute);
}
public String getPreferenceId() {
return preferenceId;
}
public void setPreferenceId(String preferenceId) {
this.preferenceId = preferenceId;
}
public JSONObject getPrefs() {
return prefs;
}
public void setPrefs(JSONObject prefs) {
this.prefs = prefs;
}
public List<String> getAllPreferenceIds() {
return allPreferenceIds;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
| microservices/util/entity-utils/src/main/java/org/xcolab/entity/utils/WidgetPreference.java | package org.xcolab.entity.utils;
import org.json.JSONObject;
import org.xcolab.client.admin.AdminClient;
import org.xcolab.client.admin.pojo.ConfigurationAttribute;
import org.xcolab.util.attributes.AttributeGetter;
import org.xcolab.util.i18n.I18nUtils;
import java.util.ArrayList;
import java.util.List;
public abstract class WidgetPreference {
private final static String DEFAULT_ID = "default";
private final static String PREFERENCES_JSON_OBJECT = "preferences";
private final static String UNDERSCOREDIVIDER = "_";
private final List<String> allPreferenceIds = new ArrayList<>();
protected String preferenceId;
protected String language;
protected JSONObject prefs;
public WidgetPreference() {
this(DEFAULT_ID, I18nUtils.DEFAULT_LANGUAGE);
}
public WidgetPreference(String id, String language) {
if(id==null){
id = DEFAULT_ID;
}
if (language != null) {
id += UNDERSCOREDIVIDER + language;
}
prefs = new JSONObject(getConfigurationAttribute().get());
if (prefs.has(PREFERENCES_JSON_OBJECT)) {
JSONObject preferencesArray = prefs.getJSONObject(PREFERENCES_JSON_OBJECT);
//preferencesArray.keySet().stream().forEach(s -> allPreferenceIds.add(s));
for (int i = 0; i < preferencesArray.names().length(); i++) {
allPreferenceIds.add(preferencesArray.names().get(i).toString());
}
if (id != null) {
preferenceId = id;
} else {
preferenceId = UNDERSCOREDIVIDER + language;
//allPreferenceIds.add(DEFAULT_ID);
}
if (preferencesArray.has(preferenceId)) {
prefs = preferencesArray.getJSONObject(preferenceId);
} else {
prefs = preferencesArray.getJSONObject(DEFAULT_ID);
preferenceId = DEFAULT_ID + UNDERSCOREDIVIDER + language;
}
} else {
allPreferenceIds.add(DEFAULT_ID);
preferenceId = DEFAULT_ID;
}
}
public abstract AttributeGetter<String> getConfigurationAttribute();
protected void savePreferences(JSONObject prefsToSave, String id) {
id = (id == null ? (DEFAULT_ID) : (id));
JSONObject currentPreferences = new JSONObject(getConfigurationAttribute().get());
if (!currentPreferences.has(PREFERENCES_JSON_OBJECT)) {
JSONObject defaultPrefs = currentPreferences;
currentPreferences = new JSONObject();
JSONObject preferences = new JSONObject();
preferences.put(id, prefsToSave);
if (!id.equals(DEFAULT_ID)) {
preferences.put(DEFAULT_ID, defaultPrefs);
}
currentPreferences.put(PREFERENCES_JSON_OBJECT, preferences);
} else {
JSONObject preferences = currentPreferences.getJSONObject(PREFERENCES_JSON_OBJECT);
preferences.put(id, prefsToSave);
currentPreferences.put(PREFERENCES_JSON_OBJECT, preferences);
}
ConfigurationAttribute configurationAttribute = new ConfigurationAttribute();
configurationAttribute.setName(getConfigurationAttribute().name());
configurationAttribute.setStringValue(currentPreferences.toString());
AdminClient.updateConfigurationAttribute(configurationAttribute);
}
public String getPreferenceId() {
return preferenceId;
}
public void setPreferenceId(String preferenceId) {
this.preferenceId = preferenceId;
}
public JSONObject getPrefs() {
return prefs;
}
public void setPrefs(JSONObject prefs) {
this.prefs = prefs;
}
public List<String> getAllPreferenceIds() {
return allPreferenceIds;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
| small fix for preference
| microservices/util/entity-utils/src/main/java/org/xcolab/entity/utils/WidgetPreference.java | small fix for preference | <ide><path>icroservices/util/entity-utils/src/main/java/org/xcolab/entity/utils/WidgetPreference.java
<ide>
<ide> public WidgetPreference(String id, String language) {
<ide>
<add> boolean idWasNull = false;
<ide> if(id==null){
<ide> id = DEFAULT_ID;
<add> idWasNull = true;
<ide> }
<del> if (language != null) {
<add> if (!idWasNull && language != null&&!id.contains("_")) {
<ide> id += UNDERSCOREDIVIDER + language;
<ide> }
<ide> |
|
Java | mit | 11a7779d9bad83eea38c96aae673be3a7ff46e4b | 0 | PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website,PATRIC3/patric3_website | /*******************************************************************************
* Copyright 2014 Virginia Polytechnic Institute and State University
*
* 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 edu.vt.vbi.patric.portlets;
import com.google.gson.Gson;
import edu.vt.vbi.patric.beans.Genome;
import edu.vt.vbi.patric.beans.GenomeFeature;
import edu.vt.vbi.patric.common.*;
import edu.vt.vbi.patric.dao.DBSummary;
import edu.vt.vbi.patric.dao.ResultType;
import edu.vt.vbi.patric.jbrowse.CRFeature;
import edu.vt.vbi.patric.jbrowse.CRResultSet;
import edu.vt.vbi.patric.jbrowse.CRTrack;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.theseed.servers.SAPserver;
import javax.portlet.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.*;
public class CompareRegionViewer extends GenericPortlet {
private static final Logger LOGGER = LoggerFactory.getLogger(CompareRegionViewer.class);
protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
new SiteHelper().setHtmlMetaElements(request, response, "Compare Region Viewer");
response.setContentType("text/html");
PortletRequestDispatcher prd;
prd = getPortletContext().getRequestDispatcher("/WEB-INF/CRViewer.jsp");
prd.include(request, response);
}
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
String mode = request.getParameter("mode");
switch (mode) {
case "getRefSeqs":
printRefSeqInfo(request, response);
break;
case "getTrackList":
printTrackList(request, response);
break;
case "getTrackInfo":
printTrackInfo(request, response);
break;
case "downloadInExcel":
exportInExcelFormat(request, response);
break;
default:
response.getWriter().write("wrong param");
break;
}
}
@SuppressWarnings("unchecked")
private void printRefSeqInfo(ResourceRequest request, ResourceResponse response) throws IOException {
String contextType = request.getParameter("cType");
String contextId = request.getParameter("cId");
String pinFeatureSeedId = request.getParameter("feature"); // pin feature
String windowSize = request.getParameter("window"); // window size
// if pin feature is not given, retrieve from the database based on na_feature_id
if (pinFeatureSeedId == null && (contextType != null && contextType.equals("feature") && contextId != null)) {
SolrInterface solr = new SolrInterface();
GenomeFeature feature = solr.getFeature(contextId);
pinFeatureSeedId = feature.getSeedId();
}
if (pinFeatureSeedId != null && !pinFeatureSeedId.equals("") && windowSize != null) {
JSONObject seq = new JSONObject();
seq.put("length", (Integer.parseInt(windowSize)));
seq.put("name", pinFeatureSeedId);
seq.put("seqDir", "");
seq.put("start", 1);
seq.put("end", (Integer.parseInt(windowSize)));
seq.put("seqChunkSize", 20000);
JSONArray json = new JSONArray();
json.add(seq);
response.setContentType("application/json");
json.writeJSONString(response.getWriter());
response.getWriter().close();
}
else {
response.getWriter().write("[]");
}
}
@SuppressWarnings("unchecked")
private void printTrackList(ResourceRequest request, ResourceResponse response) throws IOException {
String contextType = request.getParameter("cType");
String contextId = request.getParameter("cId");
String pinFeatureSeedId = request.getParameter("feature"); // pin feature
String windowSize = request.getParameter("window"); // window size
int _numRegion = Integer.parseInt(request.getParameter("regions")); // number of genomes to compare
int _numRegion_buffer = 10; // number of genomes to use as a buffer in case that PATRIC has no genome data,
// which was retrieved from API
String _key = "";
// DBSummary conn_summary = new DBSummary();
SolrInterface solr = new SolrInterface();
// if pin feature is not given, retrieve from the database based on na_feature_id
if (pinFeatureSeedId == null && (contextType != null && contextType.equals("feature") && contextId != null)) {
GenomeFeature feature = solr.getFeature(contextId);
pinFeatureSeedId = feature.getSeedId();
}
if (pinFeatureSeedId != null && !pinFeatureSeedId.equals("") && windowSize != null) {
CRResultSet crRS = null;
try {
SAPserver sapling = new SAPserver("http://servers.nmpdr.org/pseed/sapling/server.cgi");
crRS = new CRResultSet(pinFeatureSeedId,
sapling.compared_regions(pinFeatureSeedId, _numRegion + _numRegion_buffer, Integer.parseInt(windowSize) / 2));
long pk = (new Random()).nextLong();
_key = "" + pk;
Gson gson = new Gson();
SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, gson.toJson(crRS, CRResultSet.class));
SessionHandler.getInstance().set(SessionHandler.PREFIX + "_windowsize" + pk, windowSize);
}
catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
JSONObject trackList = new JSONObject();
JSONArray tracks = new JSONArray();
JSONObject trStyle = new JSONObject();
trStyle.put("className", "feature5");
trStyle.put("showLabels", false);
trStyle.put("label", "function( feature ) { return feature.get('seed_id'); }");
JSONObject trHooks = new JSONObject();
trHooks.put(
"modify",
"function(track, feature, div) { div.style.backgroundColor = ['red','#1F497D','#938953','#4F81BD','#9BBB59','#806482','#4BACC6','#F79646'][feature.get('phase')];}");
// query genome metadata
List<Genome> patricGenomes = null;
try {
SolrQuery query = new SolrQuery("genome_id:(" + StringUtils.join(crRS.getGenomeIds(), " OR ") + ")");
query.setFields("genome_id,genome_name,isolation_country,host_name,disease,collection_date,completion_date");
query.setRows(_numRegion + _numRegion_buffer);
QueryResponse qr = solr.getSolrServer(SolrCore.GENOME).query(query);
patricGenomes = qr.getBeans(Genome.class);
}
catch (MalformedURLException | SolrServerException e) {
LOGGER.error(e.getMessage(), e);
}
int count_genomes = 1;
if (crRS.getGenomeNames().size() > 0) {
for (Integer idx : crRS.getTrackMap().keySet()) {
if (count_genomes > _numRegion) {
break;
}
CRTrack crTrack = crRS.getTrackMap().get(idx);
Genome currentGenome = null;
for (Genome genome : patricGenomes) {
if (genome.getId().equals(crTrack.getGenomeID())) {
currentGenome = genome;
}
}
if (currentGenome != null) {
count_genomes++;
crRS.addToDefaultTracks(crTrack);
JSONObject tr = new JSONObject();
tr.put("style", trStyle);
tr.put("hooks", trHooks);
tr.put("type", "FeatureTrack");
tr.put("tooltip",
"<div style='line-height:1.7em'><b>{seed_id}</b> | {refseq_locus_tag} | {alt_locus_tag} | {gene}<br>{product}<br>{type}:{start}...{end} ({strand_str})<br> <i>Click for detail information</i></div>");
tr.put("urlTemplate", "/portal/portal/patric/CompareRegionViewer/CRWindow?action=b&cacheability=PAGE&mode=getTrackInfo&key="
+ _key + "&rowId=" + crTrack.getRowID() + "&format=.json");
tr.put("key", crTrack.getGenomeName());
tr.put("label", "CR" + idx);
tr.put("dataKey", _key);
JSONObject metaData = new JSONObject();
if (currentGenome.getIsolationCountry() != null) {
metaData.put("Isolation Country", currentGenome.getIsolationCountry());
}
if (currentGenome.getHostName() != null) {
metaData.put("Host Name", currentGenome.getHostName());
}
if (currentGenome.getDisease() != null) {
metaData.put("Disease", currentGenome.getDisease());
}
if (currentGenome.getCollectionDate() != null) {
metaData.put("Collection Date", currentGenome.getCollectionDate());
}
if (currentGenome.getCompletionDate() != null) {
metaData.put("Completion Date", currentGenome.getCompletionDate());
}
tr.put("metadata", metaData);
tracks.add(tr);
}
}
}
trackList.put("tracks", tracks);
JSONObject facetedTL = new JSONObject();
JSONArray dpColumns = new JSONArray();
dpColumns.addAll(Arrays.asList("key", "Isolation Country", "Host Name", "Disease", "Collection Date", "Completion Date"));
facetedTL.put("displayColumns", dpColumns);
facetedTL.put("type", "Faceted");
facetedTL.put("escapeHTMLInData", false);
trackList.put("trackSelector", facetedTL);
trackList.put("defaultTracks", crRS.getDefaultTracks());
response.setContentType("application/json");
trackList.writeJSONString(response.getWriter());
response.getWriter().close();
}
else {
response.getWriter().write("{}");
}
}
@SuppressWarnings("unchecked")
private void printTrackInfo(ResourceRequest request, ResourceResponse response) throws IOException {
String _rowID = request.getParameter("rowId");
String pk = request.getParameter("key");
Gson gson = new Gson();
String pin_strand = null;
CRTrack crTrack = null;
String pseed_ids = null;
try {
CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk), CRResultSet.class);
pin_strand = crRS.getPinStrand();
crTrack = crRS.getTrackMap().get(Integer.parseInt(_rowID));
pseed_ids = crTrack.getSeedIds();
}
catch (Exception e) {
LOGGER.error(e.getMessage());
LOGGER.debug("{}", SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
}
int _window_size = 0;
try {
_window_size = Integer.parseInt(SessionHandler.getInstance().get(SessionHandler.PREFIX + "_windowsize" + pk));
}
catch (Exception e) {
LOGGER.error(e.getMessage());
LOGGER.debug("pk:{}, {}", SessionHandler.getInstance().get(SessionHandler.PREFIX + "_windowsize" + pk));
}
int features_count = 0;
try {
crTrack.relocateFeatures(_window_size, pin_strand);
Collections.sort(crTrack.getFeatureList());
features_count = crTrack.getFeatureList().size();
}
catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
DBSummary conn_summary = new DBSummary();
Map<String, ResultType> pseedMap = conn_summary.getPSeedMapping("seed", pseed_ids);
// formatting
JSONArray nclist = new JSONArray();
CRFeature feature;
ResultType feature_patric;
for (int i = 0; i < features_count; i++) {
feature = crTrack.getFeatureList().get(i);
feature_patric = pseedMap.get(feature.getfeatureID());
if (feature_patric != null) {
JSONArray alist = new JSONArray();
alist.addAll(Arrays.asList(0,
feature.getStartPosition(),
feature.getStartString(),
feature.getEndPosition(),
(feature.getStrand().equals("+") ? 1 : -1),
feature.getStrand(),
feature_patric.get("feature_id"),
feature_patric.get("seed_id"),
feature_patric.get("refseq_locus_tag"),
feature_patric.get("alt_locus_tag"),
"PATRIC",
feature_patric.get("feature_type"),
feature_patric.get("product"),
feature_patric.get("gene"),
feature_patric.get("genome_name"),
feature_patric.get("accession"),
feature.getPhase()
));
nclist.add(alist);
}
}
// formatter.close();
JSONObject track = new JSONObject();
track.put("featureCount", features_count);
track.put("formatVersion", 1);
track.put("histograms", new JSONObject());
JSONObject intervals = new JSONObject();
JSONArray _clses = new JSONArray();
JSONObject _cls = new JSONObject();
_cls.put("attributes",
Arrays.asList("Start", "Start_str", "End", "Strand", "strand_str", "id", "seed_id", "refseq_locus_tag", "alt_locus_tag", "source",
"type", "product",
"gene", "genome_name", "accession", "phase"));
_cls.put("isArrayAttr", new JSONObject());
_clses.add(_cls);
intervals.put("classes", _clses);
intervals.put("lazyClass", 5);
intervals.put("minStart", 1);
intervals.put("maxEnd", 20000);
intervals.put("urlTemplate", "lf-{Chunk}.json");
intervals.put("nclist", nclist);
track.put("intervals", intervals);
response.setContentType("application/json");
track.writeJSONString(response.getWriter());
response.getWriter().close();
}
private void exportInExcelFormat(ResourceRequest request, ResourceResponse response) throws IOException {
String pk = request.getParameter("key");
Gson gson = new Gson();
CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk), CRResultSet.class);
CRTrack crTrack;
CRFeature crFeature;
String genome_name;
List<String> _tbl_header = new ArrayList<>();
List<String> _tbl_field = new ArrayList<>();
List<ResultType> _tbl_source = new ArrayList<>();
_tbl_header.addAll(Arrays.asList("Genome Name", "Feature", "Start", "End", "Strand", "FigFam", "Product", "Group"));
_tbl_field.addAll(Arrays.asList("genome_name", "feature_id", "start", "end", "strand", "figfam_id", "product", "group_id"));
if (crRS != null && crRS.getGenomeNames().size() > 0) {
for (Integer idx : crRS.getTrackMap().keySet()) {
crTrack = crRS.getTrackMap().get(idx);
genome_name = crTrack.getGenomeName();
for (Object aCrTrack : crTrack.getFeatureList()) {
crFeature = (CRFeature) aCrTrack;
ResultType f = new ResultType();
f.put("genome_name", genome_name);
f.put("feature_id", crFeature.getfeatureID());
f.put("start", crFeature.getStartPosition());
f.put("end", crFeature.getEndPosition());
f.put("strand", crFeature.getStrand());
f.put("figfam_id", crFeature.getFigfam());
f.put("product", crFeature.getProduct());
f.put("group_id", crFeature.getGrpNum());
_tbl_source.add(f);
}
}
}
// print out to xlsx file
response.setContentType("application/octetstream");
response.setProperty("Content-Disposition", "attachment; filename=\"CompareRegionView.xlsx\"");
OutputStream outs = response.getPortletOutputStream();
ExcelHelper excel = new ExcelHelper("xssf", _tbl_header, _tbl_field, _tbl_source);
excel.buildSpreadsheet();
excel.writeSpreadsheettoBrowser(outs);
}
}
| portal/patric-jbrowse/src/edu/vt/vbi/patric/portlets/CompareRegionViewer.java | /*******************************************************************************
* Copyright 2014 Virginia Polytechnic Institute and State University
*
* 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 edu.vt.vbi.patric.portlets;
import com.google.gson.Gson;
import edu.vt.vbi.patric.beans.Genome;
import edu.vt.vbi.patric.beans.GenomeFeature;
import edu.vt.vbi.patric.common.*;
import edu.vt.vbi.patric.dao.DBSummary;
import edu.vt.vbi.patric.dao.ResultType;
import edu.vt.vbi.patric.jbrowse.CRFeature;
import edu.vt.vbi.patric.jbrowse.CRResultSet;
import edu.vt.vbi.patric.jbrowse.CRTrack;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.theseed.servers.SAPserver;
import javax.portlet.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.*;
public class CompareRegionViewer extends GenericPortlet {
private static final Logger LOGGER = LoggerFactory.getLogger(CompareRegionViewer.class);
protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
new SiteHelper().setHtmlMetaElements(request, response, "Compare Region Viewer");
response.setContentType("text/html");
PortletRequestDispatcher prd;
prd = getPortletContext().getRequestDispatcher("/WEB-INF/CRViewer.jsp");
prd.include(request, response);
}
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
String mode = request.getParameter("mode");
switch (mode) {
case "getRefSeqs":
printRefSeqInfo(request, response);
break;
case "getTrackList":
printTrackList(request, response);
break;
case "getTrackInfo":
printTrackInfo(request, response);
break;
case "downloadInExcel":
exportInExcelFormat(request, response);
break;
default:
response.getWriter().write("wrong param");
break;
}
}
@SuppressWarnings("unchecked")
private void printRefSeqInfo(ResourceRequest request, ResourceResponse response) throws IOException {
String contextType = request.getParameter("cType");
String contextId = request.getParameter("cId");
String pinFeatureSeedId = request.getParameter("feature"); // pin feature
String windowSize = request.getParameter("window"); // window size
// if pin feature is not given, retrieve from the database based on na_feature_id
if (pinFeatureSeedId == null && (contextType != null && contextType.equals("feature") && contextId != null)) {
SolrInterface solr = new SolrInterface();
GenomeFeature feature = solr.getFeature(contextId);
pinFeatureSeedId = feature.getSeedId();
}
if (pinFeatureSeedId != null && !pinFeatureSeedId.equals("") && windowSize != null) {
JSONObject seq = new JSONObject();
seq.put("length", (Integer.parseInt(windowSize)));
seq.put("name", pinFeatureSeedId);
seq.put("seqDir", "");
seq.put("start", 1);
seq.put("end", (Integer.parseInt(windowSize)));
seq.put("seqChunkSize", 20000);
JSONArray json = new JSONArray();
json.add(seq);
response.setContentType("application/json");
json.writeJSONString(response.getWriter());
response.getWriter().close();
}
else {
response.getWriter().write("[]");
}
}
@SuppressWarnings("unchecked")
private void printTrackList(ResourceRequest request, ResourceResponse response) throws IOException {
String contextType = request.getParameter("cType");
String contextId = request.getParameter("cId");
String pinFeatureSeedId = request.getParameter("feature"); // pin feature
String windowSize = request.getParameter("window"); // window size
int _numRegion = Integer.parseInt(request.getParameter("regions")); // number of genomes to compare
int _numRegion_buffer = 10; // number of genomes to use as a buffer in case that PATRIC has no genome data,
// which was retrieved from API
String _key = "";
// DBSummary conn_summary = new DBSummary();
SolrInterface solr = new SolrInterface();
// if pin feature is not given, retrieve from the database based on na_feature_id
if (pinFeatureSeedId == null && (contextType != null && contextType.equals("feature") && contextId != null)) {
GenomeFeature feature = solr.getFeature(contextId);
pinFeatureSeedId = feature.getSeedId();
}
if (pinFeatureSeedId != null && !pinFeatureSeedId.equals("") && windowSize != null) {
CRResultSet crRS = null;
try {
SAPserver sapling = new SAPserver("http://servers.nmpdr.org/pseed/sapling/server.cgi");
crRS = new CRResultSet(pinFeatureSeedId,
sapling.compared_regions(pinFeatureSeedId, _numRegion + _numRegion_buffer, Integer.parseInt(windowSize) / 2));
long pk = (new Random()).nextLong();
_key = "" + pk;
Gson gson = new Gson();
SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, gson.toJson(crRS, CRResultSet.class));
SessionHandler.getInstance().set(SessionHandler.PREFIX + pk + "_windowsize", windowSize);
}
catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
JSONObject trackList = new JSONObject();
JSONArray tracks = new JSONArray();
JSONObject trStyle = new JSONObject();
trStyle.put("className", "feature5");
trStyle.put("showLabels", false);
trStyle.put("label", "function( feature ) { return feature.get('seed_id'); }");
JSONObject trHooks = new JSONObject();
trHooks.put(
"modify",
"function(track, feature, div) { div.style.backgroundColor = ['red','#1F497D','#938953','#4F81BD','#9BBB59','#806482','#4BACC6','#F79646'][feature.get('phase')];}");
// query genome metadata
List<Genome> patricGenomes = null;
try {
SolrQuery query = new SolrQuery("genome_id:(" + StringUtils.join(crRS.getGenomeIds(), " OR ") + ")");
query.setFields("genome_id,genome_name,isolation_country,host_name,disease,collection_date,completion_date");
query.setRows(_numRegion + _numRegion_buffer);
QueryResponse qr = solr.getSolrServer(SolrCore.GENOME).query(query);
patricGenomes = qr.getBeans(Genome.class);
}
catch (MalformedURLException | SolrServerException e) {
LOGGER.error(e.getMessage(), e);
}
int count_genomes = 1;
if (crRS.getGenomeNames().size() > 0) {
for (Integer idx : crRS.getTrackMap().keySet()) {
if (count_genomes > _numRegion) {
break;
}
CRTrack crTrack = crRS.getTrackMap().get(idx);
Genome currentGenome = null;
for (Genome genome : patricGenomes) {
if (genome.getId().equals(crTrack.getGenomeID())) {
currentGenome = genome;
}
}
if (currentGenome != null) {
count_genomes++;
crRS.addToDefaultTracks(crTrack);
JSONObject tr = new JSONObject();
tr.put("style", trStyle);
tr.put("hooks", trHooks);
tr.put("type", "FeatureTrack");
tr.put("tooltip",
"<div style='line-height:1.7em'><b>{seed_id}</b> | {refseq_locus_tag} | {alt_locus_tag} | {gene}<br>{product}<br>{type}:{start}...{end} ({strand_str})<br> <i>Click for detail information</i></div>");
tr.put("urlTemplate", "/portal/portal/patric/CompareRegionViewer/CRWindow?action=b&cacheability=PAGE&mode=getTrackInfo&key="
+ _key + "&rowId=" + crTrack.getRowID() + "&format=.json");
tr.put("key", crTrack.getGenomeName());
tr.put("label", "CR" + idx);
tr.put("dataKey", _key);
JSONObject metaData = new JSONObject();
if (currentGenome.getIsolationCountry() != null) {
metaData.put("Isolation Country", currentGenome.getIsolationCountry());
}
if (currentGenome.getHostName() != null) {
metaData.put("Host Name", currentGenome.getHostName());
}
if (currentGenome.getDisease() != null) {
metaData.put("Disease", currentGenome.getDisease());
}
if (currentGenome.getCollectionDate() != null) {
metaData.put("Collection Date", currentGenome.getCollectionDate());
}
if (currentGenome.getCompletionDate() != null) {
metaData.put("Completion Date", currentGenome.getCompletionDate());
}
tr.put("metadata", metaData);
tracks.add(tr);
}
}
}
trackList.put("tracks", tracks);
JSONObject facetedTL = new JSONObject();
JSONArray dpColumns = new JSONArray();
dpColumns.addAll(Arrays.asList("key", "Isolation Country", "Host Name", "Disease", "Collection Date", "Completion Date"));
facetedTL.put("displayColumns", dpColumns);
facetedTL.put("type", "Faceted");
facetedTL.put("escapeHTMLInData", false);
trackList.put("trackSelector", facetedTL);
trackList.put("defaultTracks", crRS.getDefaultTracks());
response.setContentType("application/json");
trackList.writeJSONString(response.getWriter());
response.getWriter().close();
}
else {
response.getWriter().write("{}");
}
}
@SuppressWarnings("unchecked")
private void printTrackInfo(ResourceRequest request, ResourceResponse response) throws IOException {
String _rowID = request.getParameter("rowId");
String pk = request.getParameter("key");
Gson gson = new Gson();
CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk), CRResultSet.class);
LOGGER.trace("pk:{}, windowsize:{}", pk, SessionHandler.getInstance().get(SessionHandler.PREFIX + pk + "_windowsize"));
int _window_size = Integer.parseInt(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk + "_windowsize"));
String pin_strand = crRS.getPinStrand();
CRTrack crTrack = crRS.getTrackMap().get(Integer.parseInt(_rowID));
String pseed_ids = crTrack.getSeedIds();
int features_count = 0;
try {
crTrack.relocateFeatures(_window_size, pin_strand);
Collections.sort(crTrack.getFeatureList());
features_count = crTrack.getFeatureList().size();
}
catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
DBSummary conn_summary = new DBSummary();
Map<String, ResultType> pseedMap = conn_summary.getPSeedMapping("seed", pseed_ids);
// formatting
JSONArray nclist = new JSONArray();
CRFeature feature;
ResultType feature_patric;
for (int i = 0; i < features_count; i++) {
feature = crTrack.getFeatureList().get(i);
feature_patric = pseedMap.get(feature.getfeatureID());
if (feature_patric != null) {
JSONArray alist = new JSONArray();
alist.addAll(Arrays.asList(0,
feature.getStartPosition(),
feature.getStartString(),
feature.getEndPosition(),
(feature.getStrand().equals("+") ? 1 : -1),
feature.getStrand(),
feature_patric.get("feature_id"),
feature_patric.get("seed_id"),
feature_patric.get("refseq_locus_tag"),
feature_patric.get("alt_locus_tag"),
"PATRIC",
feature_patric.get("feature_type"),
feature_patric.get("product"),
feature_patric.get("gene"),
feature_patric.get("genome_name"),
feature_patric.get("accession"),
feature.getPhase()
));
nclist.add(alist);
}
}
// formatter.close();
JSONObject track = new JSONObject();
track.put("featureCount", features_count);
track.put("formatVersion", 1);
track.put("histograms", new JSONObject());
JSONObject intervals = new JSONObject();
JSONArray _clses = new JSONArray();
JSONObject _cls = new JSONObject();
_cls.put("attributes",
Arrays.asList("Start", "Start_str", "End", "Strand", "strand_str", "id", "seed_id", "refseq_locus_tag", "alt_locus_tag", "source",
"type", "product",
"gene", "genome_name", "accession", "phase"));
_cls.put("isArrayAttr", new JSONObject());
_clses.add(_cls);
intervals.put("classes", _clses);
intervals.put("lazyClass", 5);
intervals.put("minStart", 1);
intervals.put("maxEnd", 20000);
intervals.put("urlTemplate", "lf-{Chunk}.json");
intervals.put("nclist", nclist);
track.put("intervals", intervals);
response.setContentType("application/json");
track.writeJSONString(response.getWriter());
response.getWriter().close();
}
private void exportInExcelFormat(ResourceRequest request, ResourceResponse response) throws IOException {
String pk = request.getParameter("key");
Gson gson = new Gson();
CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk), CRResultSet.class);
CRTrack crTrack;
CRFeature crFeature;
String genome_name;
List<String> _tbl_header = new ArrayList<>();
List<String> _tbl_field = new ArrayList<>();
List<ResultType> _tbl_source = new ArrayList<>();
_tbl_header.addAll(Arrays.asList("Genome Name", "Feature", "Start", "End", "Strand", "FigFam", "Product", "Group"));
_tbl_field.addAll(Arrays.asList("genome_name", "feature_id", "start", "end", "strand", "figfam_id", "product", "group_id"));
if (crRS != null && crRS.getGenomeNames().size() > 0) {
for (Integer idx : crRS.getTrackMap().keySet()) {
crTrack = crRS.getTrackMap().get(idx);
genome_name = crTrack.getGenomeName();
for (Object aCrTrack : crTrack.getFeatureList()) {
crFeature = (CRFeature) aCrTrack;
ResultType f = new ResultType();
f.put("genome_name", genome_name);
f.put("feature_id", crFeature.getfeatureID());
f.put("start", crFeature.getStartPosition());
f.put("end", crFeature.getEndPosition());
f.put("strand", crFeature.getStrand());
f.put("figfam_id", crFeature.getFigfam());
f.put("product", crFeature.getProduct());
f.put("group_id", crFeature.getGrpNum());
_tbl_source.add(f);
}
}
}
// print out to xlsx file
response.setContentType("application/octetstream");
response.setProperty("Content-Disposition", "attachment; filename=\"CompareRegionView.xlsx\"");
OutputStream outs = response.getPortletOutputStream();
ExcelHelper excel = new ExcelHelper("xssf", _tbl_header, _tbl_field, _tbl_source);
excel.buildSpreadsheet();
excel.writeSpreadsheettoBrowser(outs);
}
}
| code cleanup
| portal/patric-jbrowse/src/edu/vt/vbi/patric/portlets/CompareRegionViewer.java | code cleanup | <ide><path>ortal/patric-jbrowse/src/edu/vt/vbi/patric/portlets/CompareRegionViewer.java
<ide>
<ide> Gson gson = new Gson();
<ide> SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, gson.toJson(crRS, CRResultSet.class));
<del> SessionHandler.getInstance().set(SessionHandler.PREFIX + pk + "_windowsize", windowSize);
<add> SessionHandler.getInstance().set(SessionHandler.PREFIX + "_windowsize" + pk, windowSize);
<ide>
<ide> }
<ide> catch (Exception ex) {
<ide> String pk = request.getParameter("key");
<ide>
<ide> Gson gson = new Gson();
<del> CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk), CRResultSet.class);
<del>
<del> LOGGER.trace("pk:{}, windowsize:{}", pk, SessionHandler.getInstance().get(SessionHandler.PREFIX + pk + "_windowsize"));
<del> int _window_size = Integer.parseInt(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk + "_windowsize"));
<del>
<del> String pin_strand = crRS.getPinStrand();
<del> CRTrack crTrack = crRS.getTrackMap().get(Integer.parseInt(_rowID));
<del> String pseed_ids = crTrack.getSeedIds();
<add> String pin_strand = null;
<add> CRTrack crTrack = null;
<add> String pseed_ids = null;
<add> try {
<add> CRResultSet crRS = gson.fromJson(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk), CRResultSet.class);
<add> pin_strand = crRS.getPinStrand();
<add> crTrack = crRS.getTrackMap().get(Integer.parseInt(_rowID));
<add> pseed_ids = crTrack.getSeedIds();
<add> }
<add> catch (Exception e) {
<add> LOGGER.error(e.getMessage());
<add> LOGGER.debug("{}", SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
<add> }
<add>
<add> int _window_size = 0;
<add> try {
<add> _window_size = Integer.parseInt(SessionHandler.getInstance().get(SessionHandler.PREFIX + "_windowsize" + pk));
<add> }
<add> catch (Exception e) {
<add> LOGGER.error(e.getMessage());
<add> LOGGER.debug("pk:{}, {}", SessionHandler.getInstance().get(SessionHandler.PREFIX + "_windowsize" + pk));
<add> }
<ide>
<ide> int features_count = 0;
<ide> try { |
|
Java | apache-2.0 | b798433a4e45efbef65ca19aedc416a06667a11a | 0 | Donnerbart/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,dbrimley/hazelcast,tufangorel/hazelcast,tkountis/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,mesutcelik/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast,emre-aydin/hazelcast,Donnerbart/hazelcast,juanavelez/hazelcast,tombujok/hazelcast,mdogan/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,lmjacksoniii/hazelcast,mdogan/hazelcast,emrahkocaman/hazelcast,lmjacksoniii/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,emrahkocaman/hazelcast | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.mapreduce;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.XmlClientConfigBuilder;
import com.hazelcast.config.Config;
import com.hazelcast.config.XmlConfigBuilder;
import com.hazelcast.test.HazelcastTestSupport;
public abstract class AbstractClientMapReduceJobTest extends HazelcastTestSupport {
protected ClientConfig buildClientConfig() {
ClientConfig config = new XmlClientConfigBuilder().build();
return config;
}
protected Config buildConfig() {
Config config = new XmlConfigBuilder().build();
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1");
return config;
}
}
| hazelcast-client/src/test/java/com/hazelcast/client/mapreduce/AbstractClientMapReduceJobTest.java | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.mapreduce;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.XmlClientConfigBuilder;
import com.hazelcast.config.Config;
import com.hazelcast.config.XmlConfigBuilder;
import com.hazelcast.test.HazelcastTestSupport;
public abstract class AbstractClientMapReduceJobTest extends HazelcastTestSupport {
protected ClientConfig buildClientConfig() {
ClientConfig config = new XmlClientConfigBuilder().build();
return config;
}
protected Config buildConfig() {
Config config = new XmlConfigBuilder().build();
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1");
return config;
}
}
| Fixed issue in ClientMapReduceTest: both multicast and tcp were enabled
| hazelcast-client/src/test/java/com/hazelcast/client/mapreduce/AbstractClientMapReduceJobTest.java | Fixed issue in ClientMapReduceTest: both multicast and tcp were enabled | <ide><path>azelcast-client/src/test/java/com/hazelcast/client/mapreduce/AbstractClientMapReduceJobTest.java
<ide>
<ide> protected Config buildConfig() {
<ide> Config config = new XmlConfigBuilder().build();
<add> config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
<ide> config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1");
<ide> return config;
<ide> } |
|
Java | apache-2.0 | 33e3f566079e225d819154ecc3dca26b950cd167 | 0 | kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.graphics.color;
import java.util.Arrays;
import org.apache.pdfbox.cos.COSName;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Allows colors to be specified according to the subtractive CMYK (cyan, magenta, yellow, black)
* model typical of printers and other paper-based output devices.
*
* @author John Hewson
* @author Ben Litchfield
*/
public class PDDeviceCMYK extends PDDeviceColorSpace
{
/** The single instance of this class. */
public static PDDeviceCMYK INSTANCE;
static
{
INSTANCE = new PDDeviceCMYK();
}
private final PDColor initialColor = new PDColor(new float[] { 0, 0, 0, 1 }, this);
private ICC_ColorSpace awtColorSpace;
private volatile boolean initDone = false;
private boolean usePureJavaCMYKConversion = false;
protected PDDeviceCMYK()
{
}
/**
* Lazy load the ICC profile, because it's slow.
*/
protected void init() throws IOException
{
// no need to synchronize this check as it is atomic
if (initDone)
{
return;
}
synchronized (this)
{
// we might have been waiting for another thread, so check again
if (initDone)
{
return;
}
// loads the ICC color profile for CMYK
ICC_Profile iccProfile = getICCProfile();
if (iccProfile == null)
{
throw new IOException("Default CMYK color profile could not be loaded");
}
awtColorSpace = new ICC_ColorSpace(iccProfile);
// there is a JVM bug which results in a CMMException which appears to be a race
// condition caused by lazy initialization of the color transform, so we perform
// an initial color conversion while we're still in a static context, see PDFBOX-2184
awtColorSpace.toRGB(new float[] { 0, 0, 0, 0 });
usePureJavaCMYKConversion = System
.getProperty("org.apache.pdfbox.rendering.UsePureJavaCMYKConversion") != null;
// Assignment to volatile must be the LAST statement in this block!
initDone = true;
}
}
protected ICC_Profile getICCProfile() throws IOException
{
// Adobe Acrobat uses "U.S. Web Coated (SWOP) v2" as the default
// CMYK profile, however it is not available under an open license.
// Instead, the "ISO Coated v2 300% (basICColor)" is used, which
// is an open alternative to the "ISO Coated v2 300% (ECI)" profile.
String resourceName = "/org/apache/pdfbox/resources/icc/ISOcoated_v2_300_bas.icc";
InputStream resourceAsStream = PDDeviceCMYK.class.getResourceAsStream(resourceName);
if (resourceAsStream == null)
{
throw new IOException("resource '" + resourceName + "' not found");
}
try (InputStream is = new BufferedInputStream(resourceAsStream))
{
return ICC_Profile.getInstance(is);
}
}
@Override
public String getName()
{
return COSName.DEVICECMYK.getName();
}
@Override
public int getNumberOfComponents()
{
return 4;
}
@Override
public float[] getDefaultDecode(int bitsPerComponent)
{
return new float[] { 0, 1, 0, 1, 0, 1, 0, 1 };
}
@Override
public PDColor getInitialColor()
{
return initialColor;
}
@Override
public float[] toRGB(float[] value) throws IOException
{
init();
return awtColorSpace.toRGB(value);
}
@Override
public BufferedImage toRawImage(WritableRaster raster) throws IOException
{
// Device CMYK is not specified, as its the colors of whatever device you use.
// The user should fallback to the RGB image
return null;
}
@Override
public BufferedImage toRGBImage(WritableRaster raster) throws IOException
{
init();
return toRGBImageAWT(raster, awtColorSpace);
}
@Override
protected BufferedImage toRGBImageAWT(WritableRaster raster, ColorSpace colorSpace)
{
if (usePureJavaCMYKConversion)
{
BufferedImage dest = new BufferedImage(raster.getWidth(), raster.getHeight(),
BufferedImage.TYPE_INT_RGB);
ColorSpace destCS = dest.getColorModel().getColorSpace();
WritableRaster destRaster = dest.getRaster();
float[] srcValues = new float[4];
float[] lastValues = new float[] { -1.0f, -1.0f, -1.0f, -1.0f };
float[] destValues = new float[3];
int startX = raster.getMinX();
int startY = raster.getMinY();
int endX = raster.getWidth() + startX;
int endY = raster.getHeight() + startY;
for (int x = startX; x < endX; x++)
{
for (int y = startY; y < endY; y++)
{
raster.getPixel(x, y, srcValues);
// check if the last value can be reused
if (!Arrays.equals(lastValues, srcValues))
{
lastValues[0] = srcValues[0];
srcValues[0] = srcValues[0] / 255f;
lastValues[1] = srcValues[1];
srcValues[1] = srcValues[1] / 255f;
lastValues[2] = srcValues[2];
srcValues[2] = srcValues[2] / 255f;
lastValues[3] = srcValues[3];
srcValues[3] = srcValues[3] / 255f;
// use CIEXYZ as intermediate format to optimize the color conversion
destValues = destCS.fromCIEXYZ(colorSpace.toCIEXYZ(srcValues));
for (int k = 0; k < destValues.length; k++)
{
destValues[k] = destValues[k] * 255f;
}
}
destRaster.setPixel(x, y, destValues);
}
}
return dest;
}
else
{
return super.toRGBImageAWT(raster, colorSpace);
}
}
}
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/color/PDDeviceCMYK.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.graphics.color;
import java.util.Arrays;
import org.apache.pdfbox.cos.COSName;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Allows colors to be specified according to the subtractive CMYK (cyan, magenta, yellow, black)
* model typical of printers and other paper-based output devices.
*
* @author John Hewson
* @author Ben Litchfield
*/
public class PDDeviceCMYK extends PDDeviceColorSpace
{
/** The single instance of this class. */
public static PDDeviceCMYK INSTANCE;
static
{
INSTANCE = new PDDeviceCMYK();
}
private final PDColor initialColor = new PDColor(new float[] { 0, 0, 0, 1 }, this);
private ICC_ColorSpace awtColorSpace;
private volatile boolean initDone = false;
private boolean usePureJavaCMYKConversion = false;
protected PDDeviceCMYK()
{
}
/**
* Lazy load the ICC profile, because it's slow.
*/
protected void init() throws IOException
{
// no need to synchronize this check as it is atomic
if (initDone)
{
return;
}
synchronized (this)
{
// we might have been waiting for another thread, so check again
if (initDone)
{
return;
}
// loads the ICC color profile for CMYK
ICC_Profile iccProfile = getICCProfile();
if (iccProfile == null)
{
throw new IOException("Default CMYK color profile could not be loaded");
}
awtColorSpace = new ICC_ColorSpace(iccProfile);
// there is a JVM bug which results in a CMMException which appears to be a race
// condition caused by lazy initialization of the color transform, so we perform
// an initial color conversion while we're still in a static context, see PDFBOX-2184
awtColorSpace.toRGB(new float[] { 0, 0, 0, 0 });
usePureJavaCMYKConversion = System
.getProperty("org.apache.pdfbox.rendering.UsePureJavaCMYKConversion") != null;
// Assignment to volatile must be the LAST statement in this block!
initDone = true;
}
}
protected ICC_Profile getICCProfile() throws IOException
{
// Adobe Acrobat uses "U.S. Web Coated (SWOP) v2" as the default
// CMYK profile, however it is not available under an open license.
// Instead, the "ISO Coated v2 300% (basICColor)" is used, which
// is an open alternative to the "ISO Coated v2 300% (ECI)" profile.
String resourceName = "/org/apache/pdfbox/resources/icc/ISOcoated_v2_300_bas.icc";
InputStream resourceAsStream = PDDeviceCMYK.class.getResourceAsStream(resourceName);
if (resourceAsStream == null)
{
throw new IOException("resource '" + resourceName + "' not found");
}
try (InputStream is = new BufferedInputStream(resourceAsStream))
{
return ICC_Profile.getInstance(is);
}
}
@Override
public String getName()
{
return COSName.DEVICECMYK.getName();
}
@Override
public int getNumberOfComponents()
{
return 4;
}
@Override
public float[] getDefaultDecode(int bitsPerComponent)
{
return new float[] { 0, 1, 0, 1, 0, 1, 0, 1 };
}
@Override
public PDColor getInitialColor()
{
return initialColor;
}
@Override
public float[] toRGB(float[] value) throws IOException
{
init();
return awtColorSpace.toRGB(value);
}
@Override
public BufferedImage toRawImage(WritableRaster raster) throws IOException
{
// Device CMYK is not specified, as its the colors of whatever device you use.
// The user should fallback to the RGB image
return null;
}
@Override
public BufferedImage toRGBImage(WritableRaster raster) throws IOException
{
init();
return toRGBImageAWT(raster, awtColorSpace);
}
@Override
protected BufferedImage toRGBImageAWT(WritableRaster raster, ColorSpace colorSpace)
{
if (usePureJavaCMYKConversion)
{
BufferedImage dest = new BufferedImage(raster.getWidth(), raster.getHeight(),
BufferedImage.TYPE_INT_RGB);
ColorSpace destCS = dest.getColorModel().getColorSpace();
WritableRaster destRaster = dest.getRaster();
float[] srcValues = new float[4];
float[] lastValues = new float[] { -1.0f, -1.0f, -1.0f, -1.0f };
float[] destValues = new float[3];
int width = raster.getWidth();
int startX = raster.getMinX();
int height = raster.getHeight();
int startY = raster.getMinY();
for (int x = startX; x < width + startX; x++)
{
for (int y = startY; y < height + startY; y++)
{
raster.getPixel(x, y, srcValues);
// check if the last value can be reused
if (!Arrays.equals(lastValues, srcValues))
{
for (int k = 0; k < 4; k++)
{
lastValues[k] = srcValues[k];
srcValues[k] = srcValues[k] / 255f;
}
// use CIEXYZ as intermediate format to optimize the color conversion
destValues = destCS.fromCIEXYZ(colorSpace.toCIEXYZ(srcValues));
for (int k = 0; k < destValues.length; k++)
{
destValues[k] = destValues[k] * 255f;
}
}
destRaster.setPixel(x, y, destValues);
}
}
return dest;
}
else
{
return super.toRGBImageAWT(raster, colorSpace);
}
}
}
| PDFBOX-4892: performance improvement, as suggested by valerybokov
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1888371 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/color/PDDeviceCMYK.java | PDFBOX-4892: performance improvement, as suggested by valerybokov | <ide><path>dfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/color/PDDeviceCMYK.java
<ide> float[] srcValues = new float[4];
<ide> float[] lastValues = new float[] { -1.0f, -1.0f, -1.0f, -1.0f };
<ide> float[] destValues = new float[3];
<del> int width = raster.getWidth();
<ide> int startX = raster.getMinX();
<del> int height = raster.getHeight();
<ide> int startY = raster.getMinY();
<del> for (int x = startX; x < width + startX; x++)
<add> int endX = raster.getWidth() + startX;
<add> int endY = raster.getHeight() + startY;
<add> for (int x = startX; x < endX; x++)
<ide> {
<del> for (int y = startY; y < height + startY; y++)
<add> for (int y = startY; y < endY; y++)
<ide> {
<ide> raster.getPixel(x, y, srcValues);
<ide> // check if the last value can be reused
<ide> if (!Arrays.equals(lastValues, srcValues))
<ide> {
<del> for (int k = 0; k < 4; k++)
<del> {
<del> lastValues[k] = srcValues[k];
<del> srcValues[k] = srcValues[k] / 255f;
<del> }
<add> lastValues[0] = srcValues[0];
<add> srcValues[0] = srcValues[0] / 255f;
<add>
<add> lastValues[1] = srcValues[1];
<add> srcValues[1] = srcValues[1] / 255f;
<add>
<add> lastValues[2] = srcValues[2];
<add> srcValues[2] = srcValues[2] / 255f;
<add>
<add> lastValues[3] = srcValues[3];
<add> srcValues[3] = srcValues[3] / 255f;
<add>
<ide> // use CIEXYZ as intermediate format to optimize the color conversion
<ide> destValues = destCS.fromCIEXYZ(colorSpace.toCIEXYZ(srcValues));
<ide> for (int k = 0; k < destValues.length; k++) |
|
Java | mit | 9c6bf30b04f59ce62f7d6185db0c4f77b3e6b634 | 0 | MSurai/OCR-Sudoku-Solver,MSurai/OCR-Sudoku-Solver | public class Matrix {
/* -------------------
CLASS VARIABLES
---------------------*/
private double[][] vals; // values of matrix
private int m, n; // row and column dimensions
/* -------------------
CONSTRUCTORS
---------------------*/
// empty m x n matrix
public Matrix (int m, int n) {
this(m, n, 0);
}
// m x n matrix filled with scalar s
public Matrix (int m, int n, double s) {
this.m = n;
this.n = n;
this.vals = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
this.vals[i][j] = s;
}
}
}
// matrix created with given array
public Matrix (double[][] vals) {
this.m = vals.length;
this.n = vals[0].length;
this.vals = vals;
}
// matrix created from matrix, deep copy
public Matrix (Matrix matrix) {
double[][] tmp = new double[matrix.getRowDimension()][matrix.getColumnDimension()];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[i].length; j++) {
tmp[i][j] = matrix.getComponent(i, j);
}
}
this.m = tmp.length;
this.n = tmp[0].length;
this.vals = tmp;
}
/* -------------------
METHODS
---------------------*/
// GETTERS
public int getRowDimension () {
return this.m;
}
public int getColumnDimension () {
return this.n;
}
public double[][] getVals () {
return this.vals;
}
public double[] getColumnPackedArray () {
double[] tmp = new double[m*n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[i + j * m] = this.vals[i][j];
}
}
return tmp;
}
public double[] getRowPackedArray () {
double[] tmp = new double[m*n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[i * n + j] = this.vals[i][j];
}
}
return tmp;
}
public double getComponent (int i, int j) {
return this.vals[i][j];
}
public Matrix copy () {
return new Matrix(this);
}
public Matrix deepCopy () {
double[][] tmp = new double[this.m][this.n];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[i].length; j++) {
tmp[i][j] = this.vals[i][j];
}
}
return new Matrix(tmp);
}
public Matrix getSubMatrix (int x1, int x2, int y1, int y2) {
double[][] tmp = new double[y2-y1+1][x2-x1+1];
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
tmp[y - y1][x - x1] = this.vals[y][x];
}
}
return new Matrix(tmp);
}
public double[] getRowwiseMax () {
double[] tmp = new double[this.m];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = this.vals[i][0];
for (int j = 0; j < this.n; j++) {
tmp[i] = tmp[i] < this.vals[i][j] ? this.vals[i][j] : tmp[i];
}
}
return tmp;
}
public double[] getColwiseMax () {
double[] tmp = new double[this.n];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = this.vals[0][i];
for (int j = 0; j < this.m; j++) {
tmp[i] = tmp[i] < this.vals[j][i] ? this.vals[j][i] : tmp[i];
}
}
return tmp;
}
public double getMax () {
double tmp = this.vals[0][0];
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
tmp = tmp < this.vals[i][j] ? this.vals[i][j] : tmp;
}
}
return tmp;
}
// SETTERS
public void setComponent (int i, int j, double s) {
this.vals[i][j] = s;
}
public void setVals (double[][] vals) {
this.m = vals.length;
this.n = vals[0].length;
this.vals = new double[this.m][this.n];
this.vals = vals;
}
// OPERATIONS
public void unroll () {
double[][] tmp = new double[this.m * this.n][1];
int counter = 0;
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
tmp[counter][0] = this.vals[i][j];
counter++;
}
}
setVals(tmp);
}
public Matrix unrollNew () {
Matrix tmp = this.deepCopy();
tmp.unroll();
return tmp;
}
public void reshape (int m, int n) {
double[][] tmp = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[i][j] = this.vals[i + j * m][0];
}
}
setVals(tmp);
}
public Matrix reshapeNew (int m, int n) {
Matrix tmp = this.deepCopy();
tmp.reshape(m, n);
return tmp;
}
public void transpose () {
double [][] tmp = new double[this.n][this.m];
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
tmp[j][i] = this.vals[i][j];
}
}
setVals(tmp);
}
public Matrix transposeNew () {
Matrix tmp = this.copy();
tmp.transpose();
return tmp;
}
public void add (double s) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] += s;
}
}
}
public Matrix addNew (double s) {
Matrix tmp = this.deepCopy();
tmp.add(s);
return tmp;
}
public void add (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] += B.getComponent(i, j);
}
}
}
public Matrix addNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.add(B);
return tmp;
}
public void subtract (double s) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] -= s;
}
}
}
public Matrix subtractNew (double s) {
Matrix tmp = this.deepCopy();
tmp.subtract(s);
return tmp;
}
public void subtract (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] -= B.getComponent(i, j);
}
}
}
public Matrix subtractNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.subtract(B);
return tmp;
}
public void multiply (double s) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] *= s;
}
}
}
public Matrix multiplyNew (double s) {
Matrix tmp = this.deepCopy();
tmp.multiply(s);
return tmp;
}
public void multiply (Matrix B) {
double[][] tmp = new double[this.m][B.getColumnDimension()];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[0].length; j++) {
for (int k = 0; k < tmp.length; k++) {
tmp[i][j] += this.vals[i][k] * B.getComponent(k, j);
}
}
}
setVals(tmp);
}
public Matrix multiplyNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.multiply(B);
return tmp;
}
public void multiplyEach (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] *= B.getComponent(i, j);
}
}
}
public Matrix multiplyEachNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.multiplyEach(B);
return tmp;
}
public void divide (double s) {
for (int i = 0; i < this.vals.length; i++) {
for (int j = 0; j < this.vals[i].length; j++) {
this.vals[i][j] /= s;
}
}
}
public Matrix divideNew (double s) {
Matrix tmp = this.deepCopy();
tmp.divide(s);
return tmp;
}
public void divideEach (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] /= B.getComponent(i, j);
}
}
}
public Matrix divideEachNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.divideEach(B);
return tmp;
}
public void logN () {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] = Math.log(this.vals[i][j]);
}
}
}
public Matrix logNNew () {
Matrix tmp = this.deepCopy();
tmp.logN();
return tmp;
}
public void print() {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
System.out.print(this.vals[i][j] + ", ");
}
System.out.println();
}
}
}
| src/Matrix.java | public class Matrix {
/* -------------------
CLASS VARIABLES
---------------------*/
private double[][] vals; // values of matrix
private int m, n; // row and column dimensions
/* -------------------
CONSTRUCTORS
---------------------*/
// empty m x n matrix
public Matrix (int m, int n) {
this(m, n, 0);
}
// m x n matrix filled with scalar s
public Matrix (int m, int n, double s) {
this.m = n;
this.n = n;
this.vals = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
this.vals[i][j] = s;
}
}
}
// matrix created with given array
public Matrix (double[][] vals) {
this.m = vals.length;
this.n = vals[0].length;
this.vals = vals;
}
// matrix created from matrix, deep copy
public Matrix (Matrix matrix) {
double[][] tmp = new double[matrix.getRowDimension()][matrix.getColumnDimension()];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[i].length; j++) {
tmp[i][j] = matrix.getComponent(i, j);
}
}
this.m = tmp.length;
this.n = tmp[0].length;
this.vals = tmp;
}
/* -------------------
METHODS
---------------------*/
// GETTERS
public int getRowDimension () {
return this.m;
}
public int getColumnDimension () {
return this.n;
}
public double[][] getVals () {
return this.vals;
}
public double[] getColumnPackedArray () {
double[] tmp = new double[m*n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[i + j * m] = this.vals[i][j];
}
}
return tmp;
}
public double[] getRowPackedArray () {
double[] tmp = new double[m*n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[i * n + j] = this.vals[i][j];
}
}
return tmp;
}
public double getComponent (int i, int j) {
return this.vals[i][j];
}
public Matrix copy () {
return new Matrix(this);
}
public Matrix deepCopy () {
double[][] tmp = new double[this.m][this.n];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[i].length; j++) {
tmp[i][j] = this.vals[i][j];
}
}
return new Matrix(tmp);
}
public Matrix getSubMatrix (int x1, int x2, int y1, int y2) {
double[][] tmp = new double[y2-y1+1][x2-x1+1];
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
tmp[y - y1][x - x1] = this.vals[y][x];
}
}
return new Matrix(tmp);
}
public double[] getRowwiseMax () {
double[] tmp = new double[this.m];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = this.vals[i][0];
for (int j = 0; j < this.n; j++) {
tmp[i] = tmp[i] < this.vals[i][j] ? this.vals[i][j] : tmp[i];
}
}
return tmp;
}
public double[] getColwiseMax () {
double[] tmp = new double[this.n];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = this.vals[0][i];
for (int j = 0; j < this.m; j++) {
tmp[i] = tmp[i] < this.vals[j][i] ? this.vals[j][i] : tmp[i];
}
}
return tmp;
}
public double getMax () {
double tmp = this.vals[0][0];
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
tmp = tmp < this.vals[i][j] ? this.vals[i][j] : tmp;
}
}
return tmp;
}
// SETTERS
public void setComponent (int i, int j, double s) {
this.vals[i][j] = s;
}
public void setVals (double[][] vals) {
this.m = vals.length;
this.n = vals[0].length;
this.vals = new double[this.m][this.n];
this.vals = vals;
}
// OPERATIONS
public void unroll () {
double[][] tmp = new double[this.m * this.n][1];
int counter = 0;
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
tmp[counter][0] = this.vals[i][j];
counter++;
}
}
setVals(tmp);
}
public Matrix unrollNew () {
Matrix tmp = this.deepCopy();
tmp.unroll();
return tmp;
}
public void reshape (int m, int n) {
double[][] tmp = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
tmp[i][j] = this.vals[i + j * m][0];
}
}
setVals(tmp);
}
public Matrix reshapeNew (int m, int n) {
Matrix tmp = this.deepCopy();
tmp.reshape(m, n);
return tmp;
}
public void transpose () {
double [][] tmp = new double[this.n][this.m];
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
tmp[j][i] = this.vals[i][j];
}
}
setVals(tmp);
}
public Matrix transposeNew () {
Matrix tmp = this.copy();
tmp.transpose();
return tmp;
}
public void add (double s) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] += s;
}
}
}
public Matrix addNew (double s) {
Matrix tmp = this.deepCopy();
tmp.add(s);
return tmp;
}
public void add (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] += B.getComponent(i, j);
}
}
}
public Matrix addNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.add(B);
return tmp;
}
public void subtract (double s) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] -= s;
}
}
}
public Matrix subtractNew (double s) {
Matrix tmp = this.deepCopy();
tmp.subtract(s);
return tmp;
}
public void subtract (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] -= B.getComponent(i, j);
}
}
}
public Matrix subtractNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.subtract(B);
return tmp;
}
public void multiply (double s) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] *= s;
}
}
}
public Matrix multiplyNew (double s) {
Matrix tmp = this.deepCopy();
tmp.multiply(s);
return tmp;
}
public void multiply (Matrix B) {
double[][] tmp = new double[this.m][B.getColumnDimension()];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[0].length; j++) {
for (int k = 0; k < tmp.length; k++) {
tmp[i][j] += this.vals[i][k] * B.getComponent(k, j);
}
}
}
setVals(tmp);
}
public Matrix multiplyNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.multiply(B);
return tmp;
}
public void multiplyEach (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] *= B.getComponent(i, j);
}
}
}
public Matrix multiplyEachNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.multiplyEach(B);
return tmp;
}
public void divide (double s) {
for (int i = 0; i < this.vals.length; i++) {
for (int j = 0; j < this.vals[i].length; j++) {
this.vals[i][j] /= s;
}
}
}
public Matrix divideNew (double s) {
Matrix tmp = this.deepCopy();
tmp.divide(s);
return tmp;
}
public void divideEach (Matrix B) {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
this.vals[i][j] /= B.getComponent(i, j);
}
}
}
public Matrix divideEachNew (Matrix B) {
Matrix tmp = this.deepCopy();
tmp.divideEach(B);
return tmp;
}
public void print() {
for (int i = 0; i < this.m; i++) {
for (int j = 0; j < this.n; j++) {
System.out.print(this.vals[i][j] + ", ");
}
System.out.println();
}
}
}
| added log n functionality | src/Matrix.java | added log n functionality | <ide><path>rc/Matrix.java
<ide> return tmp;
<ide> }
<ide>
<add> public void logN () {
<add> for (int i = 0; i < this.m; i++) {
<add> for (int j = 0; j < this.n; j++) {
<add> this.vals[i][j] = Math.log(this.vals[i][j]);
<add> }
<add> }
<add> }
<add>
<add> public Matrix logNNew () {
<add> Matrix tmp = this.deepCopy();
<add> tmp.logN();
<add> return tmp;
<add> }
<add>
<ide>
<ide>
<ide> |
|
Java | apache-2.0 | 94e6b7587d83b4ac1a0af0953199e0f4bd9340e8 | 0 | wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,jcshen007/cloudstack,resmo/cloudstack,wido/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.upgrade.dao;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.utils.crypt.DBEncryptionUtil;
import org.apache.log4j.Logger;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
public class Upgrade442to450 implements DbUpgrade {
final static Logger s_logger = Logger.getLogger(Upgrade442to450.class);
@Override
public String[] getUpgradableVersionRange() {
return new String[] {"4.4.2", "4.5.0"};
}
@Override
public String getUpgradedVersion() {
return "4.5.0";
}
@Override
public boolean supportsRollingUpgrade() {
return false;
}
@Override
public File[] getPrepareScripts() {
String script = Script.findScript("", "db/schema-442to450.sql");
if (script == null) {
throw new CloudRuntimeException("Unable to find db/schema-442to450.sql");
}
return new File[] {new File(script)};
}
@Override
public void performDataMigration(Connection conn) {
updateSystemVmTemplates(conn);
dropInvalidKeyFromStoragePoolTable(conn);
dropDuplicatedForeignKeyFromAsyncJobTable(conn);
updateMaxRouterSizeConfig(conn);
upgradeMemoryOfVirtualRoutervmOffering(conn);
upgradeMemoryOfInternalLoadBalancervmOffering(conn);
}
private void updateMaxRouterSizeConfig(Connection conn) {
PreparedStatement updatePstmt = null;
try {
String encryptedValue = DBEncryptionUtil.encrypt("256");
updatePstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value=? WHERE name='router.ram.size' AND category='Hidden'");
updatePstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade max ram size of router in config.", e);
} catch (UnsupportedEncodingException e) {
throw new CloudRuntimeException("Unable encrypt configuration values ", e);
} finally {
try {
if (updatePstmt != null) {
updatePstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done updating router.ram.size config to 256");
}
private void upgradeMemoryOfVirtualRoutervmOffering(Connection conn) {
PreparedStatement updatePstmt = null;
PreparedStatement selectPstmt = null;
ResultSet selectResultSet = null;
int newRamSize = 256; //256MB
long serviceOfferingId = 0;
/**
* Pick first row in service_offering table which has system vm type as domainrouter. User added offerings would start from 2nd row onwards.
* We should not update/modify any user-defined offering.
*/
try {
selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='domainrouter'");
updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
selectResultSet = selectPstmt.executeQuery();
if(selectResultSet.next()) {
serviceOfferingId = selectResultSet.getLong("id");
}
updatePstmt.setInt(1, newRamSize);
updatePstmt.setLong(2, serviceOfferingId);
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for domain router. ", e);
} finally {
try {
if (selectPstmt != null) {
selectPstmt.close();
}
if (selectResultSet != null) {
selectResultSet.close();
}
if (updatePstmt != null) {
updatePstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done upgrading RAM for service offering of domain router to " + newRamSize);
}
private void upgradeMemoryOfInternalLoadBalancervmOffering(Connection conn) {
int newRamSize = 256; //256MB
long serviceOfferingId = 0;
/**
* Pick first row in service_offering table which has system vm type as internalloadbalancervm. User added offerings would start from 2nd row onwards.
* We should not update/modify any user-defined offering.
*/
try (PreparedStatement selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='internalloadbalancervm'");
PreparedStatement updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
ResultSet selectResultSet = selectPstmt.executeQuery()){
if(selectResultSet.next()) {
serviceOfferingId = selectResultSet.getLong("id");
}
updatePstmt.setInt(1, newRamSize);
updatePstmt.setLong(2, serviceOfferingId);
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for internal loadbalancer vm. ", e);
}
s_logger.debug("Done upgrading RAM for service offering of internal loadbalancer vm to " + newRamSize);
}
@Override
public File[] getCleanupScripts() {
String script = Script.findScript("", "db/schema-442to450-cleanup.sql");
if (script == null) {
throw new CloudRuntimeException("Unable to find db/schema-442to450-cleanup.sql");
}
return new File[] {new File(script)};
}
private void updateSystemVmTemplates(Connection conn) {
s_logger.debug("Updating System Vm template IDs");
//Get all hypervisors in use
Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
try (PreparedStatement pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
ResultSet rs = pstmt.executeQuery()
) {
while(rs.next()){
switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
case XenServer: hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
break;
case KVM: hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
break;
case VMware: hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
break;
case Hyperv: hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
break;
case LXC: hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
break;
default: // no action on cases Any, BareMetal, None, Ovm, Parralels, Simulator and VirtualBox:
break;
}
}
} catch (SQLException e) {
s_logger.error("updateSystemVmTemplates:Exception while getting hypervisor types from clusters: "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e);
}
Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.5");
put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.5");
put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.5");
put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.5");
put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.5");
}
};
Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.XenServer, "router.template.xen");
put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
}
};
Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.XenServer, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-xen.vhd.bz2");
put(Hypervisor.HypervisorType.VMware, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-vmware.ova");
put(Hypervisor.HypervisorType.KVM, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.LXC, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.Hyperv, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-hyperv.vhd.zip");
}
};
Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.XenServer, "2b15ab4401c2d655264732d3fc600241");
put(Hypervisor.HypervisorType.VMware, "3106a79a4ce66cd7f6a7c50e93f2db57");
put(Hypervisor.HypervisorType.KVM, "aa9f501fecd3de1daeb9e2f357f6f002");
put(Hypervisor.HypervisorType.LXC, "aa9f501fecd3de1daeb9e2f357f6f002");
put(Hypervisor.HypervisorType.Hyperv, "70bd30ea02ee9ed67d2c6b85c179cee9");
}
};
for (Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()) {
s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1")) {
//Get 4.5.0 system Vm template Id for corresponding hypervisor
long templateId = -1;
pstmt.setString(1, hypervisorAndTemplateName.getValue());
try (ResultSet rs = pstmt.executeQuery()) {
if(rs.next()){
templateId = rs.getLong(1);
}
} catch (SQLException e)
{
s_logger.error("updateSystemVmTemplates:Exception while getting ids of templates: "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
}
// change template type to SYSTEM
if (templateId != -1) {
try(PreparedStatement templ_type_pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");)
{
templ_type_pstmt.setLong(1, templateId);
templ_type_pstmt.executeUpdate();
}
catch (SQLException e)
{
s_logger.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system'", e);
}
// update template ID of system Vms
try(PreparedStatement update_templ_id_pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?");)
{
update_templ_id_pstmt.setLong(1, templateId);
update_templ_id_pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
update_templ_id_pstmt.executeUpdate();
}catch (Exception e)
{
s_logger.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId + ": "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId, e);
}
// Change value of global configuration parameter router.template.* for the corresponding hypervisor
try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");) {
update_pstmt.setString(1, hypervisorAndTemplateName.getValue());
update_pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
update_pstmt.executeUpdate();
}catch (SQLException e)
{
s_logger.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue() + ": "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue(), e);
}
} else {
if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())){
throw new CloudRuntimeException("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
} else {
s_logger.warn("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade");
// Update the latest template URLs for corresponding hypervisor
try(PreparedStatement update_templ_url_pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");) {
update_templ_url_pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
update_templ_url_pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
update_templ_url_pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
update_templ_url_pstmt.executeUpdate();
}catch (SQLException e)
{
s_logger.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString() + ": "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString(), e);
}
}
}
} catch (SQLException e) {
s_logger.error("updateSystemVmTemplates:Exception while getting ids of templates: "+e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
}
}
s_logger.debug("Updating System Vm Template IDs Complete");
}
private void dropInvalidKeyFromStoragePoolTable(Connection conn) {
HashMap<String, List<String>> uniqueKeys = new HashMap<String, List<String>>();
List<String> keys = new ArrayList<String>();
keys.add("id_2");
uniqueKeys.put("storage_pool", keys);
s_logger.debug("Dropping id_2 key from storage_pool table");
for (Map.Entry<String, List<String>> entry: uniqueKeys.entrySet()) {
DbUpgradeUtils.dropKeysIfExist(conn,entry.getKey(), entry.getValue(), false);
}
}
private void dropDuplicatedForeignKeyFromAsyncJobTable(Connection conn) {
HashMap<String, List<String>> foreignKeys = new HashMap<String, List<String>>();
List<String> keys = new ArrayList<String>();
keys.add("fk_async_job_join_map__join_job_id");
foreignKeys.put("async_job_join_map", keys);
s_logger.debug("Dropping fk_async_job_join_map__join_job_id key from async_job_join_map table");
for (Map.Entry<String, List<String>> entry: foreignKeys.entrySet()) {
DbUpgradeUtils.dropKeysIfExist(conn,entry.getKey(), entry.getValue(), true);
}
}
}
| engine/schema/src/com/cloud/upgrade/dao/Upgrade442to450.java | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.upgrade.dao;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.utils.crypt.DBEncryptionUtil;
import org.apache.log4j.Logger;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
public class Upgrade442to450 implements DbUpgrade {
final static Logger s_logger = Logger.getLogger(Upgrade442to450.class);
@Override
public String[] getUpgradableVersionRange() {
return new String[] {"4.4.2", "4.5.0"};
}
@Override
public String getUpgradedVersion() {
return "4.5.0";
}
@Override
public boolean supportsRollingUpgrade() {
return false;
}
@Override
public File[] getPrepareScripts() {
String script = Script.findScript("", "db/schema-442to450.sql");
if (script == null) {
throw new CloudRuntimeException("Unable to find db/schema-442to450.sql");
}
return new File[] {new File(script)};
}
@Override
public void performDataMigration(Connection conn) {
updateSystemVmTemplates(conn);
dropInvalidKeyFromStoragePoolTable(conn);
dropDuplicatedForeignKeyFromAsyncJobTable(conn);
updateMaxRouterSizeConfig(conn);
upgradeMemoryOfVirtualRoutervmOffering(conn);
upgradeMemoryOfInternalLoadBalancervmOffering(conn);
}
private void updateMaxRouterSizeConfig(Connection conn) {
PreparedStatement updatePstmt = null;
try {
String encryptedValue = DBEncryptionUtil.encrypt("256");
updatePstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value=? WHERE name='router.ram.size' AND category='Hidden'");
updatePstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade max ram size of router in config.", e);
} catch (UnsupportedEncodingException e) {
throw new CloudRuntimeException("Unable encrypt configuration values ", e);
} finally {
try {
if (updatePstmt != null) {
updatePstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done updating router.ram.size config to 256");
}
private void upgradeMemoryOfVirtualRoutervmOffering(Connection conn) {
PreparedStatement updatePstmt = null;
PreparedStatement selectPstmt = null;
ResultSet selectResultSet = null;
int newRamSize = 256; //256MB
long serviceOfferingId = 0;
/**
* Pick first row in service_offering table which has system vm type as domainrouter. User added offerings would start from 2nd row onwards.
* We should not update/modify any user-defined offering.
*/
try {
selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='domainrouter'");
updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
selectResultSet = selectPstmt.executeQuery();
if(selectResultSet.next()) {
serviceOfferingId = selectResultSet.getLong("id");
}
updatePstmt.setInt(1, newRamSize);
updatePstmt.setLong(2, serviceOfferingId);
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for domain router. ", e);
} finally {
try {
if (selectPstmt != null) {
selectPstmt.close();
}
if (selectResultSet != null) {
selectResultSet.close();
}
if (updatePstmt != null) {
updatePstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done upgrading RAM for service offering of domain router to " + newRamSize);
}
private void upgradeMemoryOfInternalLoadBalancervmOffering(Connection conn) {
PreparedStatement updatePstmt = null;
PreparedStatement selectPstmt = null;
ResultSet selectResultSet = null;
int newRamSize = 256; //256MB
long serviceOfferingId = 0;
/**
* Pick first row in service_offering table which has system vm type as internalloadbalancervm. User added offerings would start from 2nd row onwards.
* We should not update/modify any user-defined offering.
*/
try {
selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='internalloadbalancervm'");
updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
selectResultSet = selectPstmt.executeQuery();
if(selectResultSet.next()) {
serviceOfferingId = selectResultSet.getLong("id");
}
updatePstmt.setInt(1, newRamSize);
updatePstmt.setLong(2, serviceOfferingId);
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for internal loadbalancer vm. ", e);
} finally {
try {
if (selectPstmt != null) {
selectPstmt.close();
}
if (selectResultSet != null) {
selectResultSet.close();
}
if (updatePstmt != null) {
updatePstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done upgrading RAM for service offering of internal loadbalancer vm to " + newRamSize);
}
@Override
public File[] getCleanupScripts() {
String script = Script.findScript("", "db/schema-442to450-cleanup.sql");
if (script == null) {
throw new CloudRuntimeException("Unable to find db/schema-442to450-cleanup.sql");
}
return new File[] {new File(script)};
}
private void updateSystemVmTemplates(Connection conn) {
PreparedStatement pstmt = null;
ResultSet rs = null;
s_logger.debug("Updating System Vm template IDs");
try{
//Get all hypervisors in use
Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
try {
pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
rs = pstmt.executeQuery();
while(rs.next()){
switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
case XenServer: hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
break;
case KVM: hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
break;
case VMware: hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
break;
case Hyperv: hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
break;
case LXC: hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
break;
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Error while listing hypervisors in use", e);
}
Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.5");
put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.5");
put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.5");
put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.5");
put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.5");
}
};
Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "router.template.xen");
put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
}
};
Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-xen.vhd.bz2");
put(Hypervisor.HypervisorType.VMware, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-vmware.ova");
put(Hypervisor.HypervisorType.KVM, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.LXC, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.Hyperv, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-hyperv.vhd.zip");
}
};
Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "2b15ab4401c2d655264732d3fc600241");
put(Hypervisor.HypervisorType.VMware, "3106a79a4ce66cd7f6a7c50e93f2db57");
put(Hypervisor.HypervisorType.KVM, "aa9f501fecd3de1daeb9e2f357f6f002");
put(Hypervisor.HypervisorType.LXC, "aa9f501fecd3de1daeb9e2f357f6f002");
put(Hypervisor.HypervisorType.Hyperv, "70bd30ea02ee9ed67d2c6b85c179cee9");
}
};
for (Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()){
s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
try {
//Get 4.5.0 system Vm template Id for corresponding hypervisor
pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1");
pstmt.setString(1, hypervisorAndTemplateName.getValue());
rs = pstmt.executeQuery();
if(rs.next()){
long templateId = rs.getLong(1);
rs.close();
pstmt.close();
pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");
pstmt.setLong(1, templateId);
pstmt.executeUpdate();
pstmt.close();
// update templete ID of system Vms
pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?");
pstmt.setLong(1, templateId);
pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
// Change value of global configuration parameter router.template.* for the corresponding hypervisor
pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");
pstmt.setString(1, hypervisorAndTemplateName.getValue());
pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
pstmt.executeUpdate();
pstmt.close();
} else {
if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())){
throw new CloudRuntimeException("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
} else {
s_logger.warn("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade");
// Update the latest template URLs for corresponding hypervisor
pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");
pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Error while updating "+ hypervisorAndTemplateName.getKey() +" systemVm template", e);
}
}
s_logger.debug("Updating System Vm Template IDs Complete");
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
}
}
}
private void dropInvalidKeyFromStoragePoolTable(Connection conn) {
HashMap<String, List<String>> uniqueKeys = new HashMap<String, List<String>>();
List<String> keys = new ArrayList<String>();
keys.add("id_2");
uniqueKeys.put("storage_pool", keys);
s_logger.debug("Dropping id_2 key from storage_pool table");
for (Map.Entry<String, List<String>> entry: uniqueKeys.entrySet()) {
DbUpgradeUtils.dropKeysIfExist(conn,entry.getKey(), entry.getValue(), false);
}
}
private void dropDuplicatedForeignKeyFromAsyncJobTable(Connection conn) {
HashMap<String, List<String>> foreignKeys = new HashMap<String, List<String>>();
List<String> keys = new ArrayList<String>();
keys.add("fk_async_job_join_map__join_job_id");
foreignKeys.put("async_job_join_map", keys);
s_logger.debug("Dropping fk_async_job_join_map__join_job_id key from async_job_join_map table");
for (Map.Entry<String, List<String>> entry: foreignKeys.entrySet()) {
DbUpgradeUtils.dropKeysIfExist(conn,entry.getKey(), entry.getValue(), true);
}
}
}
| CID-1256275 regression: resource leak in systemvm update code
(cherry picked from commit 06d4458d0a9de5be7a7bf590678eb4b03989e9a1)
Conflicts:
engine/schema/src/com/cloud/upgrade/dao/Upgrade442to450.java
| engine/schema/src/com/cloud/upgrade/dao/Upgrade442to450.java | CID-1256275 regression: resource leak in systemvm update code (cherry picked from commit 06d4458d0a9de5be7a7bf590678eb4b03989e9a1) | <ide><path>ngine/schema/src/com/cloud/upgrade/dao/Upgrade442to450.java
<ide> }
<ide>
<ide> private void upgradeMemoryOfInternalLoadBalancervmOffering(Connection conn) {
<del> PreparedStatement updatePstmt = null;
<del> PreparedStatement selectPstmt = null;
<del> ResultSet selectResultSet = null;
<ide> int newRamSize = 256; //256MB
<ide> long serviceOfferingId = 0;
<ide>
<ide> * We should not update/modify any user-defined offering.
<ide> */
<ide>
<del> try {
<del> selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='internalloadbalancervm'");
<del> updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
<del> selectResultSet = selectPstmt.executeQuery();
<add> try (PreparedStatement selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='internalloadbalancervm'");
<add> PreparedStatement updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
<add> ResultSet selectResultSet = selectPstmt.executeQuery()){
<ide> if(selectResultSet.next()) {
<ide> serviceOfferingId = selectResultSet.getLong("id");
<ide> }
<ide> updatePstmt.executeUpdate();
<ide> } catch (SQLException e) {
<ide> throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for internal loadbalancer vm. ", e);
<del> } finally {
<del> try {
<del> if (selectPstmt != null) {
<del> selectPstmt.close();
<del> }
<del> if (selectResultSet != null) {
<del> selectResultSet.close();
<del> }
<del> if (updatePstmt != null) {
<del> updatePstmt.close();
<del> }
<del> } catch (SQLException e) {
<del> }
<ide> }
<ide> s_logger.debug("Done upgrading RAM for service offering of internal loadbalancer vm to " + newRamSize);
<ide> }
<ide> }
<ide>
<ide> private void updateSystemVmTemplates(Connection conn) {
<del> PreparedStatement pstmt = null;
<del> ResultSet rs = null;
<ide> s_logger.debug("Updating System Vm template IDs");
<del> try{
<del> //Get all hypervisors in use
<del> Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
<del> try {
<del> pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
<del> rs = pstmt.executeQuery();
<del> while(rs.next()){
<del> switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
<del> case XenServer: hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
<del> break;
<del> case KVM: hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
<del> break;
<del> case VMware: hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
<del> break;
<del> case Hyperv: hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
<del> break;
<del> case LXC: hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
<del> break;
<add> //Get all hypervisors in use
<add> Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
<add> try (PreparedStatement pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
<add> ResultSet rs = pstmt.executeQuery()
<add> ) {
<add> while(rs.next()){
<add> switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
<add> case XenServer: hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
<add> break;
<add> case KVM: hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
<add> break;
<add> case VMware: hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
<add> break;
<add> case Hyperv: hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
<add> break;
<add> case LXC: hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
<add> break;
<add> default: // no action on cases Any, BareMetal, None, Ovm, Parralels, Simulator and VirtualBox:
<add> break;
<add> }
<add> }
<add> } catch (SQLException e) {
<add> s_logger.error("updateSystemVmTemplates:Exception while getting hypervisor types from clusters: "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e);
<add> }
<add>
<add> Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>() {
<add> {
<add> put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.5");
<add> put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.5");
<add> put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.5");
<add> put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.5");
<add> put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.5");
<add> }
<add> };
<add>
<add> Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>() {
<add> {
<add> put(Hypervisor.HypervisorType.XenServer, "router.template.xen");
<add> put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
<add> put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
<add> put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
<add> put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
<add> }
<add> };
<add>
<add> Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>() {
<add> {
<add> put(Hypervisor.HypervisorType.XenServer, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-xen.vhd.bz2");
<add> put(Hypervisor.HypervisorType.VMware, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-vmware.ova");
<add> put(Hypervisor.HypervisorType.KVM, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
<add> put(Hypervisor.HypervisorType.LXC, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
<add> put(Hypervisor.HypervisorType.Hyperv, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-hyperv.vhd.zip");
<add> }
<add> };
<add>
<add> Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>() {
<add> {
<add> put(Hypervisor.HypervisorType.XenServer, "2b15ab4401c2d655264732d3fc600241");
<add> put(Hypervisor.HypervisorType.VMware, "3106a79a4ce66cd7f6a7c50e93f2db57");
<add> put(Hypervisor.HypervisorType.KVM, "aa9f501fecd3de1daeb9e2f357f6f002");
<add> put(Hypervisor.HypervisorType.LXC, "aa9f501fecd3de1daeb9e2f357f6f002");
<add> put(Hypervisor.HypervisorType.Hyperv, "70bd30ea02ee9ed67d2c6b85c179cee9");
<add> }
<add> };
<add>
<add> for (Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()) {
<add> s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
<add> try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1")) {
<add> //Get 4.5.0 system Vm template Id for corresponding hypervisor
<add> long templateId = -1;
<add> pstmt.setString(1, hypervisorAndTemplateName.getValue());
<add> try (ResultSet rs = pstmt.executeQuery()) {
<add> if(rs.next()){
<add> templateId = rs.getLong(1);
<add> }
<add> } catch (SQLException e)
<add> {
<add> s_logger.error("updateSystemVmTemplates:Exception while getting ids of templates: "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
<add> }
<add>
<add> // change template type to SYSTEM
<add> if (templateId != -1) {
<add> try(PreparedStatement templ_type_pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");)
<add> {
<add> templ_type_pstmt.setLong(1, templateId);
<add> templ_type_pstmt.executeUpdate();
<add> }
<add> catch (SQLException e)
<add> {
<add> s_logger.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system'", e);
<add> }
<add> // update template ID of system Vms
<add> try(PreparedStatement update_templ_id_pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?");)
<add> {
<add> update_templ_id_pstmt.setLong(1, templateId);
<add> update_templ_id_pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
<add> update_templ_id_pstmt.executeUpdate();
<add> }catch (Exception e)
<add> {
<add> s_logger.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId + ": "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId, e);
<add> }
<add> // Change value of global configuration parameter router.template.* for the corresponding hypervisor
<add> try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");) {
<add> update_pstmt.setString(1, hypervisorAndTemplateName.getValue());
<add> update_pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
<add> update_pstmt.executeUpdate();
<add> }catch (SQLException e)
<add> {
<add> s_logger.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue() + ": "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue(), e);
<add> }
<add> } else {
<add> if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())){
<add> throw new CloudRuntimeException("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
<add> } else {
<add> s_logger.warn("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade");
<add> // Update the latest template URLs for corresponding hypervisor
<add> try(PreparedStatement update_templ_url_pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");) {
<add> update_templ_url_pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
<add> update_templ_url_pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
<add> update_templ_url_pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
<add> update_templ_url_pstmt.executeUpdate();
<add> }catch (SQLException e)
<add> {
<add> s_logger.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString() + ": "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString(), e);
<add> }
<ide> }
<ide> }
<ide> } catch (SQLException e) {
<del> throw new CloudRuntimeException("Error while listing hypervisors in use", e);
<del> }
<del>
<del> Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>(){
<del> { put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.5");
<del> put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.5");
<del> put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.5");
<del> put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.5");
<del> put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.5");
<del> }
<del> };
<del>
<del> Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>(){
<del> { put(Hypervisor.HypervisorType.XenServer, "router.template.xen");
<del> put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
<del> put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
<del> put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
<del> put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
<del> }
<del> };
<del>
<del> Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>(){
<del> { put(Hypervisor.HypervisorType.XenServer, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-xen.vhd.bz2");
<del> put(Hypervisor.HypervisorType.VMware, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-vmware.ova");
<del> put(Hypervisor.HypervisorType.KVM, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
<del> put(Hypervisor.HypervisorType.LXC, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-kvm.qcow2.bz2");
<del> put(Hypervisor.HypervisorType.Hyperv, "http://download.cloud.com/templates/4.5/systemvm64template-4.5-hyperv.vhd.zip");
<del> }
<del> };
<del>
<del> Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>(){
<del> { put(Hypervisor.HypervisorType.XenServer, "2b15ab4401c2d655264732d3fc600241");
<del> put(Hypervisor.HypervisorType.VMware, "3106a79a4ce66cd7f6a7c50e93f2db57");
<del> put(Hypervisor.HypervisorType.KVM, "aa9f501fecd3de1daeb9e2f357f6f002");
<del> put(Hypervisor.HypervisorType.LXC, "aa9f501fecd3de1daeb9e2f357f6f002");
<del> put(Hypervisor.HypervisorType.Hyperv, "70bd30ea02ee9ed67d2c6b85c179cee9");
<del> }
<del> };
<del>
<del> for (Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()){
<del> s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
<del> try {
<del> //Get 4.5.0 system Vm template Id for corresponding hypervisor
<del> pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1");
<del> pstmt.setString(1, hypervisorAndTemplateName.getValue());
<del> rs = pstmt.executeQuery();
<del> if(rs.next()){
<del> long templateId = rs.getLong(1);
<del> rs.close();
<del> pstmt.close();
<del> pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");
<del> pstmt.setLong(1, templateId);
<del> pstmt.executeUpdate();
<del> pstmt.close();
<del> // update templete ID of system Vms
<del> pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?");
<del> pstmt.setLong(1, templateId);
<del> pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
<del> pstmt.executeUpdate();
<del> pstmt.close();
<del> // Change value of global configuration parameter router.template.* for the corresponding hypervisor
<del> pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");
<del> pstmt.setString(1, hypervisorAndTemplateName.getValue());
<del> pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
<del> pstmt.executeUpdate();
<del> pstmt.close();
<del> } else {
<del> if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())){
<del> throw new CloudRuntimeException("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
<del> } else {
<del> s_logger.warn("4.5.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade");
<del> // Update the latest template URLs for corresponding hypervisor
<del> pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");
<del> pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
<del> pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
<del> pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
<del> pstmt.executeUpdate();
<del> pstmt.close();
<del> }
<del> }
<del> } catch (SQLException e) {
<del> throw new CloudRuntimeException("Error while updating "+ hypervisorAndTemplateName.getKey() +" systemVm template", e);
<del> }
<del> }
<del> s_logger.debug("Updating System Vm Template IDs Complete");
<del> } finally {
<del> try {
<del> if (rs != null) {
<del> rs.close();
<del> }
<del>
<del> if (pstmt != null) {
<del> pstmt.close();
<del> }
<del> } catch (SQLException e) {
<del> }
<del> }
<add> s_logger.error("updateSystemVmTemplates:Exception while getting ids of templates: "+e.getMessage());
<add> throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
<add> }
<add> }
<add> s_logger.debug("Updating System Vm Template IDs Complete");
<ide> }
<ide>
<ide> |
|
Java | mit | 8c81991ec037cce2c8c3858cf937b32830bb3a76 | 0 | viqueen/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,pjanouse/jenkins,ikedam/jenkins,pjanouse/jenkins,rsandell/jenkins,recena/jenkins,recena/jenkins,patbos/jenkins,pjanouse/jenkins,oleg-nenashev/jenkins,rsandell/jenkins,pjanouse/jenkins,recena/jenkins,godfath3r/jenkins,viqueen/jenkins,oleg-nenashev/jenkins,DanielWeber/jenkins,v1v/jenkins,daniel-beck/jenkins,godfath3r/jenkins,patbos/jenkins,damianszczepanik/jenkins,recena/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,DanielWeber/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,ikedam/jenkins,DanielWeber/jenkins,patbos/jenkins,MarkEWaite/jenkins,ikedam/jenkins,damianszczepanik/jenkins,MarkEWaite/jenkins,recena/jenkins,pjanouse/jenkins,viqueen/jenkins,v1v/jenkins,DanielWeber/jenkins,patbos/jenkins,damianszczepanik/jenkins,daniel-beck/jenkins,viqueen/jenkins,viqueen/jenkins,ikedam/jenkins,damianszczepanik/jenkins,rsandell/jenkins,patbos/jenkins,v1v/jenkins,rsandell/jenkins,DanielWeber/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,oleg-nenashev/jenkins,jenkinsci/jenkins,ikedam/jenkins,ikedam/jenkins,v1v/jenkins,recena/jenkins,pjanouse/jenkins,oleg-nenashev/jenkins,v1v/jenkins,ikedam/jenkins,jenkinsci/jenkins,patbos/jenkins,godfath3r/jenkins,jenkinsci/jenkins,pjanouse/jenkins,patbos/jenkins,DanielWeber/jenkins,damianszczepanik/jenkins,damianszczepanik/jenkins,viqueen/jenkins,v1v/jenkins,v1v/jenkins,rsandell/jenkins,daniel-beck/jenkins,rsandell/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,ikedam/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,recena/jenkins,godfath3r/jenkins,rsandell/jenkins,daniel-beck/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,godfath3r/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,godfath3r/jenkins,rsandell/jenkins,viqueen/jenkins | /*
* The MIT License
*
* Copyright 2017 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PlainCLIProtocolTest {
@Test
public void ignoreUnknownOperations() throws Exception {
final PipedOutputStream upload = new PipedOutputStream();
final PipedOutputStream download = new PipedOutputStream();
class Client extends PlainCLIProtocol.ClientSide {
int code = -1;
final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
Client() throws IOException {
super(new PipedInputStream(download), upload);
}
@Override
protected synchronized void onExit(int code) {
this.code = code;
notifyAll();
}
@Override
protected void onStdout(byte[] chunk) throws IOException {
stdout.write(chunk);
}
@Override
protected void onStderr(byte[] chunk) throws IOException {}
@Override
protected void handleClose() {}
void send() throws IOException {
sendArg("command");
sendStart();
streamStdin().write("hello".getBytes());
}
void newop() throws IOException {
dos.writeInt(0);
dos.writeByte(99);
dos.flush();
}
}
class Server extends PlainCLIProtocol.ServerSide {
String arg;
boolean started;
final ByteArrayOutputStream stdin = new ByteArrayOutputStream();
Server() throws IOException {
super(new PipedInputStream(upload), download);
}
@Override
protected void onArg(String text) {
arg = text;
}
@Override
protected void onLocale(String text) {}
@Override
protected void onEncoding(String text) {}
@Override
protected synchronized void onStart() {
started = true;
notifyAll();
}
@Override
protected void onStdin(byte[] chunk) throws IOException {
/* To inject a race condition:
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
throw new IOException(x);
}
*/
stdin.write(chunk);
}
@Override
protected void onEndStdin() throws IOException {}
@Override
protected void handleClose() {}
void send() throws IOException {
streamStdout().write("goodbye".getBytes());
sendExit(2);
}
void newop() throws IOException {
dos.writeInt(0);
dos.writeByte(99);
dos.flush();
}
}
Client client = new Client();
Server server = new Server();
client.begin();
server.begin();
client.send();
client.newop();
synchronized (server) {
while (!server.started) {
server.wait();
}
}
server.newop();
server.send();
synchronized (client) {
while (client.code == -1) {
client.wait();
}
}
while (server.stdin.size() == 0) {
Thread.sleep(100);
}
assertEquals("hello", server.stdin.toString());
assertEquals("command", server.arg);
assertEquals("goodbye", client.stdout.toString());
assertEquals(2, client.code);
}
}
| cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java | /*
* The MIT License
*
* Copyright 2017 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PlainCLIProtocolTest {
@Test
public void ignoreUnknownOperations() throws Exception {
final PipedOutputStream upload = new PipedOutputStream();
final PipedOutputStream download = new PipedOutputStream();
class Client extends PlainCLIProtocol.ClientSide {
int code = -1;
final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
Client() throws IOException {
super(new PipedInputStream(download), upload);
}
@Override
protected synchronized void onExit(int code) {
this.code = code;
notifyAll();
}
@Override
protected void onStdout(byte[] chunk) throws IOException {
stdout.write(chunk);
}
@Override
protected void onStderr(byte[] chunk) throws IOException {}
@Override
protected void handleClose() {}
void send() throws IOException {
sendArg("command");
sendStart();
streamStdin().write("hello".getBytes());
}
void newop() throws IOException {
dos.writeInt(0);
dos.writeByte(99);
dos.flush();
}
}
class Server extends PlainCLIProtocol.ServerSide {
String arg;
boolean started;
final ByteArrayOutputStream stdin = new ByteArrayOutputStream();
Server() throws IOException {
super(new PipedInputStream(upload), download);
}
@Override
protected void onArg(String text) {
arg = text;
}
@Override
protected void onLocale(String text) {}
@Override
protected void onEncoding(String text) {}
@Override
protected synchronized void onStart() {
started = true;
notifyAll();
}
@Override
protected void onStdin(byte[] chunk) throws IOException {
stdin.write(chunk);
}
@Override
protected void onEndStdin() throws IOException {}
@Override
protected void handleClose() {}
void send() throws IOException {
streamStdout().write("goodbye".getBytes());
sendExit(2);
}
void newop() throws IOException {
dos.writeInt(0);
dos.writeByte(99);
dos.flush();
}
}
Client client = new Client();
Server server = new Server();
client.begin();
server.begin();
client.send();
client.newop();
synchronized (server) {
while (!server.started) {
server.wait();
}
}
server.newop();
server.send();
synchronized (client) {
while (client.code == -1) {
client.wait();
}
}
assertEquals("hello", server.stdin.toString());
assertEquals("command", server.arg);
assertEquals("goodbye", client.stdout.toString());
assertEquals(2, client.code);
}
}
| Race condition in PlainCLIProtocolTest.
| cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java | Race condition in PlainCLIProtocolTest. | <ide><path>li/src/test/java/hudson/cli/PlainCLIProtocolTest.java
<ide> }
<ide> @Override
<ide> protected void onStdin(byte[] chunk) throws IOException {
<add> /* To inject a race condition:
<add> try {
<add> Thread.sleep(1000);
<add> } catch (InterruptedException x) {
<add> throw new IOException(x);
<add> }
<add> */
<ide> stdin.write(chunk);
<ide> }
<ide> @Override
<ide> client.wait();
<ide> }
<ide> }
<add> while (server.stdin.size() == 0) {
<add> Thread.sleep(100);
<add> }
<ide> assertEquals("hello", server.stdin.toString());
<ide> assertEquals("command", server.arg);
<ide> assertEquals("goodbye", client.stdout.toString()); |
|
Java | apache-2.0 | 262404ade9f587a6c5a553ca0a3aca742f41a13f | 0 | ProgrammingLife2016/PL4-2016 | package application.factories;
import application.controllers.MainController;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.stream.Collectors;
import static java.lang.String.format;
/**
* WindowFactory class.
*
* @version 1.0
* @since 25-04-2016
*/
public final class WindowFactory {
static Rectangle2D screenSize;
static Stage window;
static MainController mainController;
static Scene scene;
/**
* Private class constructor.
*/
private WindowFactory() {
}
/**
* Create method for windows.
*
* @param m parent of the window
* @return the constructed window.
*/
public static Stage createWindow(MainController m) {
mainController = m;
window = new Stage();
scene = createScene(m.getRoot());
screenSize = Screen.getPrimary().getVisualBounds();
window.setWidth(screenSize.getWidth());
window.setHeight(screenSize.getHeight());
window.setMaxHeight(screenSize.getHeight());
window.setScene(scene);
window.show();
return window;
}
/**
* Method to create the scene.
*
* @param parent parent object for the scene.
* @return the constructed scene.
*/
public static Scene createScene(Parent parent) {
Scene scene = new Scene(parent);
return scene;
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser.
*/
public static FileChooser createGraphChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Graph File");
File selectedFile = directoryChooser.showOpenDialog(window);
mainController.addRecentGFA(selectedFile.getAbsolutePath());
File parentDir = selectedFile.getParentFile();
createGFApopup(parentDir, selectedFile);
return directoryChooser;
}
/**
* Method to create a pop-up when selecting a NWK File
*
* @param parentDir the current Directory
* @param selectedFile the selected File
*/
@SuppressFBWarnings
public static void createGFApopup(File parentDir, File selectedFile) {
ArrayList<Text> candidates = new ArrayList<>();
if (parentDir.isDirectory()) {
for (File f : parentDir.listFiles()) {
String ext = FilenameUtils.getExtension(f.getName());
if (ext.equals("nwk")) {
Text t = new Text(f.getAbsolutePath());
candidates.add(t);
}
}
}
mainController.setBackground("/background_images/loading.png");
if (!candidates.isEmpty()) {
showPopup(candidates, selectedFile, parentDir, "NWK");
} else {
mainController.getGraphController().getGraph().getNodeMapFromFile(selectedFile.toString());
mainController.initGraph();
}
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser
*/
public static FileChooser createTreeChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Tree File");
File selectedFile = directoryChooser.showOpenDialog(window);
File parentDir = selectedFile.getParentFile();
createNWKpopup(parentDir, selectedFile);
return directoryChooser;
}
/**
* Method the create a pop-up when choosing a GFA File
*
* @param parentDir the current Directory we're at
* @param selectedFile the selected File
*/
@SuppressFBWarnings
public static void createNWKpopup(File parentDir, File selectedFile) {
ArrayList<Text> candidates = new ArrayList<>();
if (parentDir.isDirectory()) {
for (File f : parentDir.listFiles()) {
String ext = FilenameUtils.getExtension(f.getName());
if (ext.equals("gfa")) {
Text t = new Text(f.getAbsolutePath());
candidates.add(t);
}
}
}
mainController.setBackground("/background_images/loading.png");
if (!candidates.isEmpty()) {
showPopup(candidates, selectedFile, parentDir, "GFA");
} else {
mainController.addRecentNWK(selectedFile.getAbsolutePath());
mainController.initTree(selectedFile.getAbsolutePath());
}
}
/**
* Method to show the created NWK pop-up
*
* @param candidates all candidates which can be loaded next
* @param selectedFile the currently selected GFA File
* @param parentDir the Directory containing the chosen File
* @param type The type
*/
public static void showPopup(ArrayList<Text> candidates, File selectedFile, File parentDir, String type) {
Stage tempStage = new Stage();
ListView listView = new ListView();
fillList(listView, candidates);
handleTempStage(tempStage, type, listView);
if (type.toUpperCase().equals("NWK")) {
addGFAEventHandler(listView, selectedFile, tempStage);
} else if (type.toUpperCase().equals("GFA")) {
addNWKEventHandler(listView, selectedFile, parentDir, tempStage);
}
}
/**
* Method to add the needed EventHandler to the List of Files
*
* @param listView the List of Files
* @param selectedGFAFile the Files which is selected
* @param tempStage the currently showed Stage
*/
public static void addGFAEventHandler(ListView listView, File selectedGFAFile, Stage tempStage) {
listView.setOnMouseClicked(event -> {
Text file = (Text) listView.getSelectionModel().getSelectedItem();
File nwk = new File(file.getText());
tempStage.hide();
if (!mainController.isMetaDataLoaded()) {
createMetaDatapopup(selectedGFAFile, nwk);
} else {
mainController.addRecentNWK(nwk.getAbsolutePath());
mainController.initTree(nwk.getAbsolutePath());
mainController.addRecentGFA(selectedGFAFile.getAbsolutePath());
mainController.getGraphController().getGraph().getNodeMapFromFile(selectedGFAFile.getAbsolutePath());
mainController.initGraph();
createMenuWithSearch();
}
});
}
/**
* Method to create the MetaData Pop-up
*
* @param gfaFile the earlier chosen GFA-File
* @param nwkFile the earlier chosen NWK-File
*/
public static void createMetaDatapopup(File gfaFile, File nwkFile) {
ArrayList<Text> candidates = new ArrayList<>();
File parentDir = gfaFile.getParentFile();
if (parentDir.isDirectory()) {
File[] fileList = parentDir.listFiles();
if (fileList != null) {
for (File f : fileList) {
String ext = FilenameUtils.getExtension(f.getName());
if (ext.equals("xlsx")) {
Text t = new Text(f.getAbsolutePath());
candidates.add(t);
}
}
}
}
mainController.setBackground("/background_images/loading.png");
if (!candidates.isEmpty()) {
showMetaDataPopup(candidates, gfaFile, nwkFile, "metaData");
} else {
mainController.getGraphController().getGraph().getNodeMapFromFile(gfaFile.toString());
mainController.initGraph();
mainController.addRecentNWK(nwkFile.getAbsolutePath());
mainController.initTree(nwkFile.getAbsolutePath());
}
}
/**
* Method to create and show the MetaData Pop-up
*
* @param candidates all candidates that can be opened
* @param selectedGFA the earlier selected GFA-File
* @param selectedNWK the earlier selected NWK-File
* @param type the type
*/
public static void showMetaDataPopup(ArrayList<Text> candidates, File selectedGFA, File selectedNWK, String type) {
Stage tempStage = new Stage();
ListView listView = new ListView();
fillList(listView, candidates);
handleTempStage(tempStage, type, listView);
if (type.equals("metaData")) {
File[] files = new File[2];
files[0] = selectedGFA;
files[1] = selectedNWK;
addMetaDataEventHandler(listView, files, tempStage);
}
}
private static void fillList(ListView listView, ArrayList<Text> candidates) {
ObservableList<Text> list = FXCollections.observableArrayList();
listView.getStylesheets().add("/css/popup.css");
listView.setMinWidth(450);
listView.setPrefWidth(450);
listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
for (Text t : candidates) {
t.setWrappingWidth(listView.getPrefWidth());
t.getStyleClass().add("text");
}
list.addAll(candidates.stream().collect(Collectors.toList()));
listView.setItems(list);
}
/**
* Method to create the popup
*
* @param tempStage the Stage to show it on
* @param type the type of File we want to load
* @param listView the ListView to add the information to
*/
private static void handleTempStage(Stage tempStage, String type, ListView listView) {
Text text = new Text("Do you also want to load one of the following files? If not, exit.");
text.setWrappingWidth(listView.getPrefWidth());
text.getStyleClass().add("title");
VBox vBox = new VBox();
vBox.getChildren().addAll(text, listView);
vBox.getStylesheets().add("/css/popup.css");
vBox.getStyleClass().add("vBox");
Scene tempScene = new Scene(vBox);
tempStage.setScene(tempScene);
tempStage.initModality(Modality.APPLICATION_MODAL);
tempStage.setTitle(format("Load additional %s file", type));
tempStage.setResizable(false);
tempStage.show();
}
/**
* Method to add the needed EventHandler to the List of Files
*
* @param listView the List of Files
* @param selectedFile the Files which is selected
* @param parentDir the Directory in which the Files are
* @param tempStage the currently showed Stage
*/
public static void addNWKEventHandler(ListView listView, File selectedFile, File parentDir, Stage tempStage) {
listView.setOnMouseClicked(event -> {
File nwk = new File(listView.getSelectionModel().getSelectedItem().toString());
tempStage.hide();
if (!mainController.isMetaDataLoaded()) {
createMetaDatapopup(selectedFile, nwk);
} else {
mainController.getGraphController().getGraph().getNodeMapFromFile(nwk.getAbsolutePath());
mainController.initGraph();
mainController.addRecentNWK(selectedFile.getAbsolutePath());
mainController.initTree(selectedFile.getAbsolutePath());
mainController.addRecentGFA(nwk.getAbsolutePath());
createMenuWithSearchWithoutAnnotation();
}
});
}
/**
* Method to add EventHandlers to the MetaData Pop-uo
*
* @param listView the listView showing
* @param files the list of chosen Files
* @param tempStage the Stage of the shown window
*/
public static void addMetaDataEventHandler(ListView listView, File[] files, Stage tempStage) {
listView.setOnMouseClicked(event -> {
Text file = (Text) listView.getSelectionModel().getSelectedItem();
File meta = new File(file.getText());
mainController.initMetadata(meta.getAbsolutePath());
mainController.addRecentMetadata(meta.getAbsolutePath());
createMenuWithSearchWithoutAnnotation();
if (files[0] != null && files[1] != null) {
File gfaFile = files[0];
File nwkFile = files[1];
if (FilenameUtils.getExtension(gfaFile.getName()).equals("NWK")) {
mainController.initTree(gfaFile.getAbsolutePath());
mainController.addRecentNWK(gfaFile.getAbsolutePath());
mainController.getGraphController().getGraph().getNodeMapFromFile(nwkFile.getAbsolutePath());
mainController.initGraph();
mainController.addRecentGFA(nwkFile.getAbsolutePath());
} else {
mainController.initTree(nwkFile.getAbsolutePath());
mainController.addRecentNWK(nwkFile.getAbsolutePath());
mainController.getGraphController().getGraph().getNodeMapFromFile(gfaFile.getAbsolutePath());
mainController.initGraph();
mainController.addRecentGFA(gfaFile.getAbsolutePath());
}
}
tempStage.hide();
});
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser
*/
public static FileChooser createAnnotationChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Annotation File");
File selectedFile = directoryChooser.showOpenDialog(window);
mainController.initAnnotations(selectedFile.getAbsolutePath());
mainController.addRecentGFF(selectedFile.getAbsolutePath());
return directoryChooser;
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser
*/
public static FileChooser createMetadataChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Metadata File");
File selectedFile = directoryChooser.showOpenDialog(window);
mainController.initMetadata(selectedFile.getAbsolutePath());
mainController.addRecentMetadata(selectedFile.getAbsolutePath());
return directoryChooser;
}
/**
* Creates the menu including a search bar with the annotations search box.
*/
public static void createMenuWithSearch() {
mainController.createMenu(true, true);
}
/**
* Creates the menu including a search bar without the annotations search box.
*/
public static void createMenuWithSearchWithoutAnnotation() {
mainController.createMenu(true, false);
}
} | src/main/java/application/factories/WindowFactory.java | package application.factories;
import application.controllers.MainController;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.stream.Collectors;
import static java.lang.String.format;
/**
* WindowFactory class.
*
* @version 1.0
* @since 25-04-2016
*/
public final class WindowFactory {
static Rectangle2D screenSize;
static Stage window;
static MainController mainController;
static Scene scene;
/**
* Private class constructor.
*/
private WindowFactory() {
}
/**
* Create method for windows.
*
* @param m parent of the window
* @return the constructed window.
*/
public static Stage createWindow(MainController m) {
mainController = m;
window = new Stage();
scene = createScene(m.getRoot());
screenSize = Screen.getPrimary().getVisualBounds();
window.setWidth(screenSize.getWidth());
window.setHeight(screenSize.getHeight());
window.setMaxHeight(screenSize.getHeight());
window.setScene(scene);
window.show();
return window;
}
/**
* Method to create the scene.
*
* @param parent parent object for the scene.
* @return the constructed scene.
*/
public static Scene createScene(Parent parent) {
Scene scene = new Scene(parent);
return scene;
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser.
*/
public static FileChooser createGraphChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Graph File");
File selectedFile = directoryChooser.showOpenDialog(window);
mainController.addRecentGFA(selectedFile.getAbsolutePath());
File parentDir = selectedFile.getParentFile();
createGFApopup(parentDir, selectedFile);
return directoryChooser;
}
/**
* Method to create a pop-up when selecting a NWK File
*
* @param parentDir the current Directory
* @param selectedFile the selected File
*/
@SuppressFBWarnings
public static void createGFApopup(File parentDir, File selectedFile) {
ArrayList<Text> candidates = new ArrayList<>();
if (parentDir.isDirectory()) {
for (File f : parentDir.listFiles()) {
String ext = FilenameUtils.getExtension(f.getName());
if (ext.equals("nwk")) {
Text t = new Text(f.getAbsolutePath());
candidates.add(t);
}
}
}
mainController.setBackground("/background_images/loading.png");
if (!candidates.isEmpty()) {
showPopup(candidates, selectedFile, parentDir, "NWK");
} else {
mainController.getGraphController().getGraph().getNodeMapFromFile(selectedFile.toString());
mainController.initGraph();
}
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser
*/
public static FileChooser createTreeChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Tree File");
File selectedFile = directoryChooser.showOpenDialog(window);
File parentDir = selectedFile.getParentFile();
createNWKpopup(parentDir, selectedFile);
return directoryChooser;
}
/**
* Method the create a pop-up when choosing a GFA File
*
* @param parentDir the current Directory we're at
* @param selectedFile the selected File
*/
@SuppressFBWarnings
public static void createNWKpopup(File parentDir, File selectedFile) {
ArrayList<Text> candidates = new ArrayList<>();
if (parentDir.isDirectory()) {
for (File f : parentDir.listFiles()) {
String ext = FilenameUtils.getExtension(f.getName());
if (ext.equals("gfa")) {
Text t = new Text(f.getAbsolutePath());
candidates.add(t);
}
}
}
mainController.setBackground("/background_images/loading.png");
if (!candidates.isEmpty()) {
showPopup(candidates, selectedFile, parentDir, "GFA");
} else {
mainController.addRecentNWK(selectedFile.getAbsolutePath());
mainController.initTree(selectedFile.getAbsolutePath());
}
}
/**
* Method to show the created NWK pop-up
*
* @param candidates all candidates which can be loaded next
* @param selectedFile the currently selected GFA File
* @param parentDir the Directory containing the chosen File
* @param type The type
*/
public static void showPopup(ArrayList<Text> candidates, File selectedFile, File parentDir, String type) {
Stage tempStage = new Stage();
ListView listView = new ListView();
fillList(listView, candidates);
handleTempStage(tempStage, type, listView);
if (type.toUpperCase().equals("NWK")) {
addGFAEventHandler(listView, selectedFile, parentDir, tempStage);
} else if (type.toUpperCase().equals("GFA")) {
addNWKEventHandler(listView, selectedFile, parentDir, tempStage);
}
}
/**
* Method to add the needed EventHandler to the List of Files
*
* @param listView the List of Files
* @param selectedGFAFile the Files which is selected
* @param parentDir the Directory containing the chosen Files
* @param tempStage the currently showed Stage
*/
public static void addGFAEventHandler(ListView listView, File selectedGFAFile, File parentDir, Stage tempStage) {
listView.setOnMouseClicked(event -> {
Text file = (Text) listView.getSelectionModel().getSelectedItem();
File nwk = new File(file.getText());
tempStage.hide();
if (!mainController.isMetaDataLoaded()) {
createMetaDatapopup(selectedGFAFile, nwk, parentDir);
} else {
mainController.addRecentNWK(nwk.getAbsolutePath());
mainController.initTree(nwk.getAbsolutePath());
mainController.addRecentGFA(selectedGFAFile.getAbsolutePath());
mainController.getGraphController().getGraph().getNodeMapFromFile(selectedGFAFile.getAbsolutePath());
mainController.initGraph();
createMenuWithSearch();
}
});
}
/**
* Method to create the MetaData Pop-up
*
* @param gfaFile the earlier chosen GFA-File
* @param nwkFile the earlier chosen NWK-File
* @param parentDir the directory of the chosen Files
*/
public static void createMetaDatapopup(File gfaFile, File nwkFile, File parentDir) {
ArrayList<Text> candidates = new ArrayList<>();
if (parentDir.isDirectory()) {
File[] fileList = parentDir.listFiles();
if (fileList != null) {
for (File f : fileList) {
String ext = FilenameUtils.getExtension(f.getName());
if (ext.equals("xlsx")) {
Text t = new Text(f.getAbsolutePath());
candidates.add(t);
}
}
}
}
mainController.setBackground("/background_images/loading.png");
if (!candidates.isEmpty()) {
showMetaDataPopup(candidates, gfaFile, nwkFile, "metaData");
} else {
mainController.getGraphController().getGraph().getNodeMapFromFile(gfaFile.toString());
mainController.initGraph();
mainController.addRecentNWK(nwkFile.getAbsolutePath());
mainController.initTree(nwkFile.getAbsolutePath());
}
}
/**
* Method to create and show the MetaData Pop-up
*
* @param candidates all candidates that can be opened
* @param selectedGFA the earlier selected GFA-File
* @param selectedNWK the earlier selected NWK-File
* @param type the type
*/
public static void showMetaDataPopup(ArrayList<Text> candidates, File selectedGFA, File selectedNWK, String type) {
Stage tempStage = new Stage();
ListView listView = new ListView();
fillList(listView, candidates);
handleTempStage(tempStage, type, listView);
if (type.equals("metaData")) {
addMetaDataEventHandler(listView, selectedGFA, selectedNWK, tempStage);
}
}
private static void fillList(ListView listView, ArrayList<Text> candidates) {
ObservableList<Text> list = FXCollections.observableArrayList();
listView.getStylesheets().add("/css/popup.css");
listView.setMinWidth(450);
listView.setPrefWidth(450);
listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
for (Text t : candidates) {
t.setWrappingWidth(listView.getPrefWidth());
t.getStyleClass().add("text");
}
list.addAll(candidates.stream().collect(Collectors.toList()));
listView.setItems(list);
}
/**
* Method to create the popup
*
* @param tempStage the Stage to show it on
* @param type the type of File we want to load
* @param listView the ListView to add the information to
*/
private static void handleTempStage(Stage tempStage, String type, ListView listView) {
Text text = new Text("Do you also want to load one of the following files? If not, exit.");
text.setWrappingWidth(listView.getPrefWidth());
text.getStyleClass().add("title");
VBox vBox = new VBox();
vBox.getChildren().addAll(text, listView);
vBox.getStylesheets().add("/css/popup.css");
vBox.getStyleClass().add("vBox");
Scene tempScene = new Scene(vBox);
tempStage.setScene(tempScene);
tempStage.initModality(Modality.APPLICATION_MODAL);
tempStage.setTitle(format("Load additional %s file", type));
tempStage.setResizable(false);
tempStage.show();
}
/**
* Method to add the needed EventHandler to the List of Files
*
* @param listView the List of Files
* @param selectedFile the Files which is selected
* @param parentDir the Directory in which the Files are
* @param tempStage the currently showed Stage
*/
public static void addNWKEventHandler(ListView listView, File selectedFile, File parentDir, Stage tempStage) {
listView.setOnMouseClicked(event -> {
File nwk = new File(listView.getSelectionModel().getSelectedItem().toString());
tempStage.hide();
if (!mainController.isMetaDataLoaded()) {
createMetaDatapopup(selectedFile, nwk, parentDir);
} else {
mainController.getGraphController().getGraph().getNodeMapFromFile(nwk.getAbsolutePath());
mainController.initGraph();
mainController.addRecentNWK(selectedFile.getAbsolutePath());
mainController.initTree(selectedFile.getAbsolutePath());
mainController.addRecentGFA(nwk.getAbsolutePath());
createMenuWithSearchWithoutAnnotation();
}
});
}
/**
* Method to add EventHandlers to the MetaData Pop-uo
*
* @param listView the listView showing
* @param gfaFile the chosen GFA-File
* @param nwkFile the chosen NWK-File
* @param tempStage the Stage of the shown window
*/
public static void addMetaDataEventHandler(ListView listView, File gfaFile, File nwkFile, Stage tempStage) {
listView.setOnMouseClicked(event -> {
Text file = (Text) listView.getSelectionModel().getSelectedItem();
File meta = new File(file.getText());
mainController.initMetadata(meta.getAbsolutePath());
mainController.addRecentMetadata(meta.getAbsolutePath());
createMenuWithSearchWithoutAnnotation();
if (FilenameUtils.getExtension(gfaFile.getName()).equals("NWK")) {
mainController.initTree(gfaFile.getAbsolutePath());
mainController.addRecentNWK(gfaFile.getAbsolutePath());
mainController.getGraphController().getGraph().getNodeMapFromFile(nwkFile.getAbsolutePath());
mainController.initGraph();
mainController.addRecentGFA(nwkFile.getAbsolutePath());
} else {
mainController.initTree(nwkFile.getAbsolutePath());
mainController.addRecentNWK(nwkFile.getAbsolutePath());
mainController.getGraphController().getGraph().getNodeMapFromFile(gfaFile.getAbsolutePath());
mainController.initGraph();
mainController.addRecentGFA(gfaFile.getAbsolutePath());
}
tempStage.hide();
});
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser
*/
public static FileChooser createAnnotationChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Annotation File");
File selectedFile = directoryChooser.showOpenDialog(window);
mainController.initAnnotations(selectedFile.getAbsolutePath());
mainController.addRecentGFF(selectedFile.getAbsolutePath());
return directoryChooser;
}
/**
* Method that creates a directoryChooser.
*
* @return the directoryChooser
*/
public static FileChooser createMetadataChooser() {
FileChooser directoryChooser = new FileChooser();
directoryChooser.setTitle("Select Metadata File");
File selectedFile = directoryChooser.showOpenDialog(window);
mainController.initMetadata(selectedFile.getAbsolutePath());
mainController.addRecentMetadata(selectedFile.getAbsolutePath());
return directoryChooser;
}
/**
* Creates the menu including a search bar with the annotations search box.
*/
public static void createMenuWithSearch() {
mainController.createMenu(true, true);
}
/**
* Creates the menu including a search bar without the annotations search box.
*/
public static void createMenuWithSearchWithoutAnnotation() {
mainController.createMenu(true, false);
}
} | Fix Pull Request comments
| src/main/java/application/factories/WindowFactory.java | Fix Pull Request comments | <ide><path>rc/main/java/application/factories/WindowFactory.java
<ide> handleTempStage(tempStage, type, listView);
<ide>
<ide> if (type.toUpperCase().equals("NWK")) {
<del> addGFAEventHandler(listView, selectedFile, parentDir, tempStage);
<add> addGFAEventHandler(listView, selectedFile, tempStage);
<ide> } else if (type.toUpperCase().equals("GFA")) {
<ide> addNWKEventHandler(listView, selectedFile, parentDir, tempStage);
<ide> }
<ide> *
<ide> * @param listView the List of Files
<ide> * @param selectedGFAFile the Files which is selected
<del> * @param parentDir the Directory containing the chosen Files
<ide> * @param tempStage the currently showed Stage
<ide> */
<del> public static void addGFAEventHandler(ListView listView, File selectedGFAFile, File parentDir, Stage tempStage) {
<add> public static void addGFAEventHandler(ListView listView, File selectedGFAFile, Stage tempStage) {
<ide> listView.setOnMouseClicked(event -> {
<ide> Text file = (Text) listView.getSelectionModel().getSelectedItem();
<ide> File nwk = new File(file.getText());
<ide> tempStage.hide();
<ide>
<ide> if (!mainController.isMetaDataLoaded()) {
<del> createMetaDatapopup(selectedGFAFile, nwk, parentDir);
<add> createMetaDatapopup(selectedGFAFile, nwk);
<ide> } else {
<ide> mainController.addRecentNWK(nwk.getAbsolutePath());
<ide> mainController.initTree(nwk.getAbsolutePath());
<ide> *
<ide> * @param gfaFile the earlier chosen GFA-File
<ide> * @param nwkFile the earlier chosen NWK-File
<del> * @param parentDir the directory of the chosen Files
<del> */
<del> public static void createMetaDatapopup(File gfaFile, File nwkFile, File parentDir) {
<add> */
<add> public static void createMetaDatapopup(File gfaFile, File nwkFile) {
<ide> ArrayList<Text> candidates = new ArrayList<>();
<add> File parentDir = gfaFile.getParentFile();
<ide> if (parentDir.isDirectory()) {
<ide> File[] fileList = parentDir.listFiles();
<ide> if (fileList != null) {
<ide> handleTempStage(tempStage, type, listView);
<ide>
<ide> if (type.equals("metaData")) {
<del> addMetaDataEventHandler(listView, selectedGFA, selectedNWK, tempStage);
<add> File[] files = new File[2];
<add> files[0] = selectedGFA;
<add> files[1] = selectedNWK;
<add> addMetaDataEventHandler(listView, files, tempStage);
<ide> }
<ide> }
<ide>
<ide> tempStage.hide();
<ide>
<ide> if (!mainController.isMetaDataLoaded()) {
<del> createMetaDatapopup(selectedFile, nwk, parentDir);
<add> createMetaDatapopup(selectedFile, nwk);
<ide> } else {
<ide> mainController.getGraphController().getGraph().getNodeMapFromFile(nwk.getAbsolutePath());
<ide> mainController.initGraph();
<ide> * Method to add EventHandlers to the MetaData Pop-uo
<ide> *
<ide> * @param listView the listView showing
<del> * @param gfaFile the chosen GFA-File
<del> * @param nwkFile the chosen NWK-File
<add> * @param files the list of chosen Files
<ide> * @param tempStage the Stage of the shown window
<ide> */
<del> public static void addMetaDataEventHandler(ListView listView, File gfaFile, File nwkFile, Stage tempStage) {
<add> public static void addMetaDataEventHandler(ListView listView, File[] files, Stage tempStage) {
<ide> listView.setOnMouseClicked(event -> {
<ide> Text file = (Text) listView.getSelectionModel().getSelectedItem();
<ide> File meta = new File(file.getText());
<ide> mainController.addRecentMetadata(meta.getAbsolutePath());
<ide> createMenuWithSearchWithoutAnnotation();
<ide>
<del> if (FilenameUtils.getExtension(gfaFile.getName()).equals("NWK")) {
<del> mainController.initTree(gfaFile.getAbsolutePath());
<del> mainController.addRecentNWK(gfaFile.getAbsolutePath());
<del> mainController.getGraphController().getGraph().getNodeMapFromFile(nwkFile.getAbsolutePath());
<del> mainController.initGraph();
<del> mainController.addRecentGFA(nwkFile.getAbsolutePath());
<del> } else {
<del> mainController.initTree(nwkFile.getAbsolutePath());
<del> mainController.addRecentNWK(nwkFile.getAbsolutePath());
<del> mainController.getGraphController().getGraph().getNodeMapFromFile(gfaFile.getAbsolutePath());
<del> mainController.initGraph();
<del> mainController.addRecentGFA(gfaFile.getAbsolutePath());
<add> if (files[0] != null && files[1] != null) {
<add> File gfaFile = files[0];
<add> File nwkFile = files[1];
<add>
<add> if (FilenameUtils.getExtension(gfaFile.getName()).equals("NWK")) {
<add> mainController.initTree(gfaFile.getAbsolutePath());
<add> mainController.addRecentNWK(gfaFile.getAbsolutePath());
<add> mainController.getGraphController().getGraph().getNodeMapFromFile(nwkFile.getAbsolutePath());
<add> mainController.initGraph();
<add> mainController.addRecentGFA(nwkFile.getAbsolutePath());
<add> } else {
<add> mainController.initTree(nwkFile.getAbsolutePath());
<add> mainController.addRecentNWK(nwkFile.getAbsolutePath());
<add> mainController.getGraphController().getGraph().getNodeMapFromFile(gfaFile.getAbsolutePath());
<add> mainController.initGraph();
<add> mainController.addRecentGFA(gfaFile.getAbsolutePath());
<add> }
<ide> }
<ide>
<ide> tempStage.hide(); |
|
Java | mit | error: pathspec 'src/main/java/alokawi/rxjava/core/SubscriberExample.java' did not match any file(s) known to git
| cf495c18c3101363787f29625b03b23b3d4422ff | 1 | alokawi/working-with-rxjava | /**
*
*/
package alokawi.rxjava.core;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import io.reactivex.Flowable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
/**
* @author alokkumar
*
*/
public class SubscriberExample {
/**
* @param args
*/
public static void main(String[] args) {
Flowable.fromArray(1, 2, 3, 4).subscribe(
i -> System.out.printf("Entry %d\n", i),
e -> System.err.printf("Failed to process: %s\n", e),
() -> System.out.println("Done")
);
//Consumer { void accept(T t); }
Flowable.fromArray(1, 2, 3, 4).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer t) throws Exception {
System.out.printf("Entry %d\n", t);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable t) throws Exception {
System.err.printf("Failed to process: %s\n", t);
}
}, new Action() {
@Override
public void run() throws Exception {
System.out.println("Done");
}
});
//Subscriber { void onNext(T t); void onError(Throwable t); void onComplete(); }
Subscriber<Integer> subscriber = new Subscriber<Integer>() {
@Override
public void onSubscribe(Subscription s) {
}
@Override
public void onNext(Integer t) {
System.out.printf("Entry %d\n", t);
}
@Override
public void onError(Throwable t) {
System.err.printf("Failed to process: %s\n", t);
}
@Override
public void onComplete() {
System.out.println("Done");
}
};
Flowable.fromArray(1, 2, 3, 4).subscribe(subscriber);
}
}
| src/main/java/alokawi/rxjava/core/SubscriberExample.java | Add RxJava Subscriber example (#4)
| src/main/java/alokawi/rxjava/core/SubscriberExample.java | Add RxJava Subscriber example (#4) | <ide><path>rc/main/java/alokawi/rxjava/core/SubscriberExample.java
<add>/**
<add> *
<add> */
<add>package alokawi.rxjava.core;
<add>
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>
<add>import io.reactivex.Flowable;
<add>import io.reactivex.functions.Action;
<add>import io.reactivex.functions.Consumer;
<add>
<add>/**
<add> * @author alokkumar
<add> *
<add> */
<add>public class SubscriberExample {
<add>
<add> /**
<add> * @param args
<add> */
<add> public static void main(String[] args) {
<add> Flowable.fromArray(1, 2, 3, 4).subscribe(
<add> i -> System.out.printf("Entry %d\n", i),
<add> e -> System.err.printf("Failed to process: %s\n", e),
<add> () -> System.out.println("Done")
<add> );
<add>
<add> //Consumer { void accept(T t); }
<add>
<add> Flowable.fromArray(1, 2, 3, 4).subscribe(new Consumer<Integer>() {
<add> @Override
<add> public void accept(Integer t) throws Exception {
<add> System.out.printf("Entry %d\n", t);
<add> }
<add> }, new Consumer<Throwable>() {
<add> @Override
<add> public void accept(Throwable t) throws Exception {
<add> System.err.printf("Failed to process: %s\n", t);
<add> }
<add> }, new Action() {
<add> @Override
<add> public void run() throws Exception {
<add> System.out.println("Done");
<add> }
<add> });
<add>
<add>
<add> //Subscriber { void onNext(T t); void onError(Throwable t); void onComplete(); }
<add>
<add> Subscriber<Integer> subscriber = new Subscriber<Integer>() {
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add>
<add> }
<add>
<add> @Override
<add> public void onNext(Integer t) {
<add> System.out.printf("Entry %d\n", t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> System.err.printf("Failed to process: %s\n", t);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> System.out.println("Done");
<add> }
<add>
<add> };
<add> Flowable.fromArray(1, 2, 3, 4).subscribe(subscriber);
<add> }
<add>
<add>} |
|
JavaScript | mpl-2.0 | b1833b1faa37753c7bd7ce7693aad4a0e37d4d4a | 0 | mstange/cleopatra,mstange/cleopatra | #!/usr/bin/env node
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This script will sync the l10 branch with the main branch.
// You can run this script with `node bin/l10n-sync.js` but you don't necessarily
// have to be at the project root directory to run it.
// Run with '-y' to automatically skip the prompts.
// @flow
const cp = require('child_process');
const readline = require('readline');
const { promisify } = require('util');
/*::
type ExecFilePromiseResult = {|
stdout: string | Buffer,
stderr: string | Buffer
|};
type ExecFile = (
command: string,
args?: string[]
) => Promise<ExecFilePromiseResult>;
*/
const execFile /*: ExecFile */ = promisify(cp.execFile);
const DATE_FORMAT = new Intl.DateTimeFormat('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric',
});
let SKIP_PROMPTS = false;
const MERGE_COMMIT_MESSAGE = '�� Daily sync: main -> l10n';
/**
* Logs the command to be executed first, and spawns a shell then executes the
* command. Returns the stdout of the executed command.
*
* @throws Will throw an error if executed command fails.
*/
async function logAndExec(
executable /*: string */,
...args /*: string[] */
) /*: Promise<ExecFilePromiseResult> */ {
console.log('[exec]', executable, args.join(' '));
const result = await execFile(executable, args);
if (result.stdout.length) {
console.log('stdout:\n' + result.stdout.toString());
}
if (result.stderr.length) {
console.log('stderr:\n' + result.stderr.toString());
}
return result;
}
/**
* Logs the command to be executed first, and executes a series of shell commands
* and pipes the stdout of them to the next one. In the end, returns the stdout
* of the last piped command.
*
* @throws Will throw an error if one of the executed commands fails.
*/
function logAndPipeExec(...commands /*: string[][] */) /*: string */ {
console.log('[exec]', commands.map(command => command.join(' ')).join(' | '));
let prevOutput = '';
for (const command of commands) {
const [executable, ...args] = command;
prevOutput = cp
.execFileSync(executable, args, { input: prevOutput })
.toString();
}
const output = prevOutput.toString();
if (output.length) {
console.log('stdout:\n' + output.toString());
}
return output;
}
/**
* Pause with a message and wait for the enter as a confirmation.
* The prompt will not be displayed if the `-y` argument is given to the script.
* This is mainly used by the CircleCI automation.
*/
async function pauseWithMessageIfNecessary(
message /*: string */ = ''
) /*: Promise<void> */ {
if (SKIP_PROMPTS) {
return;
}
if (message.length > 0) {
message += '\n';
}
message += 'Press ENTER when youʼre ready...';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
await promisify(rl.question).call(rl, message);
rl.close();
}
/**
* Check if Git workspace is clean.
*
* @throws Will throw an error if workspace is not clean.
*/
async function checkIfWorkspaceClean() /*: Promise<void> */ {
console.log('>>> Checking if the workspace is clean for the operations.');
// git status --porcelain --ignore-submodules -unormal
const statusResult = await logAndExec(
'git',
'status',
'--porcelain',
'--ignore-submodules',
'-unormal'
);
if (statusResult.stdout.length || statusResult.stderr.length) {
throw new Error(
'Your workspace is not clean. Please commit or stash your changes.'
);
}
console.log('Workspace is clean.');
}
/**
* Finds the Git upstream remote and returns it.
*
* @throws Will throw an error if it can't find an upstream remote.
*/
async function findUpstream() /*: Promise<string> */ {
console.log('>>> Finding the upstream remote.');
try {
const gitRemoteResult = await logAndExec('git', 'remote', '-v');
if (gitRemoteResult.stderr.length) {
throw new Error(`'git remote' failed to run.`);
}
const gitRemoteOutput = gitRemoteResult.stdout.toString();
const remotes = gitRemoteOutput.split('\n');
const upstreamLine = remotes.find(line =>
// Change this regexp to make it work with your fork for debugging purpose.
/devtools-html\/perf.html|firefox-devtools\/profiler/.test(line)
);
if (upstreamLine === undefined) {
throw new Error(`'upstreamLine' is undefined.`);
}
const upstream = upstreamLine.split('\t')[0];
return upstream;
} catch (error) {
console.error(error);
throw new Error(
"Couldn't find the upstream remote. Is it well configured?\n" +
"We're looking for either devtools-html/perf.html or firefox-devtools/profiler."
);
}
}
/**
* Compares the `compareBranch` with `baseBranch` and checks the changed files.
* Fails if the `compareBranch` has changes from the files that doesn't match
* the `allowedRegexp`.
*
* @throws Will throw an error if `compareBranch` has changes from the files
* that doesn't match the `allowedRegexp`.
*/
async function checkAllowedPaths(
{
upstream,
compareBranch,
baseBranch,
allowedRegexp,
} /*:
{|
upstream: string,
compareBranch: string,
baseBranch: string ,
allowedRegexp: RegExp
|}
*/
) {
console.log(
`>>> Checking if ${compareBranch} branch has changes from the files that are not allowed.`
);
// git rev-list --no-merges upstream/baseBranch..upstream/compareBranch | git diff-tree --stdin --no-commit-id --name-only -r
const changedFilesResult = logAndPipeExec(
[
'git',
'rev-list',
'--no-merges',
`${upstream}/${baseBranch}..${upstream}/${compareBranch}`,
],
['git', 'diff-tree', '--stdin', '--no-commit-id', '--name-only', '-r']
);
const changedFiles = changedFilesResult.split('\n');
for (const file of changedFiles) {
if (file.length > 0 && !allowedRegexp.test(file)) {
throw new Error(
`${compareBranch} branch includes changes from the files that are not ` +
`allowed: ${file}`
);
}
}
}
/**
* This is a simple helper function that returns the friendly English versions
* of how many times that occurs.
*
* It's a pretty simple hack and would be good to have a more sophisticated
* (localized?) API function. But it's not really worth for a deployment only
* script.
*/
function fewTimes(count /*: number */) /*: string */ {
switch (count) {
case 1:
return 'once';
case 2:
return 'twice';
default:
return `${count} times`;
}
}
/**
* Tries to sync the l10n branch and retries for 3 times if it fails to sync.
*
* @throws Will throw an error if it fails to sync for more than 3 times.
*/
async function tryToSync(upstream /*: string */) /*: Promise<void> */ {
console.log('>>> Syncing the l10n branch with main.');
// RegExp for matching only the vendored locales.
// It matches the files in `locales` directory but excludes `en-US` which is the
// main locale we edit. For example:
// ALLOWED: locales/it/app.ftl
// DISALLOWED: locales/en-US/app.ftl
// DISALLOWED: src/index.js
const vendoredLocalesPath = /^locales[\\/](?!en-US[\\/])/;
// RegExp for matching anything but the vendored locales.
// It matches the files that are not in the `locales` directory EXCEPT the
// `locales/en-US/` directory which is the main locale we edit. For example:
// ALLOWED: locales/en-US/app.ftl
// ALLOWED: src/index.js
// DISALLOWED: locales/it/app.ftl
const nonVendoredLocalesPath = /^(?:locales[\\/]en-US[\\/]|(?!locales[\\/]))/;
// We have a total try count to re-try to sync a few more time if the previous
// try fails. This can occur when someone else commits to l10n branch while we
// are syncing. In that case, `git push` will fail and we'll pull the latest
// changes and try again. Nevertheless, we should have a hard cap on the try
// count for safety.
const totalTryCount = 3;
let error /*: Error | null */ = null;
let tryCount = 0;
// Try to sync and retry for `totalTryCount` times if it fails.
do {
try {
if (tryCount > 0) {
console.warn(
'Syncing the l10n branch has failed.\n' +
'This may be due to a new commit during this operation. Trying again.\n' +
`Tried ${fewTimes(tryCount)} out of ${totalTryCount}.`
);
}
console.log(`>>> Fetching upstream ${upstream}.`);
await logAndExec('git', 'fetch', upstream);
// First, check if the l10n branch contains only changes in `locales` directory.
await checkAllowedPaths({
upstream,
compareBranch: 'l10n',
baseBranch: 'main',
allowedRegexp: vendoredLocalesPath,
});
// Second, check if the main branch contains changes except the translated locales.
await checkAllowedPaths({
upstream,
compareBranch: 'main',
baseBranch: 'l10n',
allowedRegexp: nonVendoredLocalesPath,
});
console.log('>>> Merging main to l10n.');
await logAndExec('git', 'checkout', `${upstream}/l10n`);
const currentDate = DATE_FORMAT.format(new Date());
await logAndExec(
'git',
'merge',
`${upstream}/main`,
'-m',
`${MERGE_COMMIT_MESSAGE} (${currentDate})`,
// Force the merge command to create a merge commit instead of a fast-forward.
'--no-ff'
);
console.log(`>>> Pushing to ${upstream}'s l10n branch.`);
await pauseWithMessageIfNecessary();
await logAndExec('git', 'push', '--no-verify', upstream, 'HEAD:l10n');
console.log('>>> Going back to your previous banch.');
await logAndExec('git', 'checkout', '-');
// Clear out the error after everything is done, in case this is a retry.
error = null;
} catch (e) {
error = e;
}
tryCount++;
} while (error !== null && tryCount < totalTryCount);
if (error) {
console.error(
`Tried to sync the l10n branch ${fewTimes(totalTryCount)} but failed.`
);
throw error;
}
}
/**
* Main function to be executed in the global scope.
*
* @throws Will throw an error if any of the functions it calls throw.
*/
async function main() /*: Promise<void> */ {
const args = process.argv.slice(2);
if (args.includes('-y')) {
SKIP_PROMPTS = true;
}
const upstream = await findUpstream();
await checkIfWorkspaceClean();
console.log(
`This script will sync the branch 'l10n' on the remote '${upstream}' with the branch 'main'.`
);
await pauseWithMessageIfNecessary('Are you sure?');
await tryToSync(upstream);
console.log('>>> Done!');
}
main().catch((error /*: Error */) => {
// Print the error to the console and exit if an error is caught.
console.error(error);
process.exitCode = 1;
});
| bin/l10n-sync.js | #!/usr/bin/env node
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This script will sync the l10 branch with the main branch.
// You can run this script with `node bin/l10n-sync.js` but you don't necessarily
// have to be at the project root directory to run it.
// Run with '-y' to automatically skip the prompts.
// @flow
const cp = require('child_process');
const readline = require('readline');
const { promisify } = require('util');
/*::
type ExecFilePromiseResult = {|
stdout: string | Buffer,
stderr: string | Buffer
|};
type ExecFile = (
command: string,
args?: string[]
) => Promise<ExecFilePromiseResult>;
*/
const execFile /*: ExecFile */ = promisify(cp.execFile);
const DATE_FORMAT = new Intl.DateTimeFormat('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric',
});
let SKIP_PROMPTS = false;
const MERGE_COMMIT_MESSAGE = '�� Daily sync: main -> l10n';
/**
* Logs the command to be executed first, and spawns a shell then executes the
* command. Returns the stdout of the executed command.
*
* @throws Will throw an error if executed command fails.
*/
async function logAndExec(
executable /*: string */,
...args /*: string[] */
) /*: Promise<ExecFilePromiseResult> */ {
console.log('[exec]', executable, args.join(' '));
const result = await execFile(executable, args);
if (result.stdout.length) {
console.log('stdout:\n' + result.stdout.toString());
}
if (result.stderr.length) {
console.log('stderr:\n' + result.stderr.toString());
}
return result;
}
/**
* Logs the command to be executed first, and executes a series of shell commands
* and pipes the stdout of them to the next one. In the end, returns the stdout
* of the last piped command.
*
* @throws Will throw an error if one of the executed commands fails.
*/
function logAndPipeExec(...commands /*: string[][] */) /*: string */ {
console.log('[exec]', commands.map(command => command.join(' ')).join(' | '));
let prevOutput = '';
for (const command of commands) {
const [executable, ...args] = command;
prevOutput = cp
.execFileSync(executable, args, { input: prevOutput })
.toString();
}
const output = prevOutput.toString();
if (output.length) {
console.log('stdout:\n' + output.toString());
}
return output;
}
/**
* Pause with a message and wait for the enter as a confirmation.
* The prompt will not be displayed if the `-y` argument is given to the script.
* This is mainly used by the CircleCI automation.
*/
async function pauseWithMessageIfNecessary(
message /*: string */ = ''
) /*: Promise<void> */ {
if (SKIP_PROMPTS) {
return;
}
if (message.length > 0) {
message += '\n';
}
message += 'Press ENTER when youʼre ready...';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
await promisify(rl.question).call(rl, message);
rl.close();
}
/**
* Check if Git workspace is clean.
*
* @throws Will throw an error if workspace is not clean.
*/
async function checkIfWorkspaceClean() /*: Promise<void> */ {
console.log('>>> Checking if the workspace is clean for the operations.');
// git status --porcelain --ignore-submodules -unormal
const statusResult = await logAndExec(
'git',
'status',
'--porcelain',
'--ignore-submodules',
'-unormal'
);
if (statusResult.stdout.length || statusResult.stderr.length) {
throw new Error(
'Your workspace is not clean. Please commit or stash your changes.'
);
}
console.log('Workspace is clean.');
}
/**
* Finds the Git upstream remote and returns it.
*
* @throws Will throw an error if it can't find an upstream remote.
*/
async function findUpstream() /*: Promise<string> */ {
console.log('>>> Finding the upstream remote.');
try {
const gitRemoteResult = await logAndExec('git', 'remote', '-v');
if (gitRemoteResult.stderr.length) {
throw new Error(`'git remote' failed to run.`);
}
const gitRemoteOutput = gitRemoteResult.stdout.toString();
const remotes = gitRemoteOutput.split('\n');
const upstreamLine = remotes.find(line =>
// Change this regexp to make it work with your fork for debugging purpose.
/devtools-html\/perf.html|firefox-devtools\/profiler/.test(line)
);
if (upstreamLine === undefined) {
throw new Error(`'upstreamLine' is undefined.`);
}
const upstream = upstreamLine.split('\t')[0];
return upstream;
} catch (error) {
console.error(error);
throw new Error(
"Couldn't find the upstream remote. Is it well configured?\n" +
"We're looking for either devtools-html/perf.html or firefox-devtools/profiler."
);
}
}
/**
* Compares the `compareBranch` with `baseBranch` and checks the changed files.
* Fails if the `compareBranch` has changes from the files that doesn't match
* the `allowedRegexp`.
*
* @throws Will throw an error if `compareBranch` has changes from the files
* that doesn't match the `allowedRegexp`.
*/
async function checkAllowedPaths(
{
upstream,
compareBranch,
baseBranch,
allowedRegexp,
} /*:
{|
upstream: string,
compareBranch: string,
baseBranch: string ,
allowedRegexp: RegExp
|}
*/
) {
console.log(
`>>> Checking if ${compareBranch} branch has changes from the files that are not allowed.`
);
// git rev-list --no-merges upstream/baseBranch..upstream/compareBranch | git diff-tree --stdin --no-commit-id --name-only -r
const changedFilesResult = logAndPipeExec(
[
'git',
'rev-list',
'--no-merges',
`${upstream}/${baseBranch}..${upstream}/${compareBranch}`,
],
['git', 'diff-tree', '--stdin', '--no-commit-id', '--name-only', '-r']
);
const changedFiles = changedFilesResult.split('\n');
for (const file of changedFiles) {
if (file.length > 0 && !allowedRegexp.test(file)) {
throw new Error(
`${compareBranch} branch includes changes from the files that are not ` +
`allowed: ${file}`
);
}
}
}
/**
* This is a simple helper function that returns the friendly English versions
* of how many times that occurs.
*
* It's a pretty simple hack and would be good to have a more sophisticated
* (localized?) API function. But it's not really worth for a deployment only
* script.
*/
function fewTimes(count /*: number */) /*: string */ {
switch (count) {
case 1:
return 'once';
case 2:
return 'twice';
default:
return `${count} times`;
}
}
/**
* Tries to sync the l10n branch and retries for 3 times if it fails to sync.
*
* @throws Will throw an error if it fails to sync for more than 3 times.
*/
async function tryToSync(upstream /*: string */) /*: Promise<void> */ {
console.log('>>> Syncing the l10n branch with main.');
// RegExp for matching only the vendored locales.
// It matches the files in `locales` directory but excludes `en-US` which is the
// main locale we edit. For example:
// ALLOWED: locales/it/app.ftl
// DISALLOWED: locales/en-US/app.ftl
// DISALLOWED: src/index.js
const vendoredLocalesPath = /^locales[\\/](?!en-US[\\/])/;
// RegExp for matching anything but the vendored locales.
// It matches the files that are not in the `locales` directory EXCEPT the
// `locales/en-US/` directory which is the main locale we edit. For example:
// ALLOWED: locales/en-US/app.ftl
// ALLOWED: src/index.js
// DISALLOWED: locales/it/app.ftl
const nonVendoredLocalesPath = /^(?:locales[\\/]en-US[\\/]|(?!locales[\\/]))/;
// We have a total try count to re-try to sync a few more time if the previous
// try fails. This can occur when someone else commits to l10n branch while we
// are syncing. In that case, `git push` will fail and we'll pull the latest
// changes and try again. Nevertheless, we should have a hard cap on the try
// count for safety.
const totalTryCount = 3;
let error /*: Error | null */ = null;
let tryCount = 0;
// Try to sync and retry for `totalTryCount` times if it fails.
do {
try {
if (tryCount > 0) {
console.warn(
'Syncing the l10n branch has failed.\n' +
'This may be due to a new commit during this operation. Trying again.\n' +
`Tried ${fewTimes(tryCount)} out of ${totalTryCount}.`
);
}
console.log(`>>> Fetching upstream ${upstream}.`);
await logAndExec('git', 'fetch', upstream);
// First, check if the l10n branch contains only changes in `locales` directory.
await checkAllowedPaths({
upstream,
compareBranch: 'l10n',
baseBranch: 'main',
allowedRegexp: vendoredLocalesPath,
});
// Second, check if the main branch contains changes except the translated locales.
await checkAllowedPaths({
upstream,
compareBranch: 'main',
baseBranch: 'l10n',
allowedRegexp: nonVendoredLocalesPath,
});
console.log('>>> Merging main to l10n.');
await logAndExec('git', 'checkout', `${upstream}/l10n`);
const currentDate = DATE_FORMAT.format(new Date());
await logAndExec(
'git',
'merge',
`${upstream}/main`,
'-m',
`${MERGE_COMMIT_MESSAGE} (${currentDate})`
);
console.log(`>>> Pushing to ${upstream}'s l10n branch.`);
await pauseWithMessageIfNecessary();
await logAndExec('git', 'push', '--no-verify', upstream, 'HEAD:l10n');
console.log('>>> Going back to your previous banch.');
await logAndExec('git', 'checkout', '-');
// Clear out the error after everything is done, in case this is a retry.
error = null;
} catch (e) {
error = e;
}
tryCount++;
} while (error !== null && tryCount < totalTryCount);
if (error) {
console.error(
`Tried to sync the l10n branch ${fewTimes(totalTryCount)} but failed.`
);
throw error;
}
}
/**
* Main function to be executed in the global scope.
*
* @throws Will throw an error if any of the functions it calls throw.
*/
async function main() /*: Promise<void> */ {
const args = process.argv.slice(2);
if (args.includes('-y')) {
SKIP_PROMPTS = true;
}
const upstream = await findUpstream();
await checkIfWorkspaceClean();
console.log(
`This script will sync the branch 'l10n' on the remote '${upstream}' with the branch 'main'.`
);
await pauseWithMessageIfNecessary('Are you sure?');
await tryToSync(upstream);
console.log('>>> Done!');
}
main().catch((error /*: Error */) => {
// Print the error to the console and exit if an error is caught.
console.error(error);
process.exitCode = 1;
});
| Force the merge command to create a merge commit instead of a fast-forward
| bin/l10n-sync.js | Force the merge command to create a merge commit instead of a fast-forward | <ide><path>in/l10n-sync.js
<ide> 'merge',
<ide> `${upstream}/main`,
<ide> '-m',
<del> `${MERGE_COMMIT_MESSAGE} (${currentDate})`
<add> `${MERGE_COMMIT_MESSAGE} (${currentDate})`,
<add> // Force the merge command to create a merge commit instead of a fast-forward.
<add> '--no-ff'
<ide> );
<ide>
<ide> console.log(`>>> Pushing to ${upstream}'s l10n branch.`); |
|
JavaScript | mit | 0930b084543a55d8f9d8681ddd4fd17d6787b0c7 | 0 | kissio/kiss.io | 'use strict';
/**
* Module dependencies.
*/
var http = require('http');
var read = require('fs').readFileSync;
var engine = require('engine.io');
var client = require('socket.io-client');
var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Socket.IO client source.
*/
var clientSource = read(require.resolve('socket.io-client/socket.io.js'), 'utf-8');
/**
* Server constructor.
*
* @param {http.Server|Number|Object} srv http server, port or options
* @param {Object} opts
* @api public
*/
function Server(srv, opts)
{
if (!(this instanceof Server))
{
if(!Server.singleton)
{
Server.singleton = new Server(srv, opts);
}
return Server.singleton;
}
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
}
/**
* Server request verification function, that checks for allowed origins
*
* @param {http.IncomingMessage} req request
* @param {Function} fn callback to be called with the result: `fn(err, success)`
*/
Server.prototype.checkRequest = function(req, fn) {
var origin = req.headers.origin || req.headers.referer;
// file:// URLs produce a null Origin which can't be authorized via echo-back
if ('null' == origin || null == origin) origin = '*';
if (!!origin && typeof(this._origins) == 'function') return this._origins(origin, fn);
if (this._origins.indexOf('*:*') !== -1) return fn(null, true);
if (origin) {
try {
var parts = url.parse(origin);
var defaultPort = 'https:' == parts.protocol ? 443 : 80;
parts.port = parts.port != null
? parts.port
: defaultPort;
var ok =
~this._origins.indexOf(parts.hostname + ':' + parts.port) ||
~this._origins.indexOf(parts.hostname + ':*') ||
~this._origins.indexOf('*:' + parts.port);
return fn(null, !!ok);
} catch (ex) {
}
}
fn(null, false);
};
/**
* Sets/gets whether client code is being served.
*
* @param {Boolean} v whether to serve client code
* @return {Server|Boolean} self when setting or value when getting
* @api public
*/
Server.prototype.serveClient = function(v){
if (!arguments.length) return this._serveClient;
this._serveClient = v;
return this;
};
/**
* Old settings for backwards compatibility
*/
var oldSettings = {
"transports": "transports",
"heartbeat timeout": "pingTimeout",
"heartbeat interval": "pingInterval",
"destroy buffer size": "maxHttpBufferSize"
};
/**
* Backwards compatiblity.
*
* @api public
*/
Server.prototype.set = function(key, val){
if ('authorization' == key && val) {
this.use(function(socket, next) {
val(socket.request, function(err, authorized) {
if (err) return next(new Error(err));
if (!authorized) return next(new Error('Not authorized'));
next();
});
});
} else if ('origins' == key && val) {
this.origins(val);
} else if ('resource' == key) {
this.path(val);
} else if (oldSettings[key] && this.eio[oldSettings[key]]) {
this.eio[oldSettings[key]] = val;
} else {
console.error('Option %s is not valid. Please refer to the README.', key);
}
return this;
};
/**
* Sets the client serving path.
*
* @param {String} v pathname
* @return {Server|String} self when setting or value when getting
* @api public
*/
Server.prototype.path = function(v){
if (!arguments.length) return this._path;
this._path = v.replace(/\/$/, '');
return this;
};
/**
* Sets the adapter for rooms.
*
* @param {Adapter} v pathname
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
Server.prototype.adapter = function(v){
if (!arguments.length) return this._adapter;
this._adapter = v;
for (var i in this.nsps) {
if (this.nsps.hasOwnProperty(i)) {
this.nsps[i].initAdapter();
}
}
return this;
};
/**
* Sets the allowed origins for requests.
*
* @param {String} v origins
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
Server.prototype.origins = function(v){
if (!arguments.length) return this._origins;
this._origins = v;
return this;
};
Server.createHttpServer = function()
{
return http.createServer(function(req, res)
{
res.writeHead(404);
res.end();
});
};
// TODO: add support for https
Server.prototype.attach = function(srv, opts)
{
if(this.httpServer instanceof http.Server)
{
this.httpServer.close();
}
if(!(srv instanceof http.Server))
{
debug('You are trying to start a socket.io server ' +
'without a valid http.Server. creating http server.');
srv = Server.createHttpServer();
}
// set engine.io path to `/socket.io`
opts = opts || {};
opts.path = opts.path || this.path();
// set origins verification
opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this);
// initialize engine
debug('creating engine.io instance with opts %j', opts);
this.eio = engine.attach(srv, opts);
// attach static file serving
if (this._serveClient) this.attachServe(srv);
// Export http server
this.httpServer = srv;
// bind to engine events
this.bind(this.eio);
return this;
};
Server.prototype.listen = function()
{
if(!(this.httpServer instanceof http.Server))
{
this.attach();
}
else
{
this.httpServer.close();
}
this.httpServer.listen(...arguments);
return this;
};
Server.prototype.close = function()
{
if(this.httpServer instanceof http.Server)
{
this.httpServer.close();
}
return this;
};
/**
* Attaches the static file serving.
*
* @param {Function|http.Server} srv http server
* @api private
*/
Server.prototype.attachServe = function(srv){
debug('attaching client serving req handler');
var url = this._path + '/socket.io.js';
var evs = srv.listeners('request').slice(0);
var self = this;
srv.removeAllListeners('request');
srv.on('request', function(req, res) {
if (0 === req.url.indexOf(url)) {
self.serve(req, res);
} else {
for (var i = 0; i < evs.length; i++) {
evs[i].call(srv, req, res);
}
}
});
};
/**
* Handles a request serving `/socket.io.js`
*
* @param {http.Request} req
* @param {http.Response} res
* @api private
*/
Server.prototype.serve = function(req, res){
var etag = req.headers['if-none-match'];
if (etag) {
if (clientVersion == etag) {
debug('serve client 304');
res.writeHead(304);
res.end();
return;
}
}
debug('serve client source');
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('ETag', clientVersion);
res.writeHead(200);
res.end(clientSource);
};
/**
* Binds socket.io to an engine.io instance.
*
* @param {engine.Server} engine engine.io (or compatible) server
* @return {Server} self
* @api public
*/
Server.prototype.bind = function(engine){
this.engine = engine;
this.engine.on('connection', this.onconnection.bind(this));
return this;
};
/**
* Called with each incoming transport connection.
*
* @param {engine.Socket} conn
* @return {Server} self
* @api public
*/
Server.prototype.onconnection = function(conn){
debug('incoming connection with id %s', conn.id);
var client = new Client(this, conn);
client.connect('/');
return this;
};
Server.prototype.of = function(name, constructor)
{
if (String(name)[0] !== '/')
{
name = '/' + name;
}
var nsp = this.nsps[name];
if (!nsp)
{
debug('initializing namespace %s', name);
nsp = new Namespace(this, name, constructor);
this.nsps[name] = nsp;
}
return nsp;
};
/**
* Closes server connection
*
* @api public
*/
Server.prototype.close = function(){
for (var id in this.nsps['/'].sockets) {
if (this.nsps['/'].sockets.hasOwnProperty(id)) {
this.nsps['/'].sockets[id].onclose();
}
}
this.engine.close();
if(this.httpServer){
this.httpServer.close();
}
};
/**
* Expose main namespace (/).
*/
['on', 'to', 'in', 'use', 'emit', 'send', 'write', 'clients', 'compress'].forEach(function(fn){
Server.prototype[fn] = function(){
var nsp = this.sockets[fn];
return nsp.apply(this.sockets, arguments);
};
});
Namespace.flags.forEach(function(flag){
Server.prototype.__defineGetter__(flag, function(){
this.sockets.flags = this.sockets.flags || {};
this.sockets.flags[flag] = true;
return this;
});
});
/**
* BC with `io.listen`
*/
Server.listen = Server;
| lib/index.js | 'use strict';
/**
* Module dependencies.
*/
var http = require('http');
var read = require('fs').readFileSync;
var engine = require('engine.io');
var client = require('socket.io-client');
var clientVersion = require('socket.io-client/package').version;
var Client = require('./client');
var Namespace = require('./namespace');
var Adapter = require('socket.io-adapter');
var debug = require('debug')('socket.io:server');
var url = require('url');
/**
* Socket.IO client source.
*/
var clientSource = read(require.resolve('socket.io-client/socket.io.js'), 'utf-8');
/**
* Server constructor.
*
* @param {http.Server|Number|Object} srv http server, port or options
* @param {Object} opts
* @api public
*/
function Server(srv, opts)
{
if (!(this instanceof Server))
{
if(!Server.singleton)
{
Server.singleton = new Server(srv, opts);
}
return Server.singleton;
}
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
}
/**
* Server request verification function, that checks for allowed origins
*
* @param {http.IncomingMessage} req request
* @param {Function} fn callback to be called with the result: `fn(err, success)`
*/
Server.prototype.checkRequest = function(req, fn) {
var origin = req.headers.origin || req.headers.referer;
// file:// URLs produce a null Origin which can't be authorized via echo-back
if ('null' == origin || null == origin) origin = '*';
if (!!origin && typeof(this._origins) == 'function') return this._origins(origin, fn);
if (this._origins.indexOf('*:*') !== -1) return fn(null, true);
if (origin) {
try {
var parts = url.parse(origin);
var defaultPort = 'https:' == parts.protocol ? 443 : 80;
parts.port = parts.port != null
? parts.port
: defaultPort;
var ok =
~this._origins.indexOf(parts.hostname + ':' + parts.port) ||
~this._origins.indexOf(parts.hostname + ':*') ||
~this._origins.indexOf('*:' + parts.port);
return fn(null, !!ok);
} catch (ex) {
}
}
fn(null, false);
};
/**
* Sets/gets whether client code is being served.
*
* @param {Boolean} v whether to serve client code
* @return {Server|Boolean} self when setting or value when getting
* @api public
*/
Server.prototype.serveClient = function(v){
if (!arguments.length) return this._serveClient;
this._serveClient = v;
return this;
};
/**
* Old settings for backwards compatibility
*/
var oldSettings = {
"transports": "transports",
"heartbeat timeout": "pingTimeout",
"heartbeat interval": "pingInterval",
"destroy buffer size": "maxHttpBufferSize"
};
/**
* Backwards compatiblity.
*
* @api public
*/
Server.prototype.set = function(key, val){
if ('authorization' == key && val) {
this.use(function(socket, next) {
val(socket.request, function(err, authorized) {
if (err) return next(new Error(err));
if (!authorized) return next(new Error('Not authorized'));
next();
});
});
} else if ('origins' == key && val) {
this.origins(val);
} else if ('resource' == key) {
this.path(val);
} else if (oldSettings[key] && this.eio[oldSettings[key]]) {
this.eio[oldSettings[key]] = val;
} else {
console.error('Option %s is not valid. Please refer to the README.', key);
}
return this;
};
/**
* Sets the client serving path.
*
* @param {String} v pathname
* @return {Server|String} self when setting or value when getting
* @api public
*/
Server.prototype.path = function(v){
if (!arguments.length) return this._path;
this._path = v.replace(/\/$/, '');
return this;
};
/**
* Sets the adapter for rooms.
*
* @param {Adapter} v pathname
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
Server.prototype.adapter = function(v){
if (!arguments.length) return this._adapter;
this._adapter = v;
for (var i in this.nsps) {
if (this.nsps.hasOwnProperty(i)) {
this.nsps[i].initAdapter();
}
}
return this;
};
/**
* Sets the allowed origins for requests.
*
* @param {String} v origins
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
Server.prototype.origins = function(v){
if (!arguments.length) return this._origins;
this._origins = v;
return this;
};
Server.createHttpServer = function()
{
return http.createServer(function(req, res)
{
res.writeHead(404);
res.end();
});
};
// TODO: add support for https
Server.prototype.attach = function(srv, opts)
{
if(this.httpServer instanceof http.Server)
{
this.httpServer.close();
}
if(!(srv instanceof http.Server))
{
debug('You are trying to start a socket.io server ' +
'without a valid http.Server. creating http server.');
srv = Server.createHttpServer();
}
// set engine.io path to `/socket.io`
opts = opts || {};
opts.path = opts.path || this.path();
// set origins verification
opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this);
// initialize engine
debug('creating engine.io instance with opts %j', opts);
this.eio = engine.attach(srv, opts);
// attach static file serving
if (this._serveClient) this.attachServe(srv);
// Export http server
this.httpServer = srv;
// bind to engine events
this.bind(this.eio);
return this;
};
Server.prototype.listen = function()
{
if(!(this.httpServer instanceof http.Server))
{
this.attach();
}
else
{
this.httpServer.close();
}
this.httpServer.listen(...arguments);
return this;
};
/**
* Attaches the static file serving.
*
* @param {Function|http.Server} srv http server
* @api private
*/
Server.prototype.attachServe = function(srv){
debug('attaching client serving req handler');
var url = this._path + '/socket.io.js';
var evs = srv.listeners('request').slice(0);
var self = this;
srv.removeAllListeners('request');
srv.on('request', function(req, res) {
if (0 === req.url.indexOf(url)) {
self.serve(req, res);
} else {
for (var i = 0; i < evs.length; i++) {
evs[i].call(srv, req, res);
}
}
});
};
/**
* Handles a request serving `/socket.io.js`
*
* @param {http.Request} req
* @param {http.Response} res
* @api private
*/
Server.prototype.serve = function(req, res){
var etag = req.headers['if-none-match'];
if (etag) {
if (clientVersion == etag) {
debug('serve client 304');
res.writeHead(304);
res.end();
return;
}
}
debug('serve client source');
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('ETag', clientVersion);
res.writeHead(200);
res.end(clientSource);
};
/**
* Binds socket.io to an engine.io instance.
*
* @param {engine.Server} engine engine.io (or compatible) server
* @return {Server} self
* @api public
*/
Server.prototype.bind = function(engine){
this.engine = engine;
this.engine.on('connection', this.onconnection.bind(this));
return this;
};
/**
* Called with each incoming transport connection.
*
* @param {engine.Socket} conn
* @return {Server} self
* @api public
*/
Server.prototype.onconnection = function(conn){
debug('incoming connection with id %s', conn.id);
var client = new Client(this, conn);
client.connect('/');
return this;
};
Server.prototype.of = function(name, constructor)
{
if (String(name)[0] !== '/')
{
name = '/' + name;
}
var nsp = this.nsps[name];
if (!nsp)
{
debug('initializing namespace %s', name);
nsp = new Namespace(this, name, constructor);
this.nsps[name] = nsp;
}
return nsp;
};
/**
* Closes server connection
*
* @api public
*/
Server.prototype.close = function(){
for (var id in this.nsps['/'].sockets) {
if (this.nsps['/'].sockets.hasOwnProperty(id)) {
this.nsps['/'].sockets[id].onclose();
}
}
this.engine.close();
if(this.httpServer){
this.httpServer.close();
}
};
/**
* Expose main namespace (/).
*/
['on', 'to', 'in', 'use', 'emit', 'send', 'write', 'clients', 'compress'].forEach(function(fn){
Server.prototype[fn] = function(){
var nsp = this.sockets[fn];
return nsp.apply(this.sockets, arguments);
};
});
Namespace.flags.forEach(function(flag){
Server.prototype.__defineGetter__(flag, function(){
this.sockets.flags = this.sockets.flags || {};
this.sockets.flags[flag] = true;
return this;
});
});
/**
* BC with `io.listen`
*/
Server.listen = Server;
| [FEATURE] Ability to shutdown http.Server instance
as described in node.js' http.Server.close() docs.
close server to not accept any future requests.
| lib/index.js | [FEATURE] Ability to shutdown http.Server instance | <ide><path>ib/index.js
<ide>
<ide> return this;
<ide> };
<add>
<add>Server.prototype.close = function()
<add>{
<add> if(this.httpServer instanceof http.Server)
<add> {
<add> this.httpServer.close();
<add> }
<add>
<add> return this;
<add>};
<add>
<ide> /**
<ide> * Attaches the static file serving.
<ide> * |
|
Java | apache-2.0 | 8072cd20ce060b3139f7f3c289b5e6648250a753 | 0 | tkrajina/GraphAnything | package info.puzz.graphanything.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LabelFormatter;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import junit.framework.Assert;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import info.puzz.graphanything.R;
import info.puzz.graphanything.models2.FormatVariant;
import info.puzz.graphanything.models2.GraphColumn;
import info.puzz.graphanything.models2.GraphEntry;
import info.puzz.graphanything.models2.GraphInfo;
import info.puzz.graphanything.models2.GraphStats;
import info.puzz.graphanything.models2.GraphUnitType;
import info.puzz.graphanything.models2.format.FormatException;
import info.puzz.graphanything.services.StatsCalculator;
import info.puzz.graphanything.utils.Formatters;
import info.puzz.graphanything.utils.ThreadUtils;
import info.puzz.graphanything.utils.TimeUtils;
import info.puzz.graphanything.utils.Timer;
public class GraphActivity extends BaseActivity {
private static final String TAG = GraphActivity.class.getSimpleName();
public static final String ARG_GRAPH_ID = "graph_id";
public static final String ARG_GRAPH = "graph";
public static final String ARG_COLUMN_NO = "column_no";
private Long graphId;
private GraphInfo graph;
private List<GraphColumn> graphColumns;
private GraphColumn currentGraphColumn;
private TextView timerTextView;
private Button startStopTimerButton;
private boolean activityActive;
private Float graphFontSize = null;
private View fieldSelectorGroup;
private Spinner fieldSpinner;
public static void start(BaseActivity activity, long graphId, int columnNo) {
Intent intent = new Intent(activity, GraphActivity.class);
intent.putExtra(GraphActivity.ARG_GRAPH_ID, graphId);
intent.putExtra(GraphActivity.ARG_COLUMN_NO, columnNo);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph);
timerTextView = (TextView) findViewById(R.id.timer);
Assert.assertNotNull(timerTextView);
startStopTimerButton = (Button) findViewById(R.id.start_stop_timer);
Assert.assertNotNull(startStopTimerButton);
fieldSelectorGroup = findViewById(R.id.field_selector_group);
Assert.assertNotNull(fieldSelectorGroup);
fieldSpinner = (Spinner) findViewById(R.id.field_selector);
Assert.assertNotNull(fieldSpinner);
graphId = getIntent().getExtras().getLong(ARG_GRAPH_ID);
Assert.assertNotNull(graphId);
graphColumns = getDAO().getColumns(graphId);
int columnNo = getIntent().getExtras().getInt(ARG_COLUMN_NO);
for (GraphColumn graphColumn : graphColumns) {
if (graphColumn.getColumnNo() == columnNo) {
currentGraphColumn = graphColumn;
}
}
Assert.assertNotNull(currentGraphColumn);
graph = getDAO().loadGraph(graphId);
prepareFieldSpinner();
// Prevent opening the keyboard every time (since the text fiels will have the focus by default):
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private void prepareFieldSpinner() {
if (graphColumns.size() <= 1) {
return;
}
String[] fieldsArr = new String[graphColumns.size()];
for (int i = 0; i < graphColumns.size(); i++) {
fieldsArr[i] = graphColumns.get(i).formatName();
}
fieldSelectorGroup.setVisibility(View.VISIBLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, fieldsArr);
fieldSpinner.setAdapter(adapter);
fieldSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
GraphColumn selectedColumn = graphColumns.get(position);
if (selectedColumn.getColumnNo() != currentGraphColumn.getColumnNo()) {
Log.i(TAG, "Selected column:" + selectedColumn);
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
protected void onPause() {
super.onPause();
activityActive = false;
}
@Override
protected void onResume() {
super.onResume();
activityActive = true;
setTitle(graph.name);
boolean isTimer = currentGraphColumn.getGraphUnitType() == GraphUnitType.TIMER;
findViewById(R.id.timer_value_group).setVisibility(isTimer ? View.VISIBLE : View.GONE);
findViewById(R.id.unit_value_group).setVisibility(isTimer ? View.GONE : View.VISIBLE);
if (isTimer) {
prepareTimer();
}
redrawAndUpdateGraphAndStats(true);
if (graph.isTimeActive()) {
startTimer();
}
}
@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_graph, menu);
return true;
}
private void prepareTimer() {
timerTextView.setText("00:00:00");
startStopTimerButton.setText(R.string.start_timer);
}
public void editGraph(MenuItem item) {
GraphEditActivity.start(this, graph._id);
}
public void showValues(MenuItem item) {
GraphValuesActivity.start(this, graph._id);
}
public void onSaveValue(View view) {
final EditText numberField = (EditText) findViewById(R.id.number_field);
String text = numberField.getText().toString().trim();
double value;
try {
value = currentGraphColumn.getGraphUnitType().parse(text);
} catch (FormatException e) {
new AlertDialog.Builder(this)
.setTitle("Invalid value")
.setMessage(e.getMessage())
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
numberField.setText("", TextView.BufferType.EDITABLE);
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return;
}
this.addValue(value);
}
private void addValue(double value) {
GraphEntry graphEntry = new GraphEntry()
.setGraphId(graph._id)
.setCreated(System.currentTimeMillis())
.set(0, value);
GraphEntryActivity.start(this, graph._id, graphEntry);
}
private void redrawAndUpdateGraphAndStats(boolean showGoal) {
Timer t = new Timer("redrawing graph");
GraphView graphView = (GraphView) findViewById(R.id.graph);
if (graphFontSize == null) {
graphFontSize = graphView.getGridLabelRenderer().getTextSize();
}
graphView.removeAllSeries();
final GraphUnitType graphUnitType = currentGraphColumn.getGraphUnitType();
graphView.getGridLabelRenderer().setLabelFormatter(new LabelFormatter() {
Calendar cal = Calendar.getInstance();
@Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
cal.setTimeInMillis((long) value);
return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
}
return graphUnitType.format(value, FormatVariant.SHORT);
}
@Override
public void setViewport(Viewport viewport) {
}
});
graphView.getGridLabelRenderer().setTextSize((float) (graphFontSize * 0.6));
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
graphView.getGridLabelRenderer().setNumHorizontalLabels(20);
} else {
graphView.getGridLabelRenderer().setNumHorizontalLabels(10);
}
List<GraphEntry> values = getDAO().getEntriesByCreatedAsc(graph._id);
GraphEntry latestValue = values.size() == 0 ? null : values.get(values.size() - 1);
List<DataPoint> dataPoints = graph.getGraphType().convert(values, currentGraphColumn.getColumnNo());
t.time("Before stats");
GraphStats stats = StatsCalculator.calculate(graph, dataPoints, currentGraphColumn);
t.time("After stats");
redrawStats(graphUnitType, stats);
// And when we already computed all the stats, update the graph entity:
if (latestValue != null) {
graph.lastValue = latestValue.get(0);
graph.lastValueCreated = latestValue.created;
}
if (currentGraphColumn.calculateGoal() && stats.getGoalEstimateDays() != null) {
currentGraphColumn.goalEstimateDays = stats.getGoalEstimateDays();
}
getDAO().save(graph);
getDAO().save(currentGraphColumn);
t.time("before getting graph points");
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(dataPoints.toArray(new DataPoint[dataPoints.size()]));
t.time("after getting graph points");
double minX = series.getLowestValueX();
double maxX = series.getHighestValueX();
double minY = series.getLowestValueY();
double maxY = series.getHighestValueY();
if (currentGraphColumn.calculateGoal() && showGoal) {
minY = Math.min(minY, currentGraphColumn.goal);
maxY = Math.max(maxY, currentGraphColumn.goal);
long goalTime = stats.getGoalTime();
long maxGoalDistance = (long) ((maxX - minX) * 2);
long fromGoalTime = stats.getGoalTime() - System.currentTimeMillis();
if (fromGoalTime > maxGoalDistance) {
goalTime = (long) (System.currentTimeMillis() + maxGoalDistance * 0.75);
} else if (fromGoalTime < - maxGoalDistance) {
goalTime = (long) (System.currentTimeMillis() - maxGoalDistance * 0.75);
}
minX = Math.min(minX, goalTime);
maxX = Math.max(maxX, goalTime);
// Goal line:
LineGraphSeries<DataPoint> goalSeries = new LineGraphSeries<>(new DataPoint[] {
new DataPoint(minX, currentGraphColumn.goal),
new DataPoint(maxX, currentGraphColumn.goal),
});
goalSeries.setThickness(2);
goalSeries.setColor(0xffff9c00);
goalSeries.setTitle(getResources().getString(R.string.goal));
graphView.addSeries(goalSeries);
// GraphInfo estimate line:
LineGraphSeries<DataPoint> estimateSeries = new LineGraphSeries<>(new DataPoint[] {
new DataPoint(minX, stats.calculateGoalLineValue(minX)),
new DataPoint(maxX, stats.calculateGoalLineValue(maxX)),
});
estimateSeries.setThickness(2);
estimateSeries.setTitle(getResources().getString(R.string.estimate));
estimateSeries.setColor(0xff67cfff);
graphView.addSeries(estimateSeries);
}
if (minX == maxX) {
minX -= 10;
maxX += 10;
minY -= 10;
maxY += 10;
}
double xpadding = minX == maxX ? 0 : (maxX - minX) * 0.01;
double ypadding = minY == maxY ? 0 : (maxY - minY) * 0.01;
minX -= xpadding;
maxX += xpadding;
minY -= ypadding;
maxY += ypadding;
graphView.getViewport().setMinX(minX);
graphView.getViewport().setMaxX(maxX);
graphView.getViewport().setXAxisBoundsManual(true);
graphView.getViewport().setMinY(minY);
graphView.getViewport().setMaxY(maxY);
graphView.getViewport().setYAxisBoundsManual(true);
graphView.getGridLabelRenderer().setGridColor(Color.GRAY);
LegendRenderer.LegendAlign legendAlign = LegendRenderer.LegendAlign.BOTTOM;
if (dataPoints.size() > 1 && dataPoints.get(0).getY() > dataPoints.get(dataPoints.size() - 1).getY()) {
legendAlign = LegendRenderer.LegendAlign.TOP;
}
graphView.getLegendRenderer().setAlign(legendAlign);
graphView.getLegendRenderer().setVisible(true);
graphView.getViewport().setScalable(true);
graphView.getViewport().setScrollable(true);
series.setTitle(getResources().getString(R.string.data));
if (dataPoints.size() < 6) {
series.setDrawDataPoints(true);
series.setDataPointsRadius(graphFontSize / dataPoints.size());
}
t.time("Before drawing graph");
graphView.addSeries(series);
t.time("After drawing graph");
Log.i(TAG, "GraphInfo drawing times:" + t.toString());
}
private void redrawStats(GraphUnitType graphUnitType, GraphStats stats) {
boolean horizontal = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
((TextView) findViewById(R.id.total_avg)).setText(graphUnitType.format(stats.getAvg(), FormatVariant.LONG));
((TextView) findViewById(R.id.last_preriod_avg_value)).setText(graphUnitType.format(stats.getAvgLatestPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
((TextView) findViewById(R.id.previous_preriod_avg_value)).setText(graphUnitType.format(stats.getAvgPreviousPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
((TextView) findViewById(R.id.total_sum)).setText(graphUnitType.format(stats.getSum(), FormatVariant.LONG));
((TextView) findViewById(R.id.last_preriod_sum_value)).setText(graphUnitType.format(stats.getSumLatestPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
((TextView) findViewById(R.id.previous_period_sum_value)).setText(graphUnitType.format(stats.getSumPreviousPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
if (currentGraphColumn.calculateGoal()) {
((TextView) findViewById(R.id.goal)).setText(graphUnitType.format(currentGraphColumn.goal, FormatVariant.LONG));
String estimate = "n/a";
if (stats.getGoalEstimateDays() != null && stats.getGoalEstimateDays().floatValue() >= 0) {
estimate = Formatters.formatNumber(stats.getGoalEstimateDays()) + "days";
}
((TextView) findViewById(R.id.goal_estimate)).setText(estimate);
}
}
/* public void onEditRawData(MenuItem item) {
RawGraphDataActivity.start(this, graph._id);
}*/
public void deleteGraph(MenuItem item) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
deleteGraph();
}
}
};
new AlertDialog.Builder(this)
.setMessage("Delete \"" + graph.name + "\"?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.show();
}
private void deleteGraph() {
getDAO().deleteGraph(graph);
GraphListActivity.start(this);
}
public void onStartStop(View view) {
if (currentGraphColumn.unitType != GraphUnitType.TIMER.getType()) {
return;
}
if (graph.isTimeActive()) {
stopTimer();
} else {
startTimer();
}
}
private void stopTimer() {
long value = TimeUtils.timeFrom(graph.timerStarted);
addValue(value);
startStopTimerButton.setText(R.string.start_timer);
}
/**
* Starts a thread to update the timer. The thread will automatically stop when the activity pauses or the {@link GraphInfo#timerStarted} is set to 0.
*/
private void startTimer() {
if (graph.timerStarted == 0) {
graph.timerStarted = System.currentTimeMillis();
getDAO().save(graph);
}
startStopTimerButton.setText(R.string.stop_timer);
new Thread() {
@Override
public void run() {
Log.i(TAG, "Starting timer update thread");
while (activityActive && graph.isTimeActive()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
timerTextView.setText(TimeUtils.formatDurationToHHMMSS(System.currentTimeMillis() - graph.timerStarted, FormatVariant.LONG));
}
});
ThreadUtils.sleep(TimeUnit.SECONDS.toMillis(1));
}
Log.i(TAG, "Timer stopped");
}
}.start();
}
}
| graphanything/src/main/java/info/puzz/graphanything/activities/GraphActivity.java | package info.puzz.graphanything.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LabelFormatter;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import junit.framework.Assert;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import info.puzz.graphanything.R;
import info.puzz.graphanything.models2.FormatVariant;
import info.puzz.graphanything.models2.GraphColumn;
import info.puzz.graphanything.models2.GraphEntry;
import info.puzz.graphanything.models2.GraphInfo;
import info.puzz.graphanything.models2.GraphStats;
import info.puzz.graphanything.models2.GraphUnitType;
import info.puzz.graphanything.models2.format.FormatException;
import info.puzz.graphanything.services.StatsCalculator;
import info.puzz.graphanything.utils.Formatters;
import info.puzz.graphanything.utils.ThreadUtils;
import info.puzz.graphanything.utils.TimeUtils;
import info.puzz.graphanything.utils.Timer;
public class GraphActivity extends BaseActivity {
private static final String TAG = GraphActivity.class.getSimpleName();
public static final String ARG_GRAPH_ID = "graph_id";
public static final String ARG_GRAPH = "graph";
public static final String ARG_COLUMN_NO = "column_no";
private Long graphId;
private GraphInfo graph;
private List<GraphColumn> graphColumns;
private GraphColumn currentGraphColumn;
private TextView timerTextView;
private Button startStopTimerButton;
private boolean activityActive;
private Float graphFontSize = null;
private View fieldSelectorGroup;
private Spinner fieldSpinner;
public static void start(BaseActivity activity, long graphId, int columnNo) {
Intent intent = new Intent(activity, GraphActivity.class);
intent.putExtra(GraphActivity.ARG_GRAPH_ID, graphId);
intent.putExtra(GraphActivity.ARG_COLUMN_NO, columnNo);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph);
timerTextView = (TextView) findViewById(R.id.timer);
Assert.assertNotNull(timerTextView);
startStopTimerButton = (Button) findViewById(R.id.start_stop_timer);
Assert.assertNotNull(startStopTimerButton);
fieldSelectorGroup = findViewById(R.id.field_selector_group);
Assert.assertNotNull(fieldSelectorGroup);
fieldSpinner = (Spinner) findViewById(R.id.field_selector);
Assert.assertNotNull(fieldSpinner);
graphId = getIntent().getExtras().getLong(ARG_GRAPH_ID);
Assert.assertNotNull(graphId);
graphColumns = getDAO().getColumns(graphId);
int columnNo = getIntent().getExtras().getInt(ARG_COLUMN_NO);
for (GraphColumn graphColumn : graphColumns) {
if (graphColumn.getColumnNo() == columnNo) {
currentGraphColumn = graphColumn;
}
}
Assert.assertNotNull(currentGraphColumn);
graph = getDAO().loadGraph(graphId);
prepareFieldSpinner();
// Prevent opening the keyboard every time (since the text fiels will have the focus by default):
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private void prepareFieldSpinner() {
if (graphColumns.size() <= 1) {
return;
}
String[] fieldsArr = new String[graphColumns.size()];
for (int i = 0; i < graphColumns.size(); i++) {
fieldsArr[i] = graphColumns.get(i).formatName();
}
fieldSelectorGroup.setVisibility(View.VISIBLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, fieldsArr);
fieldSpinner.setAdapter(adapter);
fieldSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
GraphColumn selectedColumn = graphColumns.get(position);
if (selectedColumn.getColumnNo() != currentGraphColumn.getColumnNo()) {
Log.i(TAG, "Selected column:" + selectedColumn);
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
protected void onPause() {
super.onPause();
activityActive = false;
}
@Override
protected void onResume() {
super.onResume();
activityActive = true;
setTitle(graph.name);
boolean isTimer = currentGraphColumn.getGraphUnitType() == GraphUnitType.TIMER;
findViewById(R.id.timer_value_group).setVisibility(isTimer ? View.VISIBLE : View.GONE);
findViewById(R.id.unit_value_group).setVisibility(isTimer ? View.GONE : View.VISIBLE);
if (isTimer) {
prepareTimer();
}
redrawAndUpdateGraphAndStats(true);
if (graph.isTimeActive()) {
startTimer();
}
}
@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_graph, menu);
return true;
}
private void prepareTimer() {
timerTextView.setText("00:00:00");
startStopTimerButton.setText(R.string.start_timer);
}
public void editGraph(MenuItem item) {
GraphEditActivity.start(this, graph._id);
}
public void showValues(MenuItem item) {
GraphValuesActivity.start(this, graph._id);
}
public void onSaveValue(View view) {
final EditText numberField = (EditText) findViewById(R.id.number_field);
String text = numberField.getText().toString().trim();
double value;
try {
value = currentGraphColumn.getGraphUnitType().parse(text);
} catch (FormatException e) {
new AlertDialog.Builder(this)
.setTitle("Invalid value")
.setMessage(e.getMessage())
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
numberField.setText("", TextView.BufferType.EDITABLE);
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return;
}
this.addValue(value);
}
private void addValue(double value) {
GraphEntry graphEntry = new GraphEntry()
.setGraphId(graph._id)
.setCreated(System.currentTimeMillis())
.set(0, value);
GraphEntryActivity.start(this, graph._id, graphEntry);
}
private void redrawAndUpdateGraphAndStats(boolean showGoal) {
Timer t = new Timer("redrawing graph");
GraphView graphView = (GraphView) findViewById(R.id.graph);
if (graphFontSize == null) {
graphFontSize = graphView.getGridLabelRenderer().getTextSize();
}
graphView.removeAllSeries();
final GraphUnitType graphUnitType = currentGraphColumn.getGraphUnitType();
graphView.getGridLabelRenderer().setLabelFormatter(new LabelFormatter() {
Calendar cal = Calendar.getInstance();
@Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
cal.setTimeInMillis((long) value);
return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
}
return graphUnitType.format(value, FormatVariant.SHORT);
}
@Override
public void setViewport(Viewport viewport) {
}
});
graphView.getGridLabelRenderer().setTextSize((float) (graphFontSize * 0.6));
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
graphView.getGridLabelRenderer().setNumHorizontalLabels(20);
} else {
graphView.getGridLabelRenderer().setNumHorizontalLabels(10);
}
List<GraphEntry> values = getDAO().getEntriesByCreatedAsc(graph._id);
GraphEntry latestValue = values.size() == 0 ? null : values.get(values.size() - 1);
List<DataPoint> dataPoints = graph.getGraphType().convert(values, currentGraphColumn.getColumnNo());
t.time("Before stats");
GraphStats stats = StatsCalculator.calculate(graph, dataPoints, currentGraphColumn);
t.time("After stats");
redrawStats(graphUnitType, stats);
// And when we already computed all the stats, update the graph entity:
if (latestValue != null) {
graph.lastValue = latestValue.get(0);
graph.lastValueCreated = latestValue.created;
}
if (currentGraphColumn.calculateGoal() && stats.getGoalEstimateDays() != null) {
currentGraphColumn.goalEstimateDays = stats.getGoalEstimateDays();
}
getDAO().save(graph);
getDAO().save(currentGraphColumn);
t.time("before getting graph points");
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(dataPoints.toArray(new DataPoint[dataPoints.size()]));
t.time("after getting graph points");
double minX = series.getLowestValueX();
double maxX = series.getHighestValueX();
double minY = series.getLowestValueY();
double maxY = series.getHighestValueY();
if (currentGraphColumn.calculateGoal() && showGoal) {
minY = Math.min(minY, currentGraphColumn.goal);
maxY = Math.max(maxY, currentGraphColumn.goal);
long goalTime = stats.getGoalTime();
long maxGoalDistance = (long) ((maxX - minX) * 2);
long fromGoalTime = stats.getGoalTime() - System.currentTimeMillis();
if (fromGoalTime > maxGoalDistance) {
goalTime = (long) (System.currentTimeMillis() + maxGoalDistance * 0.75);
} else if (fromGoalTime < - maxGoalDistance) {
goalTime = (long) (System.currentTimeMillis() - maxGoalDistance * 0.75);
}
minX = Math.min(minX, goalTime);
maxX = Math.max(maxX, goalTime);
// Goal line:
LineGraphSeries<DataPoint> goalSeries = new LineGraphSeries<>(new DataPoint[] {
new DataPoint(minX, currentGraphColumn.goal),
new DataPoint(maxX, currentGraphColumn.goal),
});
goalSeries.setThickness(2);
goalSeries.setColor(0xffff9c00);
goalSeries.setTitle(getResources().getString(R.string.goal));
graphView.addSeries(goalSeries);
// GraphInfo estimate line:
LineGraphSeries<DataPoint> estimateSeries = new LineGraphSeries<>(new DataPoint[] {
new DataPoint(minX, stats.calculateGoalLineValue(minX)),
new DataPoint(maxX, stats.calculateGoalLineValue(maxX)),
});
estimateSeries.setThickness(2);
estimateSeries.setTitle(getResources().getString(R.string.estimate));
estimateSeries.setColor(0xff67cfff);
graphView.addSeries(estimateSeries);
}
if (minX == maxX) {
minX -= 10;
maxX += 10;
minY -= 10;
maxY += 10;
}
double xpadding = minX == maxX ? 0 : (maxX - minX) * 0.01;
double ypadding = minY == maxY ? 0 : (maxY - minY) * 0.01;
minX -= xpadding;
maxX += xpadding;
minY -= ypadding;
maxY += ypadding;
graphView.getViewport().setMinX(minX);
graphView.getViewport().setMaxX(maxX);
graphView.getViewport().setXAxisBoundsManual(true);
graphView.getViewport().setMinY(minY);
graphView.getViewport().setMaxY(maxY);
graphView.getViewport().setYAxisBoundsManual(true);
graphView.getGridLabelRenderer().setGridColor(Color.GRAY);
graphView.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
graphView.getLegendRenderer().setVisible(true);
graphView.getViewport().setScalable(true);
graphView.getViewport().setScrollable(true);
series.setTitle(getResources().getString(R.string.data));
if (dataPoints.size() < 6) {
series.setDrawDataPoints(true);
series.setDataPointsRadius(graphFontSize / dataPoints.size());
}
t.time("Before drawing graph");
graphView.addSeries(series);
t.time("After drawing graph");
Log.i(TAG, "GraphInfo drawing times:" + t.toString());
}
private void redrawStats(GraphUnitType graphUnitType, GraphStats stats) {
boolean horizontal = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
((TextView) findViewById(R.id.total_avg)).setText(graphUnitType.format(stats.getAvg(), FormatVariant.LONG));
((TextView) findViewById(R.id.last_preriod_avg_value)).setText(graphUnitType.format(stats.getAvgLatestPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
((TextView) findViewById(R.id.previous_preriod_avg_value)).setText(graphUnitType.format(stats.getAvgPreviousPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
((TextView) findViewById(R.id.total_sum)).setText(graphUnitType.format(stats.getSum(), FormatVariant.LONG));
((TextView) findViewById(R.id.last_preriod_sum_value)).setText(graphUnitType.format(stats.getSumLatestPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
((TextView) findViewById(R.id.previous_period_sum_value)).setText(graphUnitType.format(stats.getSumPreviousPeriod(), horizontal ? FormatVariant.LONG : FormatVariant.SHORT));
if (currentGraphColumn.calculateGoal()) {
((TextView) findViewById(R.id.goal)).setText(graphUnitType.format(currentGraphColumn.goal, FormatVariant.LONG));
String estimate = "n/a";
if (stats.getGoalEstimateDays() != null && stats.getGoalEstimateDays().floatValue() >= 0) {
estimate = Formatters.formatNumber(stats.getGoalEstimateDays()) + "days";
}
((TextView) findViewById(R.id.goal_estimate)).setText(estimate);
}
}
/* public void onEditRawData(MenuItem item) {
RawGraphDataActivity.start(this, graph._id);
}*/
public void deleteGraph(MenuItem item) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
deleteGraph();
}
}
};
new AlertDialog.Builder(this)
.setMessage("Delete \"" + graph.name + "\"?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.show();
}
private void deleteGraph() {
getDAO().deleteGraph(graph);
GraphListActivity.start(this);
}
public void onStartStop(View view) {
if (currentGraphColumn.unitType != GraphUnitType.TIMER.getType()) {
return;
}
if (graph.isTimeActive()) {
stopTimer();
} else {
startTimer();
}
}
private void stopTimer() {
long value = TimeUtils.timeFrom(graph.timerStarted);
addValue(value);
startStopTimerButton.setText(R.string.start_timer);
}
/**
* Starts a thread to update the timer. The thread will automatically stop when the activity pauses or the {@link GraphInfo#timerStarted} is set to 0.
*/
private void startTimer() {
if (graph.timerStarted == 0) {
graph.timerStarted = System.currentTimeMillis();
getDAO().save(graph);
}
startStopTimerButton.setText(R.string.stop_timer);
new Thread() {
@Override
public void run() {
Log.i(TAG, "Starting timer update thread");
while (activityActive && graph.isTimeActive()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
timerTextView.setText(TimeUtils.formatDurationToHHMMSS(System.currentTimeMillis() - graph.timerStarted, FormatVariant.LONG));
}
});
ThreadUtils.sleep(TimeUnit.SECONDS.toMillis(1));
}
Log.i(TAG, "Timer stopped");
}
}.start();
}
}
| Legend position based on first and last value
| graphanything/src/main/java/info/puzz/graphanything/activities/GraphActivity.java | Legend position based on first and last value | <ide><path>raphanything/src/main/java/info/puzz/graphanything/activities/GraphActivity.java
<ide> graphView.getViewport().setYAxisBoundsManual(true);
<ide> graphView.getGridLabelRenderer().setGridColor(Color.GRAY);
<ide>
<del> graphView.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
<add> LegendRenderer.LegendAlign legendAlign = LegendRenderer.LegendAlign.BOTTOM;
<add> if (dataPoints.size() > 1 && dataPoints.get(0).getY() > dataPoints.get(dataPoints.size() - 1).getY()) {
<add> legendAlign = LegendRenderer.LegendAlign.TOP;
<add> }
<add> graphView.getLegendRenderer().setAlign(legendAlign);
<ide> graphView.getLegendRenderer().setVisible(true);
<ide>
<ide> graphView.getViewport().setScalable(true); |
|
JavaScript | mit | 16afba01779bb6d04f8ec8fafd53ae5a1b0dceb9 | 0 | hurwitzlab/elm-imicrobe-spa,hurwitzlab/elm-imicrobe-spa | 'use strict';
require("bootstrap-loader");
// Require these files so they get copied to dist
require('../index.html');
require("../img/nav-header.png");
require('../css/imicrobe.css');
// Load config file
var config = require('../config.json');
// Start up Elm app
var Elm = require('./Main.elm');
var mountNode = document.getElementById('main');
var app = Elm.Main.embed(mountNode, {
config: config,
session: localStorage.session || ""
});
// Initial Google Maps and define Elm ports
var GoogleMapsLoader = require("google-maps");
GoogleMapsLoader.KEY = config.googleApiKey;
var Google;
GoogleMapsLoader.load(function(google) {
Google = google;
});
app.ports.loadMap.subscribe(function(model) {
var mapDiv = document.getElementsByTagName('gmap')[0];
var myLatlng = new Google.maps.LatLng(model.lat, model.lng);
var mapOptions = {
zoom: 6,
center: myLatlng
};
var gmap = new Google.maps.Map(mapDiv, mapOptions);
app.ports.receiveMap.send(gmap);
});
app.ports.setCenter.subscribe(function(model) {
var myLatlng = new Google.maps.LatLng(model.center.lat, model.center.lng);
model.gmap.setCenter(myLatlng);
});
// Define ports for storing/watching session
app.ports.storeSession.subscribe(function(session) {
console.log("storeSession: ", session);
localStorage.session = session;
});
window.addEventListener("storage",
function(event) {
if (event.storageArea === localStorage && event.key === "session") {
console.log("storage listener: ", event.newValue);
app.ports.onSessionChange.send(event.newValue);
}
},
false
);
| src/index.js | 'use strict';
require("bootstrap-loader");
// Require these files so they get copied to dist
require('../index.html');
require("../img/nav-header.png");
// Load config file
var config = require('../config.json');
// Start up Elm app
var Elm = require('./Main.elm');
var mountNode = document.getElementById('main');
var app = Elm.Main.embed(mountNode, {
config: config,
session: localStorage.session || ""
});
// Initial Google Maps and define Elm ports
var GoogleMapsLoader = require("google-maps");
GoogleMapsLoader.KEY = config.googleApiKey;
var Google;
GoogleMapsLoader.load(function(google) {
Google = google;
});
app.ports.loadMap.subscribe(function(model) {
var mapDiv = document.getElementsByTagName('gmap')[0];
var myLatlng = new Google.maps.LatLng(model.lat, model.lng);
var mapOptions = {
zoom: 6,
center: myLatlng
};
var gmap = new Google.maps.Map(mapDiv, mapOptions);
app.ports.receiveMap.send(gmap);
});
app.ports.setCenter.subscribe(function(model) {
var myLatlng = new Google.maps.LatLng(model.center.lat, model.center.lng);
model.gmap.setCenter(myLatlng);
});
// Define ports for storing/watching session
app.ports.storeSession.subscribe(function(session) {
console.log("storeSession: ", session);
localStorage.session = session;
});
window.addEventListener("storage",
function(event) {
if (event.storageArea === localStorage && event.key === "session") {
console.log("storage listener: ", event.newValue);
app.ports.onSessionChange.send(event.newValue);
}
},
false
); | Require CSS
| src/index.js | Require CSS | <ide><path>rc/index.js
<ide> // Require these files so they get copied to dist
<ide> require('../index.html');
<ide> require("../img/nav-header.png");
<add>require('../css/imicrobe.css');
<ide>
<ide> // Load config file
<ide> var config = require('../config.json'); |
|
Java | bsd-3-clause | 458f46fac0319c2efae1267c9904e4775c1147eb | 0 | joansmith/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay | //
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.demo.ui;
import playn.core.Image;
import playn.core.PlayN;
import pythagoras.f.MathUtil;
import react.Function;
import react.IntValue;
import react.UnitSlot;
import tripleplay.ui.*;
import tripleplay.ui.layout.*;
import tripleplay.util.Colors;
import tripleplay.demo.DemoScreen;
/**
* Displays various UI stuff.
*/
public class MiscDemo extends DemoScreen
{
@Override protected String name () {
return "General";
}
@Override protected String title () {
return "UI: General";
}
@Override protected Group createIface () {
Icon smiley = Icons.image(PlayN.assets().getImage("images/smiley.png"));
final Image squares = PlayN.assets().getImage("images/squares.png");
final CapturedRoot capRoot = iface.addRoot(
new CapturedRoot(iface, AxisLayout.horizontal(), stylesheet()));
CheckBox toggle, toggle2;
Label label2;
Field editable, disabled;
Button setField;
Group iface = new Group(AxisLayout.horizontal().stretchByDefault()).add(
// left column
new Group(AxisLayout.vertical()).add(
// labels, visibility and icon toggling
new Label("Toggling visibility"),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new Group(AxisLayout.vertical()).add(
new Group(AxisLayout.horizontal()).add(
toggle = new CheckBox(),
new Label("Toggle Viz")),
new Group(AxisLayout.horizontal()).add(
toggle2 = new CheckBox(),
new Label("Toggle Icon"))),
new Group(AxisLayout.vertical()).add(
new Label("Label 1").addStyles(REDBG),
label2 = new Label("Label 2"),
new Label("Label 3", smiley))),
new Shim(5, 10),
// labels with varying icon alignment
new Label("Icon positioning"),
new Group(AxisLayout.horizontal().gap(10), GREENBG).add(
new Label("Left", tileIcon(squares, 0)).setStyles(Style.ICON_POS.left),
new Label("Right", tileIcon(squares, 1)).setStyles(Style.ICON_POS.right),
new Label("Above", tileIcon(squares, 2)).setStyles(Style.ICON_POS.above,
Style.HALIGN.center),
new Label("Below", tileIcon(squares, 3)).setStyles(Style.ICON_POS.below,
Style.HALIGN.center)),
new Shim(5, 10),
// a captured root's widget
new Label("Root capture"),
new Group(AxisLayout.vertical()).addStyles(
Style.BACKGROUND.is(Background.solid(Colors.RED).inset(10))).add(
capRoot.createWidget())),
// right column
new Group(AxisLayout.vertical()).add(
// buttons, toggle buttons, wirey uppey
new Label("Buttons"),
buttonsSection(squares),
new Shim(5, 10),
// an editable text field
new Label("Text editing"),
editable = new Field("Editable text").setConstraint(Constraints.fixedWidth(150)),
setField = new Button("Set -> "),
disabled = new Field("Disabled text").setEnabled(false)));
capRoot.add(new Label("Captured Root!").addStyles(
Style.BACKGROUND.is(Background.blank().inset(10)))).pack();
// add a style animation to the captured root (clicking on cap roots NYI)
this.iface.animator().repeat(_root.layer).delay(1000).then().action(new Runnable() {
int cycle;
@Override public void run () {
capRoot.addStyles(Style.BACKGROUND.is(cycle++ % 2 == 0 ?
Background.solid(Colors.WHITE).alpha(.5f) : Background.blank()));
}
});
toggle.checked.update(true);
toggle.checked.connect(label2.visibleSlot());
toggle2.checked.map(new Function<Boolean,Icon>() {
public Icon apply (Boolean checked) {
return checked ? tileIcon(squares, 0) : null;
}
}).connect(label2.icon.slot());
final Field source = editable, target = disabled;
setField.clicked().connect(new UnitSlot() {
@Override public void onEmit () {
PlayN.log().info("Setting text to " + source.text.get());
target.text.update(source.text.get());
}
});
return iface;
}
protected Group buttonsSection (Image squares) {
ToggleButton toggle3 = new ToggleButton("Toggle Enabled");
Button disabled = new Button("Disabled");
toggle3.selected().connectNotify(disabled.enabledSlot());
toggle3.selected().map(new Function<Boolean,String>() {
public String apply (Boolean selected) { return selected ? "Enabled" : "Disabled"; }
}).connectNotify(disabled.text.slot());
class ThrobButton extends Button {
public ThrobButton (String title) {
super(title);
}
public void throb () {
root().iface().animator().
tweenScale(layer).to(1.2f).in(300.0f).easeIn().then().
tweenScale(layer).to(1.0f).in(300.0f).easeOut();
}
@Override protected void layout () {
super.layout();
float ox = MathUtil.ifloor(_size.width/2), oy = MathUtil.ifloor(_size.height/2);
layer.setOrigin(ox, oy);
layer.transform().translate(ox, oy);
}
}
final ThrobButton throbber = new ThrobButton("Throbber");
final Label pressResult = new Label();
final IntValue clickCount = new IntValue(0);
final Box box = new Box();
return new Group(AxisLayout.vertical().offEqualize()).add(
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
toggle3, AxisLayout.stretch(disabled)),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new LongPressButton("Long Pressable").onLongPress(new UnitSlot() {
@Override public void onEmit () { pressResult.text.update("Long pressed"); }
}).onClick(new UnitSlot() {
@Override public void onEmit () { pressResult.text.update("Clicked"); }
}), AxisLayout.stretch(pressResult)),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new Label("Image button"),
new ImageButton(tile(squares, 0), tile(squares, 1)).onClick(new UnitSlot() {
@Override public void onEmit () { clickCount.increment(1); }
}),
new ValueLabel(clickCount)),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new Button("Fill Box").onClick(new UnitSlot() {
@Override public void onEmit () {
box.set(new Label(box.contents() == null ? "Filled" : "Refilled"));
}
}),
box),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
throbber.onClick(new UnitSlot() {
@Override public void onEmit () {
throbber.throb();
}
}))
);
}
protected Image tile (Image image, int index) {
final float iwidth = 16, iheight = 16;
return image.subImage(index*iwidth, 0, iwidth, iheight);
}
protected Icon tileIcon (Image image, int index) {
return Icons.image(tile(image, index));
}
protected static final Styles GREENBG = Styles.make(
Style.BACKGROUND.is(Background.solid(0xFF99CC66).inset(5)));
protected static final Styles REDBG = Styles.make(
Style.BACKGROUND.is(Background.solid(0xFFCC6666).inset(5)));
}
| demo/core/src/main/java/tripleplay/demo/ui/MiscDemo.java | //
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2013, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.demo.ui;
import playn.core.Image;
import playn.core.PlayN;
import react.Function;
import react.IntValue;
import react.UnitSlot;
import tripleplay.ui.*;
import tripleplay.ui.layout.*;
import tripleplay.util.Colors;
import tripleplay.demo.DemoScreen;
/**
* Displays various UI stuff.
*/
public class MiscDemo extends DemoScreen
{
@Override protected String name () {
return "General";
}
@Override protected String title () {
return "UI: General";
}
@Override protected Group createIface () {
Icon smiley = Icons.image(PlayN.assets().getImage("images/smiley.png"));
final Image squares = PlayN.assets().getImage("images/squares.png");
final CapturedRoot capRoot = iface.addRoot(
new CapturedRoot(iface, AxisLayout.horizontal(), stylesheet()));
CheckBox toggle, toggle2;
Label label2;
Field editable, disabled;
Button setField;
Group iface = new Group(AxisLayout.horizontal().stretchByDefault()).add(
// left column
new Group(AxisLayout.vertical()).add(
// labels, visibility and icon toggling
new Label("Toggling visibility"),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new Group(AxisLayout.vertical()).add(
new Group(AxisLayout.horizontal()).add(
toggle = new CheckBox(),
new Label("Toggle Viz")),
new Group(AxisLayout.horizontal()).add(
toggle2 = new CheckBox(),
new Label("Toggle Icon"))),
new Group(AxisLayout.vertical()).add(
new Label("Label 1").addStyles(REDBG),
label2 = new Label("Label 2"),
new Label("Label 3", smiley))),
new Shim(5, 10),
// labels with varying icon alignment
new Label("Icon positioning"),
new Group(AxisLayout.horizontal().gap(10), GREENBG).add(
new Label("Left", tileIcon(squares, 0)).setStyles(Style.ICON_POS.left),
new Label("Right", tileIcon(squares, 1)).setStyles(Style.ICON_POS.right),
new Label("Above", tileIcon(squares, 2)).setStyles(Style.ICON_POS.above,
Style.HALIGN.center),
new Label("Below", tileIcon(squares, 3)).setStyles(Style.ICON_POS.below,
Style.HALIGN.center)),
new Shim(5, 10),
// a captured root's widget
new Label("Root capture"),
new Group(AxisLayout.vertical()).addStyles(
Style.BACKGROUND.is(Background.solid(Colors.RED).inset(10))).add(
capRoot.createWidget())),
// right column
new Group(AxisLayout.vertical()).add(
// buttons, toggle buttons, wirey uppey
new Label("Buttons"),
buttonsSection(squares),
new Shim(5, 10),
// an editable text field
new Label("Text editing"),
editable = new Field("Editable text").setConstraint(Constraints.fixedWidth(150)),
setField = new Button("Set -> "),
disabled = new Field("Disabled text").setEnabled(false)));
capRoot.add(new Label("Captured Root!").addStyles(
Style.BACKGROUND.is(Background.blank().inset(10)))).pack();
// add a style animation to the captured root (clicking on cap roots NYI)
this.iface.animator().repeat(_root.layer).delay(1000).then().action(new Runnable() {
int cycle;
@Override public void run () {
capRoot.addStyles(Style.BACKGROUND.is(cycle++ % 2 == 0 ?
Background.solid(Colors.WHITE).alpha(.5f) : Background.blank()));
}
});
toggle.checked.update(true);
toggle.checked.connect(label2.visibleSlot());
toggle2.checked.map(new Function<Boolean,Icon>() {
public Icon apply (Boolean checked) {
return checked ? tileIcon(squares, 0) : null;
}
}).connect(label2.icon.slot());
final Field source = editable, target = disabled;
setField.clicked().connect(new UnitSlot() {
@Override public void onEmit () {
PlayN.log().info("Setting text to " + source.text.get());
target.text.update(source.text.get());
}
});
return iface;
}
protected Group buttonsSection (Image squares) {
ToggleButton toggle3 = new ToggleButton("Toggle Enabled");
Button disabled = new Button("Disabled");
toggle3.selected().connectNotify(disabled.enabledSlot());
toggle3.selected().map(new Function<Boolean,String>() {
public String apply (Boolean selected) { return selected ? "Enabled" : "Disabled"; }
}).connectNotify(disabled.text.slot());
final Label pressResult = new Label();
final IntValue clickCount = new IntValue(0);
final Box box = new Box();
return new Group(AxisLayout.vertical().offEqualize()).add(
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
toggle3, AxisLayout.stretch(disabled)),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new LongPressButton("Long Pressable").onLongPress(new UnitSlot() {
@Override public void onEmit () { pressResult.text.update("Long pressed"); }
}).onClick(new UnitSlot() {
@Override public void onEmit () { pressResult.text.update("Clicked"); }
}), AxisLayout.stretch(pressResult)),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new Label("Image button"),
new ImageButton(tile(squares, 0), tile(squares, 1)).onClick(new UnitSlot() {
@Override public void onEmit () { clickCount.increment(1); }
}),
new ValueLabel(clickCount)),
new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
new Button("Fill Box").onClick(new UnitSlot() {
@Override public void onEmit () {
box.set(new Label(box.contents() == null ? "Filled" : "Refilled"));
}
}),
box)
);
}
protected Image tile (Image image, int index) {
final float iwidth = 16, iheight = 16;
return image.subImage(index*iwidth, 0, iwidth, iheight);
}
protected Icon tileIcon (Image image, int index) {
return Icons.image(tile(image, index));
}
protected static final Styles GREENBG = Styles.make(
Style.BACKGROUND.is(Background.solid(0xFF99CC66).inset(5)));
protected static final Styles REDBG = Styles.make(
Style.BACKGROUND.is(Background.solid(0xFFCC6666).inset(5)));
}
| Add an example of making a button throb.
This requires too much hackery, so I'm going to do something to make it less
ugly.
| demo/core/src/main/java/tripleplay/demo/ui/MiscDemo.java | Add an example of making a button throb. | <ide><path>emo/core/src/main/java/tripleplay/demo/ui/MiscDemo.java
<ide>
<ide> import playn.core.Image;
<ide> import playn.core.PlayN;
<add>
<add>import pythagoras.f.MathUtil;
<ide>
<ide> import react.Function;
<ide> import react.IntValue;
<ide> public String apply (Boolean selected) { return selected ? "Enabled" : "Disabled"; }
<ide> }).connectNotify(disabled.text.slot());
<ide>
<add> class ThrobButton extends Button {
<add> public ThrobButton (String title) {
<add> super(title);
<add> }
<add> public void throb () {
<add> root().iface().animator().
<add> tweenScale(layer).to(1.2f).in(300.0f).easeIn().then().
<add> tweenScale(layer).to(1.0f).in(300.0f).easeOut();
<add> }
<add> @Override protected void layout () {
<add> super.layout();
<add> float ox = MathUtil.ifloor(_size.width/2), oy = MathUtil.ifloor(_size.height/2);
<add> layer.setOrigin(ox, oy);
<add> layer.transform().translate(ox, oy);
<add> }
<add> }
<add> final ThrobButton throbber = new ThrobButton("Throbber");
<add>
<ide> final Label pressResult = new Label();
<ide> final IntValue clickCount = new IntValue(0);
<ide> final Box box = new Box();
<ide> box.set(new Label(box.contents() == null ? "Filled" : "Refilled"));
<ide> }
<ide> }),
<del> box)
<add> box),
<add> new Group(AxisLayout.horizontal().gap(15), GREENBG).add(
<add> throbber.onClick(new UnitSlot() {
<add> @Override public void onEmit () {
<add> throbber.throb();
<add> }
<add> }))
<ide> );
<ide> }
<ide> |
|
Java | apache-2.0 | 29c3ccfc78738a319ce172844c71a3d9c2bf2965 | 0 | google/or-tools,or-tools/or-tools,or-tools/or-tools,google/or-tools,or-tools/or-tools,google/or-tools,google/or-tools,google/or-tools,or-tools/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools | // Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ortools;
import com.sun.jna.Platform;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.Objects;
/** Load native libraries needed for using ortools-java.*/
public class Loader {
private static final String RESOURCE_PATH = "ortools-" + Platform.RESOURCE_PREFIX + "/";
/** Try to locate the native libraries directory.*/
private static URI getNativeResourceURI() throws IOException {
ClassLoader loader = Loader.class.getClassLoader();
URL resourceURL = loader.getResource(RESOURCE_PATH);
Objects.requireNonNull(resourceURL,
String.format("Resource %s was not found in ClassLoader %s", RESOURCE_PATH, loader));
URI resourceURI;
try {
resourceURI = resourceURL.toURI();
} catch (URISyntaxException e) {
throw new IOException(e);
}
return resourceURI;
}
@FunctionalInterface
private interface PathConsumer<T extends IOException> {
void accept(Path path) throws T;
}
/**
* Extract native resources in a temp directory.
* @param resourceURI Native resource location.
* @return The directory path containing all extracted libraries.
*/
private static Path unpackNativeResources(URI resourceURI) throws IOException {
Path tempPath;
tempPath = Files.createTempDirectory("ortools-java");
tempPath.toFile().deleteOnExit();
PathConsumer<?> visitor;
visitor = (Path sourcePath) -> Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path newPath = tempPath.resolve(sourcePath.getParent().relativize(file).toString());
Files.copy(file, newPath);
newPath.toFile().deleteOnExit();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
Path newPath = tempPath.resolve(sourcePath.getParent().relativize(dir).toString());
Files.copy(dir, newPath);
newPath.toFile().deleteOnExit();
return FileVisitResult.CONTINUE;
}
});
FileSystem fs;
try {
fs = FileSystems.newFileSystem(resourceURI, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException e) {
fs = FileSystems.getFileSystem(resourceURI);
if (fs == null) {
throw new IllegalArgumentException();
}
}
Path p = fs.provider().getPath(resourceURI);
visitor.accept(p);
return tempPath;
}
/** Unpack and Load the native libraries needed for using ortools-java.*/
private static boolean loaded = false;
public static synchronized void loadNativeLibraries() {
if (!loaded) {
try {
URI resourceURI = getNativeResourceURI();
Path tempPath = unpackNativeResources(resourceURI);
// Load the native library
System.load(tempPath.resolve(RESOURCE_PATH)
.resolve(System.mapLibraryName("jniortools"))
.toString());
loaded = true;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| ortools/java/com/google/ortools/Loader.java | // Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ortools;
import com.sun.jna.Platform;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.Objects;
/** Load native libraries needed for using ortools-java.*/
public class Loader {
private static final String RESOURCE_PATH = "ortools-" + Platform.RESOURCE_PREFIX + "/";
/** Try to locate the native libraries directory.*/
private static URI getNativeResourceURI() throws IOException {
ClassLoader loader = Loader.class.getClassLoader();
URL resourceURL = loader.getResource(RESOURCE_PATH);
Objects.requireNonNull(resourceURL,
String.format("Resource %s was not found in ClassLoader %s", RESOURCE_PATH, loader));
URI resourceURI;
try {
resourceURI = resourceURL.toURI();
} catch (URISyntaxException e) {
throw new IOException(e);
}
return resourceURI;
}
@FunctionalInterface
private interface PathConsumer<T extends IOException> {
void accept(Path path) throws T;
}
/**
* Extract native resources in a temp directory.
* @param resourceURI Native resource location.
* @return The directory path containing all extracted libraries.
*/
private static Path unpackNativeResources(URI resourceURI) throws IOException {
Path tempPath;
tempPath = Files.createTempDirectory("ortools-java");
tempPath.toFile().deleteOnExit();
PathConsumer<?> visitor;
visitor = (Path sourcePath) -> Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path newPath = tempPath.resolve(sourcePath.getParent().relativize(file).toString());
Files.copy(file, newPath);
newPath.toFile().deleteOnExit();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
Path newPath = tempPath.resolve(sourcePath.getParent().relativize(dir).toString());
Files.copy(dir, newPath);
newPath.toFile().deleteOnExit();
return FileVisitResult.CONTINUE;
}
});
FileSystem fs;
try {
fs = FileSystems.newFileSystem(resourceURI, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException e) {
fs = FileSystems.getFileSystem(resourceURI);
if (fs == null) {
throw new IllegalArgumentException();
}
}
Path p = fs.provider().getPath(resourceURI);
visitor.accept(p);
return tempPath;
}
/** Unpack and Load the native libraries needed for using ortools-java.*/
private static boolean loaded = false;
public static void loadNativeLibraries() {
if (!loaded) {
try {
URI resourceURI = getNativeResourceURI();
Path tempPath = unpackNativeResources(resourceURI);
// Load the native library
System.load(tempPath.resolve(RESOURCE_PATH)
.resolve(System.mapLibraryName("jniortools"))
.toString());
loaded = true;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| java: Make loadeNativeLibraries() a static synchronized function.
| ortools/java/com/google/ortools/Loader.java | java: Make loadeNativeLibraries() a static synchronized function. | <ide><path>rtools/java/com/google/ortools/Loader.java
<ide>
<ide> /** Unpack and Load the native libraries needed for using ortools-java.*/
<ide> private static boolean loaded = false;
<del> public static void loadNativeLibraries() {
<add> public static synchronized void loadNativeLibraries() {
<ide> if (!loaded) {
<ide> try {
<ide> URI resourceURI = getNativeResourceURI(); |
|
Java | apache-2.0 | 69b72f8c2da47134c44a24aade8dff1c0a1f9d2a | 0 | e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools,e-Spirit/FSDevTools | /*
*
* *********************************************************************
* fsdevtools
* %%
* Copyright (C) 2016 e-Spirit AG
* %%
* 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.espirit.moddev.cli;
import com.espirit.moddev.cli.api.CliContext;
import com.espirit.moddev.cli.api.configuration.Config;
import com.espirit.moddev.cli.exception.CliError;
import com.espirit.moddev.cli.exception.CliException;
import de.espirit.firstspirit.access.AdminService;
import de.espirit.firstspirit.access.Connection;
import de.espirit.firstspirit.access.ConnectionManager;
import de.espirit.firstspirit.access.UserService;
import de.espirit.firstspirit.access.admin.ProjectStorage;
import de.espirit.firstspirit.access.project.Project;
import de.espirit.firstspirit.agency.BrokerAgent;
import de.espirit.firstspirit.agency.ServerInformationAgent;
import de.espirit.firstspirit.agency.SpecialistType;
import de.espirit.firstspirit.agency.SpecialistsBroker;
import de.espirit.firstspirit.common.IOError;
import de.espirit.firstspirit.common.MaximumNumberOfSessionsExceededException;
import de.espirit.firstspirit.server.authentication.AuthenticationException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Default implementation of {@link com.espirit.moddev.cli.api.CliContext}.
*
* @author e-Spirit AG
*/
public class CliContextImpl implements CliContext {
private static final Logger LOGGER = LoggerFactory.getLogger(CliContextImpl.class);
private final Map<String, Object> properties;
private final Config clientConfig;
private Connection connection;
private SpecialistsBroker projectBroker;
/**
* Create a new instance that uses the given {@link com.espirit.moddev.cli.api.configuration.Config}.
*
* @param clientConfig the configuration to be used
* @throws java.lang.IllegalArgumentException if clientConfig is null
*/
public CliContextImpl(final Config clientConfig) {
if (clientConfig == null) {
throw new IllegalArgumentException("Config is null!");
}
this.clientConfig = clientConfig;
properties = new HashMap<>();
initializeFirstSpiritConnection();
}
private void initializeFirstSpiritConnection() {
openConnection();
requireProjectSpecificBroker();
}
protected void openConnection() {
try {
connection = obtainConnection();
Object[] args = {clientConfig.getHost(), clientConfig.getPort(), clientConfig.getUser()};
LOGGER.debug("Connect to FirstSpirit server '{}:{}' with user '{}'...", args);
connection.connect();
final ServerInformationAgent serverInformationAgent = connection.getBroker().requestSpecialist(ServerInformationAgent.TYPE);
if (serverInformationAgent != null) {
final ServerInformationAgent.VersionInfo serverVersion = serverInformationAgent.getServerVersion();
LOGGER.info("Connected to FirstSpirit server at {} of version {}",
new Object[]{clientConfig.getHost(), serverVersion.getFullVersionString()});
}
} catch (MaximumNumberOfSessionsExceededException e) {
throw new CliException(CliError.SESSIONS, clientConfig, e);
} catch (AuthenticationException e) {
throw new CliException(CliError.AUTHENTICATION, clientConfig, e);
} catch (IOException e) {
throw new CliException(CliError.GENERAL_IO, clientConfig, e);
} catch (IOError e) {
throw new CliException(e);
} catch (Exception e) { //NOSONAR
throw new CliException(CliError.UNEXPECTED, clientConfig, e);
}
}
/**
* Connect to the FirstSpirit server using the configuration of this instance.
*
* @return a connection to a FirstSpirit server
*/
protected Connection obtainConnection() {
return ConnectionManager
.getConnection(clientConfig.getHost(), clientConfig.getPort(), clientConfig.getConnectionMode().getCode(), clientConfig.getUser(),
clientConfig.getPassword());
}
private void requireProjectSpecificBroker() {
LOGGER.debug("Require project specific specialist broker for project '{}'...", clientConfig.getProject());
String name;
try {
final Project project = getProject();
name = project != null ? project.getName() : null;
} catch (Exception e) { //NOSONAR
throw new IllegalStateException(
"Project '" + clientConfig.getProject() + "' not found on server. Correct project name or omit --dont-create-project option.", e);
}
if (StringUtils.isNotBlank(name)) {
final SpecialistsBroker broker = connection.getBroker();
final BrokerAgent brokerAgent = broker.requireSpecialist(BrokerAgent.TYPE);
projectBroker = brokerAgent.getBrokerByProjectName(name);
}
if (projectBroker == null) {
throw new IllegalStateException("ProjectBroker cannot be retrieved for project " + name + ". Wrong project name?");
}
}
@Override
public UserService getUserService() {
return getProject().getUserService();
}
@Override
public Project getProject() {
final String projectName = clientConfig.getProject();
if(StringUtils.isBlank(projectName)) {
return null;
}
Project project = connection.getProjectByName(projectName);
if (project == null && clientConfig.isCreatingProjectIfMissing()) {
project = createProject(projectName);
}
LOGGER.debug("activate project if deactivated: " + clientConfig.isActivateProjectIfDeactivated(), projectName);
if (clientConfig.isActivateProjectIfDeactivated()) {
activateProject(projectName, project);
}
LOGGER.info("project is '{}'", project);
return project;
}
private void activateProject(String projectName, Project project) {
if (project == null) {
throw new IllegalArgumentException("Project for activation is null");
}
if (!project.isActive()) {
LOGGER.warn("Project '{}' is not active! Try to activate...", projectName);
UserService userService = project.getUserService();
AdminService adminService = userService.getConnection().getService(AdminService.class);
adminService.getProjectStorage().activateProject(project);
} else {
LOGGER.debug("Project '{}' is already active! No need to activate...", projectName);
}
}
private Project createProject(String projectName) {
Project project;
LOGGER.info("Creating missing project '{}' on server...", projectName);
AdminService ac = connection.getService(AdminService.class);
final ProjectStorage projectStorage = ac.getProjectStorage();
project = projectStorage.createProject(projectName, projectName + " created by fs-cli");
return project;
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public Object getProperty(String name) {
return properties.get(name);
}
@Override
public void setProperty(String name, Object value) {
properties.put(name, value);
}
@Override
public void removeProperty(String name) {
properties.remove(name);
}
@Override
public String[] getProperties() {
return properties.values().toArray(new String[properties.size()]);
}
@Override
public void logError(String s) {
LOGGER.error(s);
}
@Override
public void logError(String s, Throwable throwable) {
LOGGER.error(s, throwable);
}
@Override
public void logWarning(String s) {
LOGGER.warn(s);
}
@Override
public void logDebug(String s) {
LOGGER.debug(s);
}
@Override
public void logInfo(String s) {
LOGGER.info(s);
}
@Override
public boolean is(Env env) {
return Env.HEADLESS == env;
}
@Override
public <S> S requestSpecialist(SpecialistType<S> type) {
return projectBroker.requestSpecialist(type);
}
@Override
public <S> S requireSpecialist(SpecialistType<S> type) {
return projectBroker.requireSpecialist(type);
}
@Override
public void close() throws Exception {
LOGGER.debug("Closing connection to FirstSpirit ...");
connection.close();
LOGGER.info("Connection to FirstSpirit closed!");
}
}
| fsdevtools-cli/src/main/java/com/espirit/moddev/cli/CliContextImpl.java | /*
*
* *********************************************************************
* fsdevtools
* %%
* Copyright (C) 2016 e-Spirit AG
* %%
* 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.espirit.moddev.cli;
import com.espirit.moddev.cli.api.CliContext;
import com.espirit.moddev.cli.api.configuration.Config;
import com.espirit.moddev.cli.exception.CliError;
import com.espirit.moddev.cli.exception.CliException;
import de.espirit.firstspirit.access.AdminService;
import de.espirit.firstspirit.access.Connection;
import de.espirit.firstspirit.access.ConnectionManager;
import de.espirit.firstspirit.access.UserService;
import de.espirit.firstspirit.access.admin.ProjectStorage;
import de.espirit.firstspirit.access.project.Project;
import de.espirit.firstspirit.agency.BrokerAgent;
import de.espirit.firstspirit.agency.ServerInformationAgent;
import de.espirit.firstspirit.agency.SpecialistType;
import de.espirit.firstspirit.agency.SpecialistsBroker;
import de.espirit.firstspirit.common.IOError;
import de.espirit.firstspirit.common.MaximumNumberOfSessionsExceededException;
import de.espirit.firstspirit.server.authentication.AuthenticationException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Default implementation of {@link com.espirit.moddev.cli.api.CliContext}.
*
* @author e-Spirit AG
*/
public class CliContextImpl implements CliContext {
private static final Logger LOGGER = LoggerFactory.getLogger(CliContextImpl.class);
private final Map<String, Object> properties;
private final Config clientConfig;
private Connection connection;
private SpecialistsBroker projectBroker;
/**
* Create a new instance that uses the given {@link com.espirit.moddev.cli.api.configuration.Config}.
*
* @param clientConfig the configuration to be used
* @throws java.lang.IllegalArgumentException if clientConfig is null
*/
public CliContextImpl(final Config clientConfig) {
if (clientConfig == null) {
throw new IllegalArgumentException("Config is null!");
}
this.clientConfig = clientConfig;
properties = new HashMap<>();
initializeFirstSpiritConnection();
}
private void initializeFirstSpiritConnection() {
openConnection();
requireProjectSpecificBroker();
}
protected void openConnection() {
try {
connection = obtainConnection();
Object[] args = {clientConfig.getHost(), clientConfig.getPort(), clientConfig.getUser()};
LOGGER.debug("Connect to FirstSpirit server '{}:{}' with user '{}'...", args);
connection.connect();
final ServerInformationAgent serverInformationAgent = connection.getBroker().requestSpecialist(ServerInformationAgent.TYPE);
if (serverInformationAgent != null) {
final ServerInformationAgent.VersionInfo serverVersion = serverInformationAgent.getServerVersion();
LOGGER.info("Connected to FirstSpirit server at {} of version {}",
new Object[]{clientConfig.getHost(), serverVersion.getFullVersionString()});
}
} catch (MaximumNumberOfSessionsExceededException e) {
throw new CliException(CliError.SESSIONS, clientConfig, e);
} catch (AuthenticationException e) {
throw new CliException(CliError.AUTHENTICATION, clientConfig, e);
} catch (IOException e) {
throw new CliException(CliError.GENERAL_IO, clientConfig, e);
} catch (IOError e) {
throw new CliException(e);
} catch (Exception e) { //NOSONAR
throw new CliException(CliError.UNEXPECTED, clientConfig, e);
}
}
/**
* Connect to the FirstSpirit server using the configuration of this instance.
*
* @return a connection to a FirstSpirit server
*/
protected Connection obtainConnection() {
return ConnectionManager
.getConnection(clientConfig.getHost(), clientConfig.getPort(), clientConfig.getConnectionMode().getCode(), clientConfig.getUser(),
clientConfig.getPassword());
}
private void requireProjectSpecificBroker() {
LOGGER.debug("Require project specific specialist broker for project '{}'...", clientConfig.getProject());
String name;
try {
final Project project = getProject();
name = project != null ? project.getName() : null;
} catch (Exception e) { //NOSONAR
throw new IllegalStateException(
"Project '" + clientConfig.getProject() + "' not found on server. Correct project name or omit --dont-create-project option.", e);
}
if (StringUtils.isNotBlank(name)) {
final SpecialistsBroker broker = connection.getBroker();
final BrokerAgent brokerAgent = broker.requireSpecialist(BrokerAgent.TYPE);
projectBroker = brokerAgent.getBrokerByProjectName(name);
}
if (projectBroker == null) {
throw new IllegalStateException("ProjectBroker cannot be retrieved for project " + name + ". Wrong project name?");
}
}
@Override
public UserService getUserService() {
return getProject().getUserService();
}
@Override
public Project getProject() {
final String projectName = clientConfig.getProject();
if(StringUtils.isBlank(projectName)) {
return null;
}
Project project = connection.getProjectByName(projectName);
if (project == null && clientConfig.isCreatingProjectIfMissing()) {
project = createProject(projectName);
}
LOGGER.debug("activate project if deactivated: " + clientConfig.isActivateProjectIfDeactivated(), projectName);
if (clientConfig.isActivateProjectIfDeactivated()) {
activateProject(projectName, project);
}
LOGGER.debug("project is '{}'", project);
return project;
}
private void activateProject(String projectName, Project project) {
if (project == null) {
throw new IllegalArgumentException("Project for activation is null");
}
if (!project.isActive()) {
LOGGER.warn("Project '{}' is not active! Try to activate...", projectName);
UserService userService = project.getUserService();
AdminService adminService = userService.getConnection().getService(AdminService.class);
adminService.getProjectStorage().activateProject(project);
} else {
LOGGER.debug("Project '{}' is already active! No need to activate...", projectName);
}
}
private Project createProject(String projectName) {
Project project;
LOGGER.info("Creating missing project '{}' on server...", projectName);
AdminService ac = connection.getService(AdminService.class);
final ProjectStorage projectStorage = ac.getProjectStorage();
project = projectStorage.createProject(projectName, projectName + " created by fs-cli");
return project;
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public Object getProperty(String name) {
return properties.get(name);
}
@Override
public void setProperty(String name, Object value) {
properties.put(name, value);
}
@Override
public void removeProperty(String name) {
properties.remove(name);
}
@Override
public String[] getProperties() {
return properties.values().toArray(new String[properties.size()]);
}
@Override
public void logError(String s) {
LOGGER.error(s);
}
@Override
public void logError(String s, Throwable throwable) {
LOGGER.error(s, throwable);
}
@Override
public void logWarning(String s) {
LOGGER.warn(s);
}
@Override
public void logDebug(String s) {
LOGGER.debug(s);
}
@Override
public void logInfo(String s) {
LOGGER.info(s);
}
@Override
public boolean is(Env env) {
return Env.HEADLESS == env;
}
@Override
public <S> S requestSpecialist(SpecialistType<S> type) {
return projectBroker.requestSpecialist(type);
}
@Override
public <S> S requireSpecialist(SpecialistType<S> type) {
return projectBroker.requireSpecialist(type);
}
@Override
public void close() throws Exception {
LOGGER.debug("Closing connection to FirstSpirit ...");
connection.close();
LOGGER.info("Connection to FirstSpirit closed!");
}
}
| DEVEX-78 - changed logging of project from debug to info
| fsdevtools-cli/src/main/java/com/espirit/moddev/cli/CliContextImpl.java | DEVEX-78 - changed logging of project from debug to info | <ide><path>sdevtools-cli/src/main/java/com/espirit/moddev/cli/CliContextImpl.java
<ide> if (clientConfig.isActivateProjectIfDeactivated()) {
<ide> activateProject(projectName, project);
<ide> }
<del> LOGGER.debug("project is '{}'", project);
<add> LOGGER.info("project is '{}'", project);
<ide> return project;
<ide> }
<ide> |
|
JavaScript | agpl-3.0 | b0f0bcc29439eea7be46ffbb529d5e0bba969252 | 0 | Mapotempo/optimizer-api,Mapotempo/optimizer-api,Mapotempo/optimizer-api,Mapotempo/optimizer-api |
var jobStatusTimeout = null;
var requestPendingAllJobs = false;
function buildDownloadLink(jobId, state) {
var extension = state === 'failed' ? '.json' : '';
var msg = state === 'failed'
? 'Télécharger le rapport d\'erreur de l\'optimisation'
: 'Télécharger le résultat de l\'optimisation';
var url = "http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs/" + jobId + extension + '?api_key=' + getParams()['api_key'];
return ' <a download="result' + extension + '"' + ' href="' + url + '">' + msg + '</a>';
}
var jobsManager = {
jobs: [],
htmlElements: {
builder: function (jobs) {
$(jobs).each(function () {
currentJob = this;
var donwloadBtn = currentJob.status === 'completed' || currentJob.status === 'failed';
var jobDOM =
'<div class="job">'
+ '<span class="optim-start">' + (new Date(currentJob.time)).toLocaleString('fr-FR') + ' : </span>'
+ '<span class="job_title">' + 'Job N° <b>' + currentJob.uuid + '</b></span> '
+ '<button value=' + currentJob.uuid + ' data-role="delete">'
+ ((currentJob.status === 'queued' || currentJob.status === 'working') ? i18n.killOptim : i18n.deleteOptim)
+ '</button>'
+ ' (Status: ' + currentJob.status + ')'
+ (donwloadBtn ? buildDownloadLink(currentJob.uuid, currentJob.status) : '')
+ '</div>';
$('#jobs-list').append(jobDOM);
});
$('#jobs-list button').on('click', function () {
jobsManager.roleDispatcher(this);
});
}
},
roleDispatcher: function (object) {
switch ($(object).data('role')) {
case 'focus':
//actually in building, create to apply different behavior to the button object restartJob, actually not set. #TODO
break;
case 'delete':
this.ajaxDeleteJob($(object).val());
break;
}
},
ajaxGetJobs: function (timeinterval) {
var ajaxload = function () {
if (!requestPendingAllJobs) {
requestPendingAllJobs = true;
$.ajax({
url: 'http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs',
type: 'get',
dataType: 'json',
data: { api_key: getParams()['api_key'] },
complete: function () { requestPendingAllJobs = false; }
}).done(function (data) {
jobsManager.shouldUpdate(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
clearInterval(window.AjaxGetRequestInterval);
if (jqXHR.status == 401) {
$('#optim-list-status').prepend('<div class="error">' + i18n.unauthorizedError + '</div>');
$('form input, form button').prop('disabled', true);
}
});
}
};
if (timeinterval) {
ajaxload();
window.AjaxGetRequestInterval = setInterval(ajaxload, 5000);
} else {
ajaxload();
}
},
ajaxDeleteJob: function (uuid) {
$.ajax({
url: 'http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs/0.1/vrp/jobs/' + uuid,
type: 'delete',
dataType: 'json',
data: {
api_key: getParams()['api_key']
},
}).done(function (data) {
if (debug) { console.log("the uuid has been deleted from the jobs queue & the DB"); }
$('button[data-role="delete"][value="' + uuid + '"]').fadeOut(500, function () { $(this).closest('.job').remove(); });
});
},
shouldUpdate: function (data) {
// erase list if no job running
if (data.length === 0 && jobsManager.jobs.length !== 0) {
$('#jobs-list').empty();
}
//check if chagements occurs in the data api. #TODO, update if more params are needed.
$(data).each(function (index, object) {
if (jobsManager.jobs.length > 0) {
if (object.status != jobsManager.jobs[index].status || jobsManager.jobs.length != data.length) {
jobsManager.jobs = data;
$('#jobs-list').empty();
jobsManager.htmlElements.builder(jobsManager.jobs);
}
}
else {
jobsManager.jobs = data;
$('#jobs-list').empty();
jobsManager.htmlElements.builder(jobsManager.jobs);
}
});
},
checkJobStatus: function (options, cb) {
var nbError = 0;
var requestPendingJobTimeout = false;
if (options.interval) {
jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
return;
}
requestPendingJob();
function requestPendingJob() {
$.ajax({
type: 'GET',
contentType: 'application/json',
url: 'http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs/'
+ (options.job.id || options.job.uuid)
// + (options.format ? options.format : '')
+ '?api_key=' + getParams()["api_key"],
success: function (job, _, xhr) {
if (options.interval && (checkJSONJob(job) || checkCSVJob(xhr))) {
if (debug) console.log("REQUEST PENDING JOB", checkCSVJob(xhr), checkJSONJob(job));
requestPendingJobTimeout = true;
}
nbError = 0;
cb(null, job, xhr);
},
error: function (xhr, status) {
++nbError
if (nbError > 2) {
cb({ xhr, status });
return alert(i18n.failureOptim(nbError, status));
}
requestPendingJobTimeout = true;
},
complete: function () {
if (requestPendingJobTimeout) {
requestPendingJobTimeout = false;
// interval max: 1mins
options.interval *= 2;
if (options.interval > 60000) {
options.interval = 60000
}
jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
}
}
});
}
},
stopJobChecking: function () {
requestPendingJobTimeout = false;
clearTimeout(jobStatusTimeout);
}
};
function checkCSVJob(xhr) {
if (debug) console.log(xhr, xhr.status);
return (xhr.status !== 200 && xhr.status !== 202);
}
function checkJSONJob(job) {
if (debug) console.log("JOB: ", job, (job.job && job.job.status !== 'completed'));
return ((job.job && job.job.status !== 'completed') && typeof job !== 'string')
}
| public/js/jobManager.js |
var jobStatusTimeout = null;
var requestPendingAllJobs = false;
var jobsManager = {
jobs: [],
htmlElements: {
builder: function (jobs) {
$(jobs).each(function () {
currentJob = this;
var donwloadBtn = currentJob.status === 'completed' || currentJob.status === 'failed';
var completed = (currentJob.status === 'completed' || currentJob.status === 'failed') ? true : false;
var msg = currentJob.status === 'failed'
? 'Télécharger le rapport d\'erreur de l\'optimisation'
: 'Télécharger le résultat de l\'optimisation';
var jobDOM =
'<div class="job">'
+ '<span class="optim-start">' + (new Date(currentJob.time)).toLocaleString('fr-FR') + ' : </span>'
+ '<span class="job_title">' + 'Job N° <b>' + currentJob.uuid + '</b></span> '
+ '<button value=' + currentJob.uuid + ' data-role="delete">'
+ ((currentJob.status === 'queued' || currentJob.status === 'working') ? i18n.killOptim : i18n.deleteOptim)
+ '</button>'
+ ' (Status: ' + currentJob.status + ')'
+ (donwloadBtn ? ' <a data-job-id=' + currentJob.uuid + ' href="#">' + msg + '</a>' : '')
+ '</div>';
$('#jobs-list').append(jobDOM);
if (completed) {
$('a[data-job-id="' + currentJob.uuid + '"').on('click', function (e) {
e.preventDefault();
jobsManager.checkJobStatus({
job: currentJob,
}, function (err, job) {
if (err) {
if (debug) console.error(err);
return alert("An error occured");
}
if (typeof job === 'string') {
$('#result').html(job)
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(job);
a.target = '_blank';
a.download = 'result.csv';
document.body.appendChild(a);
a.click();
}
else {
var solution = job.solutions[0];
$('#result').html(JSON.stringify(solution, null, 4));
var a = document.createElement('a');
a.href = 'data:attachment/json,' + encodeURIComponent(JSON.stringify(solution, null, 4));
a.target = '_blank';
a.download = 'result.json';
document.body.appendChild(a);
a.click();
}
});
})
}
});
$('#jobs-list button').on('click', function () {
jobsManager.roleDispatcher(this);
});
}
},
roleDispatcher: function (object) {
switch ($(object).data('role')) {
case 'focus':
//actually in building, create to apply different behavior to the button object restartJob, actually not set. #TODO
break;
case 'delete':
this.ajaxDeleteJob($(object).val());
break;
}
},
ajaxGetJobs: function (timeinterval) {
var ajaxload = function () {
if (!requestPendingAllJobs) {
requestPendingAllJobs = true;
$.ajax({
url: '/0.1/vrp/jobs',
type: 'get',
dataType: 'json',
data: { api_key: getParams()['api_key'] },
complete: function () { requestPendingAllJobs = false; }
}).done(function (data) {
jobsManager.shouldUpdate(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
clearInterval(window.AjaxGetRequestInterval);
if (jqXHR.status == 401) {
$('#optim-list-status').prepend('<div class="error">' + i18n.unauthorizedError + '</div>');
$('form input, form button').prop('disabled', true);
}
});
}
};
if (timeinterval) {
ajaxload();
window.AjaxGetRequestInterval = setInterval(ajaxload, 5000);
} else {
ajaxload();
}
},
ajaxDeleteJob: function (uuid) {
$.ajax({
url: '/0.1/vrp/jobs/' + uuid,
type: 'delete',
dataType: 'json',
data: {
api_key: getParams()['api_key']
},
}).done(function (data) {
if (debug) { console.log("the uuid has been deleted from the jobs queue & the DB"); }
$('button[data-role="delete"][value="' + uuid + '"]').fadeOut(500, function () { $(this).closest('.job').remove(); });
});
},
shouldUpdate: function (data) {
// erase list if no job running
if (data.length === 0 && jobsManager.jobs.length !== 0) {
$('#jobs-list').empty();
}
//check if chagements occurs in the data api. #TODO, update if more params are needed.
$(data).each(function (index, object) {
if (jobsManager.jobs.length > 0) {
if (object.status != jobsManager.jobs[index].status || jobsManager.jobs.length != data.length) {
jobsManager.jobs = data;
$('#jobs-list').empty();
jobsManager.htmlElements.builder(jobsManager.jobs);
}
}
else {
jobsManager.jobs = data;
$('#jobs-list').empty();
jobsManager.htmlElements.builder(jobsManager.jobs);
}
});
},
checkJobStatus: function (options, cb) {
var nbError = 0;
var requestPendingJobTimeout = false;
if (options.interval) {
jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
return;
}
requestPendingJob();
function requestPendingJob() {
$.ajax({
type: 'GET',
contentType: 'application/json',
url: '/0.1/vrp/jobs/'
+ (options.job.id || options.job.uuid)
// + (options.format ? options.format : '')
+ '?api_key=' + getParams()["api_key"],
success: function (job, _, xhr) {
if (options.interval && (checkJSONJob(job) || checkCSVJob(xhr))) {
if (debug) console.log("REQUEST PENDING JOB", checkCSVJob(xhr), checkJSONJob(job));
requestPendingJobTimeout = true;
}
nbError = 0;
cb(null, job, xhr);
},
error: function (xhr, status) {
++nbError
if (nbError > 2) {
cb({ xhr, status });
return alert(i18n.failureOptim(nbError, status));
}
requestPendingJobTimeout = true;
},
complete: function () {
if (requestPendingJobTimeout) {
requestPendingJobTimeout = false;
// interval max: 1mins
options.interval *= 2;
if (options.interval > 60000) {
options.interval = 60000
}
jobStatusTimeout = setTimeout(requestPendingJob, options.interval);
}
}
});
}
},
stopJobChecking: function () {
requestPendingJobTimeout = false;
clearTimeout(jobStatusTimeout);
}
};
function checkCSVJob(xhr) {
if (debug) console.log(xhr, xhr.status);
return (xhr.status !== 200 && xhr.status !== 202);
}
function checkJSONJob(job) {
if (debug) console.log("JOB: ", job, (job.job && job.job.status !== 'completed'));
return ((job.job && job.job.status !== 'completed') && typeof job !== 'string')
}
| Fix download link taking last job id
| public/js/jobManager.js | Fix download link taking last job id | <ide><path>ublic/js/jobManager.js
<ide>
<ide> var jobStatusTimeout = null;
<ide> var requestPendingAllJobs = false;
<add>
<add>function buildDownloadLink(jobId, state) {
<add> var extension = state === 'failed' ? '.json' : '';
<add> var msg = state === 'failed'
<add> ? 'Télécharger le rapport d\'erreur de l\'optimisation'
<add> : 'Télécharger le résultat de l\'optimisation';
<add>
<add> var url = "http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs/" + jobId + extension + '?api_key=' + getParams()['api_key'];
<add>
<add> return ' <a download="result' + extension + '"' + ' href="' + url + '">' + msg + '</a>';
<add>}
<ide>
<ide> var jobsManager = {
<ide> jobs: [],
<ide> currentJob = this;
<ide> var donwloadBtn = currentJob.status === 'completed' || currentJob.status === 'failed';
<ide>
<del> var completed = (currentJob.status === 'completed' || currentJob.status === 'failed') ? true : false;
<del> var msg = currentJob.status === 'failed'
<del> ? 'Télécharger le rapport d\'erreur de l\'optimisation'
<del> : 'Télécharger le résultat de l\'optimisation';
<del>
<ide> var jobDOM =
<ide> '<div class="job">'
<ide> + '<span class="optim-start">' + (new Date(currentJob.time)).toLocaleString('fr-FR') + ' : </span>'
<ide> + ((currentJob.status === 'queued' || currentJob.status === 'working') ? i18n.killOptim : i18n.deleteOptim)
<ide> + '</button>'
<ide> + ' (Status: ' + currentJob.status + ')'
<del> + (donwloadBtn ? ' <a data-job-id=' + currentJob.uuid + ' href="#">' + msg + '</a>' : '')
<add> + (donwloadBtn ? buildDownloadLink(currentJob.uuid, currentJob.status) : '')
<ide> + '</div>';
<ide>
<ide> $('#jobs-list').append(jobDOM);
<ide>
<del> if (completed) {
<del> $('a[data-job-id="' + currentJob.uuid + '"').on('click', function (e) {
<del> e.preventDefault();
<del> jobsManager.checkJobStatus({
<del> job: currentJob,
<del> }, function (err, job) {
<del> if (err) {
<del> if (debug) console.error(err);
<del> return alert("An error occured");
<del> }
<del>
<del> if (typeof job === 'string') {
<del> $('#result').html(job)
<del> var a = document.createElement('a');
<del> a.href = 'data:attachment/csv,' + encodeURIComponent(job);
<del> a.target = '_blank';
<del> a.download = 'result.csv';
<del> document.body.appendChild(a);
<del> a.click();
<del> }
<del> else {
<del> var solution = job.solutions[0];
<del> $('#result').html(JSON.stringify(solution, null, 4));
<del> var a = document.createElement('a');
<del> a.href = 'data:attachment/json,' + encodeURIComponent(JSON.stringify(solution, null, 4));
<del> a.target = '_blank';
<del> a.download = 'result.json';
<del> document.body.appendChild(a);
<del> a.click();
<del> }
<del> });
<del> })
<del> }
<ide> });
<ide> $('#jobs-list button').on('click', function () {
<ide> jobsManager.roleDispatcher(this);
<ide> if (!requestPendingAllJobs) {
<ide> requestPendingAllJobs = true;
<ide> $.ajax({
<del> url: '/0.1/vrp/jobs',
<add> url: 'http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs',
<ide> type: 'get',
<ide> dataType: 'json',
<ide> data: { api_key: getParams()['api_key'] },
<ide> },
<ide> ajaxDeleteJob: function (uuid) {
<ide> $.ajax({
<del> url: '/0.1/vrp/jobs/' + uuid,
<add> url: 'http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs/0.1/vrp/jobs/' + uuid,
<ide> type: 'delete',
<ide> dataType: 'json',
<ide> data: {
<ide> $.ajax({
<ide> type: 'GET',
<ide> contentType: 'application/json',
<del> url: '/0.1/vrp/jobs/'
<add> url: 'http://optimizer.alpha.mapotempo.com/0.1/vrp/jobs/'
<ide> + (options.job.id || options.job.uuid)
<ide> // + (options.format ? options.format : '')
<ide> + '?api_key=' + getParams()["api_key"],
<ide> }
<ide> });
<ide> }
<del>
<ide> },
<ide> stopJobChecking: function () {
<ide> requestPendingJobTimeout = false; |
|
JavaScript | mit | 4e3d1de857799eb0e916eae37738c30a8cb57e4f | 0 | fizzvr/vr-web,fizzvr/vr-web | module.exports = function(grunt) {
// configuracion del proyecto
grunt.initConfig({
// metadatos
leerJson: grunt.file.readJSON('package.json'),
banner: '/**\n' +
'* <%= leerJson.name %> v<%= leerJson.version %> por @fizzvr\n' +
'*/\n',
// tarea de limpieza
clean: [
'./out'
],
// tarea de distribucion JS y CSS minified
frontendConfig: {
srcWebroot: './src/public/',
webroot: './out/'
},
frontend: {
main: {
css: {
src: './src/public/css',
dest: './out/cvr'
},
js: {
files: {
'./out/jvr/vrweb.js': [
'./src/public/js/plugins.js',
'./src/public/js/jsvr.js'
]
}
}
}
},
// tarea de copia de los archivos 3rd party
copy: {
main: {
files: [
{
expand: true,
flatten: true,
src: ["./src/public/js/activos/*"],
dest: './out/jvr/act'
}
]
}
},
// tarea de compresion de los HTML
/*htmlcompressor: {
compile: {
files: {
'full-dist/index.html': 'out/index.html'
},
options: {
type: 'html',
preserveServerScript: true
}
}
}
compress: {
target: {
files: {
'pack/<%= pkg.name %>.v<%= pkg.version %>.zip': ['prod/**']
}
}
}*/
});
// carga de los plugins para el proyecto
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-frontend');
// grunt.loadNpmTasks('grunt-htmlcompressor');
// distribucion JS y CSS
grunt.registerTask('dist-jscss', ['frontend']);
// distribucion de los activos
grunt.registerTask('dist-activos', ['copy']);
// compresion HTML
// grunt.registerTask('comp-hmtl', ['htmlcompressor']);
// distribucion FULL
grunt.registerTask('dist-full', ['clean', 'dist-jscss', 'dist-activos']);
// tarea por default
grunt.registerTask('default', ['dist-full']);
}; | Gruntfile.js | module.exports = function(grunt) {
// configuracion del proyecto
grunt.initConfig({
// metadatos
leerJson: grunt.file.readJSON('package.json'),
banner: '/**\n' +
'* <%= leerJson.name %> v<%= leerJson.version %> por @fizzvr\n' +
'*/\n',
// tarea de limpieza
clean: [
'./out'
],
// tarea de distribucion JS y CSS minified
frontendConfig: {
srcWebroot: './src/public/',
webroot: './out/'
},
frontend: {
main: {
css: {
src: './src/public/css',
dest: './out/cvr'
},
js: {
files: {
'./out/jvr/vrweb.js': [
'./src/public/js/plugins.js',
'./src/public/js/jsvr.js'
]
}
}
}
},
// tarea de copia de los archivos bs3
copy: {
main: {
files: [
{
expand: true,
flatten: true,
src: ["./src/public/js/activos/*"],
dest: './out/jvr/act'
}
]
}
},
// tarea de compresion de los HTML
/*htmlcompressor: {
compile: {
files: {
'full-dist/index.html': 'out/index.html'
},
options: {
type: 'html',
preserveServerScript: true
}
}
}
compress: {
target: {
files: {
'pack/<%= pkg.name %>.v<%= pkg.version %>.zip': ['prod/**']
}
}
}*/
});
// carga de los plugins para el proyecto
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-frontend');
// grunt.loadNpmTasks('grunt-htmlcompressor');
// distribucion JS y CSS
grunt.registerTask('dist-jscss', ['frontend']);
// distribucion de los activos
grunt.registerTask('dist-activos', ['copy']);
// compresion HTML
// grunt.registerTask('comp-hmtl', ['htmlcompressor']);
// distribucion FULL
grunt.registerTask('dist-full', ['clean', 'dist-jscss', 'dist-activos']);
// tarea por default
grunt.registerTask('default', ['dist-full']);
}; | archivos de terceros
| Gruntfile.js | archivos de terceros | <ide><path>runtfile.js
<ide> }
<ide> }
<ide> },
<del> // tarea de copia de los archivos bs3
<add> // tarea de copia de los archivos 3rd party
<ide> copy: {
<ide> main: {
<ide> files: [ |
|
Java | apache-2.0 | 77b79f50ac96ee5d2f82677e4c6c2cf93bf3330e | 0 | hkq325800/YellowNote | package com.kerchin.yellownote.adapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.kerchin.yellownote.R;
import com.kerchin.yellownote.bean.SimpleFolder;
import com.kerchin.yellownote.bean.SimpleNote;
import com.kerchin.yellownote.helper.ItemDrag.OnDragVHListener;
import com.kerchin.yellownote.utilities.Trace;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by KerchinHuang on 2016/1/31 0031.
*/
public class FolderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> /*implements OnItemMoveListener*/ {
public static int animDuration = 450;
private Context context;
// 笔记夹名
public static final int TYPE_HEADER = 0;
// 笔记夹下内容
public static final int TYPE_ITEM = 1;
// 是否为 编辑 模式
private boolean isEditMode;
private static final long ANIM_TIME = 360L;
// touch 点击开始时间
private long startTime;
private int shownFolderPosition = 0;
private int lastFolderPosition = 0;
// touch 间隔时间 用于分辨是否是 "点击"
private static final long SPACE_TIME = 100;
private LayoutInflater mInflater;
private ItemTouchHelper mItemTouchHelper;
private List<SimpleFolder> mFolders;
private List<SimpleNote> mNotes;
// private int headersNum = 0;
private SimpleFolder fromFolder;
private SimpleFolder toFolder;
SimpleNote fromItem;
SimpleNote toItem;
// 我的频道点击事件
private OnFolderItemClickListener mFolderItemClickListener;
boolean isAnimating = false;
public FolderAdapter(Context context, ItemTouchHelper helper, List<SimpleFolder> mFoldersTrans, List<SimpleNote> mNotesTrans) {
this.context = context;
this.mInflater = LayoutInflater.from(context);
this.mItemTouchHelper = helper;
this.mFolders = mFoldersTrans;
this.mNotes = mNotesTrans;
initData(mFoldersTrans);
}
private void initData(List<SimpleFolder> mFoldersTrans) {
List<SimpleNote> mTemp = new ArrayList<SimpleNote>();
shownFolderPosition = 0;
//mItem复刻
for (int i = 0; i < mNotes.size(); i++) {
mTemp.add(mNotes.get(i));
}
//设置ID和HeaderBefore
for (int i = 0; i < mFoldersTrans.size(); i++) {
for (int j = 0; j < mTemp.size(); j++) {
if (mTemp.get(j).getFolderId().equals(mFoldersTrans.get(i).getFolderId())) {
//设置noteItem的真实ID
mNotes.get(j).setId(mFoldersTrans.get(i).getId() + mFoldersTrans.get(i).getNow() + 1);
//找到一个数值+1
mFoldersTrans.get(i).addNow();
mNotes.get(j).setFolderPosition(mFoldersTrans.get(i).getId());
mNotes.get(j).setBrotherCount(mFoldersTrans.get(i).getContain());
//设置该noteItem前item的数量
mNotes.get(j).setHeaderBefore(i + 1);//mFolders.get(i).getId()
if (mNotes.get(j).getHeaderBefore() == 1) {
mNotes.get(j).setIsShown(true);
}
}
}
}
//重排mNotes 非必须
Collections.sort(mNotes, new Comparator<SimpleNote>() {
@Override
public int compare(SimpleNote lhs, SimpleNote rhs) {
if (lhs.getId() > rhs.getId())
return 1;
else
return -1;
}
});
}
public void setFolders(List<SimpleFolder> mFolders) {
this.mFolders = mFolders;
}
@Override
public int getItemViewType(int position) {
for (int i = 0; i < mFolders.size(); i++) {
if (position == mFolders.get(i).getId())
return TYPE_HEADER;
}
return TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view;
switch (viewType) {
case TYPE_HEADER:
view = mInflater.inflate(R.layout.item_folder_header, parent, false);
return new HeaderViewHolder(view);
case TYPE_ITEM:
view = mInflater.inflate(R.layout.item_folder_item, parent, false);
return new ItemViewHolder(view);
}
return null;
}
// private SystemHandler handler = new SystemHandler(this) {
//
// @Override
// public void handlerMessage(Message msg) {
// ItemViewHolder mHolder = (ItemViewHolder) msg.obj;
// switch (msg.what) {
// case 0:
// mHolder.mFolderItemRelative.setLayoutParams(new RelativeLayout.LayoutParams(0, 0));
// break;
// case 1:
// mHolder.mFolderItemRelative.setLayoutParams(new RelativeLayout.LayoutParams(
// RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
// break;
// default:break;
// }
// }
// };
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof HeaderViewHolder) {
HeaderViewHolder myHolder = (HeaderViewHolder) holder;
SimpleFolder thisFolder;
for (int i = 0; i < mFolders.size(); i++) {
if (mFolders.get(i).getId() == position) {
thisFolder = mFolders.get(i);
//set name and contains
myHolder.mFolderHeaderNameTxt.setText(thisFolder.getName());
String contain = thisFolder.getContain() + "";
myHolder.mFolderHeaderContainTxt.setText(contain);
break;
}
}
myHolder.mFolderHeaderNameTxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mFolderItemClickListener.onItemClick(v, position, TYPE_HEADER);
}
});
myHolder.mFolderHeaderNameTxt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mFolderItemClickListener.onItemLongClick(v, position, TYPE_HEADER);
return true;
}
});
} else if (holder instanceof ItemViewHolder) {
final ItemViewHolder mHolder = (ItemViewHolder) holder;
SimpleNote thisItem = null;
for (int i = 0; i < mNotes.size(); i++) {
if (mNotes.get(i).getId() == position) {
thisItem = mNotes.get(i);
mHolder.mFolderItemTxt.setText(thisItem.getName());
break;
}
}
if (thisItem != null) {
//应当为isShown的状态 目前是mHolder.isShown的状态
// Trace.d(thisItem.isShown()+"");
if (!thisItem.isShown()) {
//关闭动画
if (thisItem.getFolderPosition() == lastFolderPosition) {
// Trace.d(thisItem.getFolderPosition()+"关闭1");
mHolder.runAnimator(false);
} else {
// Trace.d(thisItem.getFolderPosition()+"关闭2");
mHolder.mFolderItemRelative.getLayoutParams().height = 0;
}
} else {
//开启动画
if (thisItem.getFolderPosition() == shownFolderPosition) {
// Trace.d(thisItem.getFolderPosition()+"开启1");
mHolder.runAnimator(true);//后行 等待关闭动画结束
} else {
// Trace.d(thisItem.getFolderPosition()+"开启2");
mHolder.mFolderItemRelative.getLayoutParams().height = (int) context.getResources().getDimension(R.dimen.folder_item_height);
}
if (isEditMode) {
mHolder.mFolderItemImg.setVisibility(View.VISIBLE);
} else {
mHolder.mFolderItemImg.setVisibility(View.GONE);
}
mHolder.mFolderItemTxt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
// if (!isEditMode) {
// RecyclerView recyclerView = ((RecyclerView) parent);
// startEditMode(recyclerView);
// header 按钮文字 改成 "完成"
// View view = recyclerView.getChildAt(0);
// if (view == recyclerView.getLayoutManager().findViewByPosition(0)) {
// TextView tvBtnEdit = (TextView) view.findViewById(R.id.tv_btn_edit);
// tvBtnEdit.setText("完成");
// }
mItemTouchHelper.startDrag(mHolder);
// } else {
// RecyclerView recyclerView = ((RecyclerView) parent);
// cancelEditMode(recyclerView);
// View view = recyclerView.getChildAt(0);
// if (view == recyclerView.getLayoutManager().findViewByPosition(0)) {
// TextView tvBtnEdit = (TextView) view.findViewById(R.id.tv_btn_edit);
// tvBtnEdit.setText("编辑");
// }
// }
return true;
}
});
mHolder.mFolderItemTxt.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (isEditMode) {
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
startTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_MOVE:
if (System.currentTimeMillis() - startTime > SPACE_TIME) {
mItemTouchHelper.startDrag(mHolder);
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
startTime = 0;
break;
}
}
return false;
}
});
}
}
}
}
@Override
public int getItemCount() {
return mNotes.size() + mFolders.size();
}
// @Override
// public void onItemMove(int fromPosition, int toPosition) {
//// boolean flag = true;
//// for (int i = 0; i < mFolders.size(); i++) {
//// if (mFolders.get(i).getId() == toPosition) {
//// flag = false;
//// }
//// }
//// if (flag) {
//// int preHeaders = 0;
//// for (int i = 0; i < mFolders.size(); i++) {
//// int id = mFolders.get(i).getId();
//// int contain = mFolders.get(i).getContain();
//// if (fromPosition > id && fromPosition <= contain + id) {
//// preHeaders = i;
//// }
//// }
//
// fromItem = null;
// toItem = null;
// fromFolder = null;
// toFolder = null;
// findTwoItem(fromPosition, toPosition);
// if (fromItem != null && toItem != null) {
// findTwoFolder(fromItem.getFolderId(), toItem.getFolderId());
// if (!fromItem.getFolderId().equals(toItem.getFolderId())) {//相同文件夹内不允许移动
// int trueTo = toPosition - toItem.getHeaderBefore();
// int trueFrom = fromPosition - fromItem.getHeaderBefore();
// Trace.d("fromPosition:" + fromPosition + "toPosition:" + toPosition);
// Trace.d("trueFrom:" + trueFrom + "trueTo:" + trueTo);
// Trace.d("fromName:" + fromItem.getName() + "toName:" + toItem.getName());
//
// //setFolderNum +1 -1
// fromFolder.decContain();//fromFolder
// toFolder.decId();//toFolder
// toFolder.addContain();//toFolder
// //从旧位置移除
// mNotes.remove(fromItem);
// //设置id folderId headerBefore
// fromItem.setId(toFolder.getId() + 1);//应该移动到改folder的第一个
// fromItem.setFolderId(toItem.getFolderId());
// fromItem.setHeaderBefore(toItem.getHeaderBefore());
// //添加到新位置
// mNotes.add(trueTo - 1, fromItem);//TODO
// if (toPosition > fromPosition)
// notifyItemRangeChanged(fromPosition, toPosition - fromPosition + 1);//TODO
// else
// notifyItemRangeChanged(toPosition, fromPosition - toPosition + 1);//TODO
//// notifyItemMoved(fromPosition, toPosition);
// Trace.d("finalFromItem:" + mNotes.get(trueTo).getName()
// + "finalToItem:" + mNotes.get(trueFrom).getName());
// }
// } else {
//// Trace.show(context, "出错啦!");
// }
// }
private void findTwoFolder(String oldFolderId, String newFolderId) {
for (int i = 0; i < mFolders.size(); i++) {
//-1
if (oldFolderId.equals(mFolders.get(i).getFolderId())) {
fromFolder = mFolders.get(i);
}
//+1
if (newFolderId.equals(mFolders.get(i).getFolderId())) {
toFolder = mFolders.get(i);
}
}
}
private void findTwoItem(int fromPosition, int toPosition) {
for (int i = 0; i < mNotes.size(); i++) {
if (fromPosition == mNotes.get(i).getId()) {
fromItem = mNotes.get(i);
}
if (toPosition == mNotes.get(i).getId()) {
toItem = mNotes.get(i);
}
}
}
public void openFolder(int position) {
if (!isAnimating) {
isAnimating = true;
if (position != shownFolderPosition) {
for (int i = 0; i < mNotes.size(); i++) {
//-1
if (mNotes.get(i).getFolderPosition() == position) {
mNotes.get(i).setIsShown(true);
}
//+1
if (mNotes.get(i).getFolderPosition() == shownFolderPosition) {
mNotes.get(i).setIsShown(false);
}
}
lastFolderPosition = shownFolderPosition;
shownFolderPosition = position;
// Trace.d("lastFolderPosition" + lastFolderPosition + "/shownFolderPosition" + shownFolderPosition);
notifyDataSetChanged();
} else {
for (int i = 0; i < mNotes.size(); i++) {
if (mNotes.get(i).getFolderPosition() == position) {
mNotes.get(i).setIsShown(false);
}
}
lastFolderPosition = shownFolderPosition;
shownFolderPosition = -1;
notifyDataSetChanged();
}
new CountDownTimer(animDuration,animDuration){
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
isAnimating = false;
}
}.start();
}
}
public interface OnFolderItemClickListener {
void onItemClick(View v, int position, int viewType);
void onItemLongClick(View v, int position, int viewType);
}
public void setOnMyChannelItemClickListener(OnFolderItemClickListener listener) {
this.mFolderItemClickListener = listener;
}
/**
* 开启编辑模式
*
* @param parent 父控件RecyclerView
*/
private void startEditMode(RecyclerView parent) {
isEditMode = true;
int visibleChildCount = parent.getChildCount();
for (int i = 0; i < visibleChildCount; i++) {
View view = parent.getChildAt(i);
ImageView mFolderItemImg = (ImageView) view.findViewById(R.id.mFolderItemImg);
if (mFolderItemImg != null) {
mFolderItemImg.setVisibility(View.VISIBLE);
}
}
}
/**
* 完成编辑模式
*
* @param parent 父控件RecyclerView
*/
private void cancelEditMode(RecyclerView parent) {
isEditMode = false;
int visibleChildCount = parent.getChildCount();
for (int i = 0; i < visibleChildCount; i++) {
View view = parent.getChildAt(i);
ImageView mFolderItemImg = (ImageView) view.findViewById(R.id.mFolderItemImg);
if (mFolderItemImg != null) {
mFolderItemImg.setVisibility(View.GONE);
}
}
}
/**
* 开始增删动画
*/
private void startAnimation(RecyclerView recyclerView, final View currentView, float targetX, float targetY) {
final ViewGroup viewGroup = (ViewGroup) recyclerView.getParent();
final ImageView mirrorView = addMirrorView(viewGroup, recyclerView, currentView);
Animation animation = getTranslateAnimator(
targetX - currentView.getLeft(), targetY - currentView.getTop());
currentView.setVisibility(View.INVISIBLE);
mirrorView.startAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
viewGroup.removeView(mirrorView);
if (currentView.getVisibility() == View.INVISIBLE) {
currentView.setVisibility(View.VISIBLE);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
//
// /**
// * 我的频道 移动到 其他频道
// *
// * @param myHolder
// */
// private void moveMyToOther(MyViewHolder myHolder) {
// int position = myHolder.getAdapterPosition();
//
// int startPosition = position - COUNT_PRE_MY_HEADER;
// if (startPosition > mMyChannelItems.size() - 1) {
// return;
// }
// ChannelEntity item = mMyChannelItems.get(startPosition);
// mMyChannelItems.remove(startPosition);
// mOtherChannelItems.add(0, item);
//
// notifyItemMoved(position, mMyChannelItems.size() + COUNT_PRE_OTHER_HEADER);
// }
//
// /**
// * 其他频道 移动到 我的频道
// *
// * @param otherHolder
// */
// private void moveOtherToMy(ItemViewHolder otherHolder) {
// int position = processItemRemoveAdd(otherHolder);
// if (position == -1) {
// return;
// }
// notifyItemMoved(position, mNotes.size() - 1 + COUNT_PRE_MY_HEADER);
// }
//
// /**
// * 其他频道 移动到 我的频道 伴随延迟
// *
// * @param otherHolder
// */
// private void moveOtherToMyWithDelay(ItemViewHolder otherHolder) {
// final int position = processItemRemoveAdd(otherHolder);
// if (position == -1) {
// return;
// }
// delayHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// notifyItemMoved(position, mNotes.size() - 1 + COUNT_PRE_MY_HEADER);
// }
// }, ANIM_TIME);
// }
//
// private Handler delayHandler = new Handler();
//
// private int processItemRemoveAdd(ItemViewHolder otherHolder) {
// int position = otherHolder.getAdapterPosition();
//
// int startPosition = position - mMyChannelItems.size() - COUNT_PRE_OTHER_HEADER;
// if (startPosition > mOtherChannelItems.size() - 1) {
// return -1;
// }
// ChannelEntity item = mOtherChannelItems.get(startPosition);
// mOtherChannelItems.remove(startPosition);
// mMyChannelItems.add(item);
// return position;
// }
/**
* 添加需要移动的 镜像View
*/
private ImageView addMirrorView(ViewGroup parent, RecyclerView recyclerView, View view) {
/**
* 我们要获取cache首先要通过setDrawingCacheEnable方法开启cache,然后再调用getDrawingCache方法就可以获得view的cache图片了。
buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果cache没有建立,系统会自动调用buildDrawingCache方法生成cache。
若想更新cache, 必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。
当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。
*/
view.destroyDrawingCache();
view.setDrawingCacheEnabled(true);
final ImageView mirrorView = new ImageView(recyclerView.getContext());
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
mirrorView.setImageBitmap(bitmap);
view.setDrawingCacheEnabled(false);
int[] locations = new int[2];
view.getLocationOnScreen(locations);
int[] parenLocations = new int[2];
recyclerView.getLocationOnScreen(parenLocations);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
params.setMargins(locations[0], locations[1] - parenLocations[1], 0, 0);
parent.addView(mirrorView, params);
return mirrorView;
}
/**
* 获取位移动画
*/
private TranslateAnimation getTranslateAnimator(float targetX, float targetY) {
TranslateAnimation translateAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f,
Animation.ABSOLUTE, targetX,
Animation.RELATIVE_TO_SELF, 0f,
Animation.ABSOLUTE, targetY);
// RecyclerView默认移动动画250ms 这里设置360ms 是为了防止在位移动画结束后 remove(view)过早 导致闪烁
translateAnimation.setDuration(ANIM_TIME);
translateAnimation.setFillAfter(true);
return translateAnimation;
}
class HeaderViewHolder extends RecyclerView.ViewHolder implements OnDragVHListener {
@Bind(R.id.mFolderHeaderNameTxt)
TextView mFolderHeaderNameTxt;
@Bind(R.id.mFolderHeaderContainTxt)
TextView mFolderHeaderContainTxt;
public HeaderViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
/**
* item 被选中时
*/
@Override
public void onItemSelected() {
mFolderHeaderNameTxt.setBackgroundResource(R.drawable.bg_channel_p);
}
/**
* item 取消选中时
*/
@Override
public void onItemFinish() {
mFolderHeaderNameTxt.setBackgroundResource(R.drawable.bg_channel);
}
}
class ItemViewHolder extends RecyclerView.ViewHolder implements OnDragVHListener {
@Bind(R.id.mFolderItemTxt)
TextView mFolderItemTxt;
@Bind(R.id.mFolderItemImg)
ImageView mFolderItemImg;
@Bind(R.id.mFolderItemRelative)
RelativeLayout mFolderItemRelative;
private ValueAnimator valueAnimator;
public boolean isShown = false;
private DecelerateInterpolator di = new DecelerateInterpolator();
private AccelerateInterpolator ai = new AccelerateInterpolator();
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
mFolderItemRelative.getLayoutParams().height = 0;
}
public void runAnimator(boolean isExpand) {
if (isExpand) {
isShown = true;
// mFolderItemRelative.setAlpha(0);
// mFolderItemRelative.animate()
// .alpha(1)
// .setDuration(animDuration).start();
valueAnimator = ValueAnimator.ofFloat(0, context.getResources().getDimension(R.dimen.folder_item_height));
valueAnimator.setInterpolator(ai);
} else {
isShown = false;
// mFolderItemRelative.setAlpha(1);
// mFolderItemRelative.animate()
// .alpha(0.2f)
// .setDuration(animDuration).start();
valueAnimator = ValueAnimator.ofFloat(context.getResources().getDimension(R.dimen.folder_item_height), 0);
valueAnimator.setInterpolator(di);
}
valueAnimator.setDuration(animDuration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Float value = (Float) animation.getAnimatedValue();
mFolderItemRelative.getLayoutParams().height = value.intValue();
mFolderItemRelative.requestLayout();
}
});
valueAnimator.start();
}
/**
* item 被选中时
*/
@Override
public void onItemSelected() {
mFolderItemTxt.setBackgroundResource(R.drawable.bg_channel_p);
}
/**
* item 取消选中时
*/
@Override
public void onItemFinish() {
mFolderItemTxt.setBackgroundResource(R.drawable.bg_channel);
}
}
}
| app/src/main/java/com/kerchin/yellownote/adapter/FolderAdapter.java | package com.kerchin.yellownote.adapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.kerchin.yellownote.R;
import com.kerchin.yellownote.bean.SimpleFolder;
import com.kerchin.yellownote.bean.SimpleNote;
import com.kerchin.yellownote.helper.ItemDrag.OnDragVHListener;
import com.kerchin.yellownote.utilities.Trace;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by KerchinHuang on 2016/1/31 0031.
*/
public class FolderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> /*implements OnItemMoveListener*/ {
public static int animDuration = 450;
private Context context;
// 笔记夹名
public static final int TYPE_HEADER = 0;
// 笔记夹下内容
public static final int TYPE_ITEM = 1;
// 是否为 编辑 模式
private boolean isEditMode;
private static final long ANIM_TIME = 360L;
// touch 点击开始时间
private long startTime;
private int shownFolderPosition = 0;
private int lastFolderPosition = 0;
// touch 间隔时间 用于分辨是否是 "点击"
private static final long SPACE_TIME = 100;
private LayoutInflater mInflater;
private ItemTouchHelper mItemTouchHelper;
private List<SimpleFolder> mFolders;
private List<SimpleNote> mNotes;
// private int headersNum = 0;
private SimpleFolder fromFolder;
private SimpleFolder toFolder;
SimpleNote fromItem;
SimpleNote toItem;
// 我的频道点击事件
private OnFolderItemClickListener mFolderItemClickListener;
boolean isAnimating = false;
public FolderAdapter(Context context, ItemTouchHelper helper, List<SimpleFolder> mFoldersTrans, List<SimpleNote> mNotesTrans) {
this.context = context;
this.mInflater = LayoutInflater.from(context);
this.mItemTouchHelper = helper;
this.mFolders = mFoldersTrans;
this.mNotes = mNotesTrans;
initData(mFoldersTrans);
}
private void initData(List<SimpleFolder> mFoldersTrans) {
List<SimpleNote> mTemp = new ArrayList<SimpleNote>();
shownFolderPosition = 0;
//mItem复刻
for (int i = 0; i < mNotes.size(); i++) {
mTemp.add(mNotes.get(i));
}
//设置ID和HeaderBefore
for (int i = 0; i < mFoldersTrans.size(); i++) {
for (int j = 0; j < mTemp.size(); j++) {
if (mTemp.get(j).getFolderId().equals(mFoldersTrans.get(i).getFolderId())) {
//设置noteItem的真实ID
mNotes.get(j).setId(mFoldersTrans.get(i).getId() + mFoldersTrans.get(i).getNow() + 1);
//找到一个数值+1
mFoldersTrans.get(i).addNow();
mNotes.get(j).setFolderPosition(mFoldersTrans.get(i).getId());
mNotes.get(j).setBrotherCount(mFoldersTrans.get(i).getContain());
//设置该noteItem前item的数量
mNotes.get(j).setHeaderBefore(i + 1);//mFolders.get(i).getId()
if (mNotes.get(j).getHeaderBefore() == 1) {
mNotes.get(j).setIsShown(true);
}
}
}
}
//重排mNotes 非必须
Collections.sort(mNotes, new Comparator<SimpleNote>() {
@Override
public int compare(SimpleNote lhs, SimpleNote rhs) {
if (lhs.getId() > rhs.getId())
return 1;
else
return -1;
}
});
}
public void setFolders(List<SimpleFolder> mFolders) {
this.mFolders = mFolders;
}
@Override
public int getItemViewType(int position) {
for (int i = 0; i < mFolders.size(); i++) {
if (position == mFolders.get(i).getId())
return TYPE_HEADER;
}
return TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view;
switch (viewType) {
case TYPE_HEADER:
view = mInflater.inflate(R.layout.item_folder_header, parent, false);
return new HeaderViewHolder(view);
case TYPE_ITEM:
view = mInflater.inflate(R.layout.item_folder_item, parent, false);
return new ItemViewHolder(view);
}
return null;
}
// private SystemHandler handler = new SystemHandler(this) {
//
// @Override
// public void handlerMessage(Message msg) {
// ItemViewHolder mHolder = (ItemViewHolder) msg.obj;
// switch (msg.what) {
// case 0:
// mHolder.mFolderItemRelative.setLayoutParams(new RelativeLayout.LayoutParams(0, 0));
// break;
// case 1:
// mHolder.mFolderItemRelative.setLayoutParams(new RelativeLayout.LayoutParams(
// RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
// break;
// default:break;
// }
// }
// };
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof HeaderViewHolder) {
HeaderViewHolder myHolder = (HeaderViewHolder) holder;
SimpleFolder thisFolder;
for (int i = 0; i < mFolders.size(); i++) {
if (mFolders.get(i).getId() == position) {
thisFolder = mFolders.get(i);
//set name and contains
myHolder.mFolderHeaderNameTxt.setText(thisFolder.getName());
String contain = thisFolder.getContain() + "";
myHolder.mFolderHeaderContainTxt.setText(contain);
break;
}
}
myHolder.mFolderHeaderNameTxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mFolderItemClickListener.onItemClick(v, position, TYPE_HEADER);
}
});
myHolder.mFolderHeaderNameTxt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mFolderItemClickListener.onItemLongClick(v, position, TYPE_HEADER);
return true;
}
});
} else if (holder instanceof ItemViewHolder) {
final ItemViewHolder mHolder = (ItemViewHolder) holder;
SimpleNote thisItem = null;
for (int i = 0; i < mNotes.size(); i++) {
if (mNotes.get(i).getId() == position) {
thisItem = mNotes.get(i);
mHolder.mFolderItemTxt.setText(thisItem.getName());
break;
}
}
if (thisItem != null) {
//应当为isShown的状态 目前是mHolder.isShown的状态
// Trace.d(thisItem.isShown()+"");
if (!thisItem.isShown()) {
//关闭动画
if (thisItem.getFolderPosition() == lastFolderPosition) {
// Trace.d(thisItem.getFolderPosition()+"关闭1");
mHolder.runAnimator(false);
} else {
// Trace.d(thisItem.getFolderPosition()+"关闭2");
mHolder.mFolderItemRelative.getLayoutParams().height = 0;
}
} else {
//开启动画
if (thisItem.getFolderPosition() == shownFolderPosition) {
// Trace.d(thisItem.getFolderPosition()+"开启1");
mHolder.runAnimator(true);//后行 等待关闭动画结束
} else {
// Trace.d(thisItem.getFolderPosition()+"开启2");
mHolder.mFolderItemRelative.getLayoutParams().height = (int) context.getResources().getDimension(R.dimen.folder_item_height);
}
if (isEditMode) {
mHolder.mFolderItemImg.setVisibility(View.VISIBLE);
} else {
mHolder.mFolderItemImg.setVisibility(View.GONE);
}
mHolder.mFolderItemTxt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
// if (!isEditMode) {
// RecyclerView recyclerView = ((RecyclerView) parent);
// startEditMode(recyclerView);
// header 按钮文字 改成 "完成"
// View view = recyclerView.getChildAt(0);
// if (view == recyclerView.getLayoutManager().findViewByPosition(0)) {
// TextView tvBtnEdit = (TextView) view.findViewById(R.id.tv_btn_edit);
// tvBtnEdit.setText("完成");
// }
mItemTouchHelper.startDrag(mHolder);
// } else {
// RecyclerView recyclerView = ((RecyclerView) parent);
// cancelEditMode(recyclerView);
// View view = recyclerView.getChildAt(0);
// if (view == recyclerView.getLayoutManager().findViewByPosition(0)) {
// TextView tvBtnEdit = (TextView) view.findViewById(R.id.tv_btn_edit);
// tvBtnEdit.setText("编辑");
// }
// }
return true;
}
});
mHolder.mFolderItemTxt.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (isEditMode) {
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
startTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_MOVE:
if (System.currentTimeMillis() - startTime > SPACE_TIME) {
mItemTouchHelper.startDrag(mHolder);
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
startTime = 0;
break;
}
}
return false;
}
});
}
}
}
}
@Override
public int getItemCount() {
return mNotes.size() + mFolders.size();
}
// @Override
// public void onItemMove(int fromPosition, int toPosition) {
//// boolean flag = true;
//// for (int i = 0; i < mFolders.size(); i++) {
//// if (mFolders.get(i).getId() == toPosition) {
//// flag = false;
//// }
//// }
//// if (flag) {
//// int preHeaders = 0;
//// for (int i = 0; i < mFolders.size(); i++) {
//// int id = mFolders.get(i).getId();
//// int contain = mFolders.get(i).getContain();
//// if (fromPosition > id && fromPosition <= contain + id) {
//// preHeaders = i;
//// }
//// }
//
// fromItem = null;
// toItem = null;
// fromFolder = null;
// toFolder = null;
// findTwoItem(fromPosition, toPosition);
// if (fromItem != null && toItem != null) {
// findTwoFolder(fromItem.getFolderId(), toItem.getFolderId());
// if (!fromItem.getFolderId().equals(toItem.getFolderId())) {//相同文件夹内不允许移动
// int trueTo = toPosition - toItem.getHeaderBefore();
// int trueFrom = fromPosition - fromItem.getHeaderBefore();
// Trace.d("fromPosition:" + fromPosition + "toPosition:" + toPosition);
// Trace.d("trueFrom:" + trueFrom + "trueTo:" + trueTo);
// Trace.d("fromName:" + fromItem.getName() + "toName:" + toItem.getName());
//
// //setFolderNum +1 -1
// fromFolder.decContain();//fromFolder
// toFolder.decId();//toFolder
// toFolder.addContain();//toFolder
// //从旧位置移除
// mNotes.remove(fromItem);
// //设置id folderId headerBefore
// fromItem.setId(toFolder.getId() + 1);//应该移动到改folder的第一个
// fromItem.setFolderId(toItem.getFolderId());
// fromItem.setHeaderBefore(toItem.getHeaderBefore());
// //添加到新位置
// mNotes.add(trueTo - 1, fromItem);//TODO
// if (toPosition > fromPosition)
// notifyItemRangeChanged(fromPosition, toPosition - fromPosition + 1);//TODO
// else
// notifyItemRangeChanged(toPosition, fromPosition - toPosition + 1);//TODO
//// notifyItemMoved(fromPosition, toPosition);
// Trace.d("finalFromItem:" + mNotes.get(trueTo).getName()
// + "finalToItem:" + mNotes.get(trueFrom).getName());
// }
// } else {
//// Trace.show(context, "出错啦!");
// }
// }
private void findTwoFolder(String oldFolderId, String newFolderId) {
for (int i = 0; i < mFolders.size(); i++) {
//-1
if (oldFolderId.equals(mFolders.get(i).getFolderId())) {
fromFolder = mFolders.get(i);
}
//+1
if (newFolderId.equals(mFolders.get(i).getFolderId())) {
toFolder = mFolders.get(i);
}
}
}
private void findTwoItem(int fromPosition, int toPosition) {
for (int i = 0; i < mNotes.size(); i++) {
if (fromPosition == mNotes.get(i).getId()) {
fromItem = mNotes.get(i);
}
if (toPosition == mNotes.get(i).getId()) {
toItem = mNotes.get(i);
}
}
}
public void openFolder(int position) {
if (!isAnimating) {
isAnimating = true;
if (position != shownFolderPosition) {
for (int i = 0; i < mNotes.size(); i++) {
//-1
if (mNotes.get(i).getFolderPosition() == position) {
mNotes.get(i).setIsShown(true);
}
//+1
if (mNotes.get(i).getFolderPosition() == shownFolderPosition) {
mNotes.get(i).setIsShown(false);
}
}
lastFolderPosition = shownFolderPosition;
shownFolderPosition = position;
// Trace.d("lastFolderPosition" + lastFolderPosition + "/shownFolderPosition" + shownFolderPosition);
notifyDataSetChanged();
} else {
for (int i = 0; i < mNotes.size(); i++) {
if (mNotes.get(i).getFolderPosition() == position) {
mNotes.get(i).setIsShown(false);
}
}
lastFolderPosition = shownFolderPosition;
shownFolderPosition = -1;
notifyDataSetChanged();
}
new CountDownTimer(animDuration,animDuration){
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
isAnimating = false;
}
}.start();
}
}
public interface OnFolderItemClickListener {
void onItemClick(View v, int position, int viewType);
void onItemLongClick(View v, int position, int viewType);
}
public void setOnMyChannelItemClickListener(OnFolderItemClickListener listener) {
this.mFolderItemClickListener = listener;
}
/**
* 开启编辑模式
*
* @param parent 父控件RecyclerView
*/
private void startEditMode(RecyclerView parent) {
isEditMode = true;
int visibleChildCount = parent.getChildCount();
for (int i = 0; i < visibleChildCount; i++) {
View view = parent.getChildAt(i);
ImageView mFolderItemImg = (ImageView) view.findViewById(R.id.mFolderItemImg);
if (mFolderItemImg != null) {
mFolderItemImg.setVisibility(View.VISIBLE);
}
}
}
/**
* 完成编辑模式
*
* @param parent 父控件RecyclerView
*/
private void cancelEditMode(RecyclerView parent) {
isEditMode = false;
int visibleChildCount = parent.getChildCount();
for (int i = 0; i < visibleChildCount; i++) {
View view = parent.getChildAt(i);
ImageView mFolderItemImg = (ImageView) view.findViewById(R.id.mFolderItemImg);
if (mFolderItemImg != null) {
mFolderItemImg.setVisibility(View.GONE);
}
}
}
/**
* 开始增删动画
*/
private void startAnimation(RecyclerView recyclerView, final View currentView, float targetX, float targetY) {
final ViewGroup viewGroup = (ViewGroup) recyclerView.getParent();
final ImageView mirrorView = addMirrorView(viewGroup, recyclerView, currentView);
Animation animation = getTranslateAnimator(
targetX - currentView.getLeft(), targetY - currentView.getTop());
currentView.setVisibility(View.INVISIBLE);
mirrorView.startAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
viewGroup.removeView(mirrorView);
if (currentView.getVisibility() == View.INVISIBLE) {
currentView.setVisibility(View.VISIBLE);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
//
// /**
// * 我的频道 移动到 其他频道
// *
// * @param myHolder
// */
// private void moveMyToOther(MyViewHolder myHolder) {
// int position = myHolder.getAdapterPosition();
//
// int startPosition = position - COUNT_PRE_MY_HEADER;
// if (startPosition > mMyChannelItems.size() - 1) {
// return;
// }
// ChannelEntity item = mMyChannelItems.get(startPosition);
// mMyChannelItems.remove(startPosition);
// mOtherChannelItems.add(0, item);
//
// notifyItemMoved(position, mMyChannelItems.size() + COUNT_PRE_OTHER_HEADER);
// }
//
// /**
// * 其他频道 移动到 我的频道
// *
// * @param otherHolder
// */
// private void moveOtherToMy(ItemViewHolder otherHolder) {
// int position = processItemRemoveAdd(otherHolder);
// if (position == -1) {
// return;
// }
// notifyItemMoved(position, mNotes.size() - 1 + COUNT_PRE_MY_HEADER);
// }
//
// /**
// * 其他频道 移动到 我的频道 伴随延迟
// *
// * @param otherHolder
// */
// private void moveOtherToMyWithDelay(ItemViewHolder otherHolder) {
// final int position = processItemRemoveAdd(otherHolder);
// if (position == -1) {
// return;
// }
// delayHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// notifyItemMoved(position, mNotes.size() - 1 + COUNT_PRE_MY_HEADER);
// }
// }, ANIM_TIME);
// }
//
// private Handler delayHandler = new Handler();
//
// private int processItemRemoveAdd(ItemViewHolder otherHolder) {
// int position = otherHolder.getAdapterPosition();
//
// int startPosition = position - mMyChannelItems.size() - COUNT_PRE_OTHER_HEADER;
// if (startPosition > mOtherChannelItems.size() - 1) {
// return -1;
// }
// ChannelEntity item = mOtherChannelItems.get(startPosition);
// mOtherChannelItems.remove(startPosition);
// mMyChannelItems.add(item);
// return position;
// }
/**
* 添加需要移动的 镜像View
*/
private ImageView addMirrorView(ViewGroup parent, RecyclerView recyclerView, View view) {
/**
* 我们要获取cache首先要通过setDrawingCacheEnable方法开启cache,然后再调用getDrawingCache方法就可以获得view的cache图片了。
buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果cache没有建立,系统会自动调用buildDrawingCache方法生成cache。
若想更新cache, 必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。
当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。
*/
view.destroyDrawingCache();
view.setDrawingCacheEnabled(true);
final ImageView mirrorView = new ImageView(recyclerView.getContext());
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
mirrorView.setImageBitmap(bitmap);
view.setDrawingCacheEnabled(false);
int[] locations = new int[2];
view.getLocationOnScreen(locations);
int[] parenLocations = new int[2];
recyclerView.getLocationOnScreen(parenLocations);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
params.setMargins(locations[0], locations[1] - parenLocations[1], 0, 0);
parent.addView(mirrorView, params);
return mirrorView;
}
/**
* 获取位移动画
*/
private TranslateAnimation getTranslateAnimator(float targetX, float targetY) {
TranslateAnimation translateAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f,
Animation.ABSOLUTE, targetX,
Animation.RELATIVE_TO_SELF, 0f,
Animation.ABSOLUTE, targetY);
// RecyclerView默认移动动画250ms 这里设置360ms 是为了防止在位移动画结束后 remove(view)过早 导致闪烁
translateAnimation.setDuration(ANIM_TIME);
translateAnimation.setFillAfter(true);
return translateAnimation;
}
class HeaderViewHolder extends RecyclerView.ViewHolder implements OnDragVHListener {
@Bind(R.id.mFolderHeaderNameTxt)
TextView mFolderHeaderNameTxt;
@Bind(R.id.mFolderHeaderContainTxt)
TextView mFolderHeaderContainTxt;
public HeaderViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
/**
* item 被选中时
*/
@Override
public void onItemSelected() {
mFolderHeaderNameTxt.setBackgroundResource(R.drawable.bg_channel_p);
}
/**
* item 取消选中时
*/
@Override
public void onItemFinish() {
mFolderHeaderNameTxt.setBackgroundResource(R.drawable.bg_channel);
}
}
class ItemViewHolder extends RecyclerView.ViewHolder implements OnDragVHListener {
@Bind(R.id.mFolderItemTxt)
TextView mFolderItemTxt;
@Bind(R.id.mFolderItemImg)
ImageView mFolderItemImg;
@Bind(R.id.mFolderItemRelative)
RelativeLayout mFolderItemRelative;
private ValueAnimator valueAnimator;
public boolean isShown = false;
private DecelerateInterpolator di = new DecelerateInterpolator();
private AccelerateInterpolator ai = new AccelerateInterpolator();
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
mFolderItemRelative.getLayoutParams().height = 0;
}
public void runAnimator(boolean isExpand) {
if (isExpand) {
isShown = true;
mFolderItemRelative.setAlpha(0);
mFolderItemRelative.animate()
.alpha(1)
.setInterpolator(ai)
.setDuration(animDuration).start();
valueAnimator = ValueAnimator.ofFloat(0, context.getResources().getDimension(R.dimen.folder_item_height));
valueAnimator.setInterpolator(ai);
} else {
isShown = false;
mFolderItemRelative.setAlpha(1);
mFolderItemRelative.animate()
.alpha(0.2f)
.setInterpolator(di)
.setDuration(animDuration).start();
valueAnimator = ValueAnimator.ofFloat(context.getResources().getDimension(R.dimen.folder_item_height), 0);
valueAnimator.setInterpolator(di);
}
valueAnimator.setDuration(animDuration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Float value = (Float) animation.getAnimatedValue();
mFolderItemRelative.getLayoutParams().height = value.intValue();
mFolderItemRelative.requestLayout();
}
});
valueAnimator.start();
}
/**
* item 被选中时
*/
@Override
public void onItemSelected() {
mFolderItemTxt.setBackgroundResource(R.drawable.bg_channel_p);
}
/**
* item 取消选中时
*/
@Override
public void onItemFinish() {
mFolderItemTxt.setBackgroundResource(R.drawable.bg_channel);
}
}
}
| 忍痛去除alpha动画
| app/src/main/java/com/kerchin/yellownote/adapter/FolderAdapter.java | 忍痛去除alpha动画 | <ide><path>pp/src/main/java/com/kerchin/yellownote/adapter/FolderAdapter.java
<ide> public void runAnimator(boolean isExpand) {
<ide> if (isExpand) {
<ide> isShown = true;
<del> mFolderItemRelative.setAlpha(0);
<del> mFolderItemRelative.animate()
<del> .alpha(1)
<del> .setInterpolator(ai)
<del> .setDuration(animDuration).start();
<add>// mFolderItemRelative.setAlpha(0);
<add>// mFolderItemRelative.animate()
<add>// .alpha(1)
<add>// .setDuration(animDuration).start();
<ide> valueAnimator = ValueAnimator.ofFloat(0, context.getResources().getDimension(R.dimen.folder_item_height));
<ide> valueAnimator.setInterpolator(ai);
<ide> } else {
<ide> isShown = false;
<del> mFolderItemRelative.setAlpha(1);
<del> mFolderItemRelative.animate()
<del> .alpha(0.2f)
<del> .setInterpolator(di)
<del> .setDuration(animDuration).start();
<add>// mFolderItemRelative.setAlpha(1);
<add>// mFolderItemRelative.animate()
<add>// .alpha(0.2f)
<add>// .setDuration(animDuration).start();
<ide> valueAnimator = ValueAnimator.ofFloat(context.getResources().getDimension(R.dimen.folder_item_height), 0);
<ide> valueAnimator.setInterpolator(di);
<ide> } |
|
Java | apache-2.0 | 8c8ece87f9e76917daaa9b221011cc8fa1835b51 | 0 | ppavlidis/baseCode,ppavlidis/baseCode | /*
* The baseCode project
*
* Copyright (c) 2011 University of British Columbia
*
* 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 ubic.basecode.math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import no.uib.cipr.matrix.DenseMatrix;
import no.uib.cipr.matrix.Matrices;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.FDistribution;
import org.apache.commons.math.distribution.FDistributionImpl;
import org.apache.commons.math.distribution.TDistribution;
import org.apache.commons.math.distribution.TDistributionImpl;
import org.netlib.lapack.LAPACK;
import org.netlib.util.intW;
import ubic.basecode.dataStructure.matrix.DoubleMatrix;
import ubic.basecode.dataStructure.matrix.DoubleMatrixFactory;
import ubic.basecode.dataStructure.matrix.MatrixUtil;
import ubic.basecode.dataStructure.matrix.ObjectMatrix;
import ubic.basecode.util.r.type.AnovaEffect;
import ubic.basecode.util.r.type.GenericAnovaResult;
import ubic.basecode.util.r.type.LinearModelSummary;
import cern.colt.function.IntIntDoubleFunction;
import cern.colt.list.DoubleArrayList;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.linalg.Algebra;
import cern.jet.math.Functions;
import cern.jet.stat.Descriptive;
/**
* For performing "bulk" linear model fits. Allows rapid fitting to large data sets.
*
* @author paul
* @version $Id$
*/
public class LeastSquaresFit {
/*
* Making this static causes problems with memory leaks/garbage that is not efficiently collected.
*/
// private static Algebra solver = new Algebra();
/**
* Model fix coefficients (the x in Ax=b)
*/
private DoubleMatrix2D coefficients = null;
/**
*
*/
private boolean hasMissing = false;
/**
* Fitted values
*/
private DoubleMatrix2D fitted;
/**
* Residuals of the fit
*/
private DoubleMatrix2D residuals;
/**
* QR decomposition of the design matrix
*/
private QRDecompositionPivoting qr;
/**
* The (raw) design matrix
*/
private DoubleMatrix2D A;
/**
* Independent variables
*/
private DoubleMatrix2D b;
private int residualDof;
private boolean hasWarned = false;
/*
* Lists which factors (terms) are associated with which columns of the design matrix; 0 indicates the intercept.
*/
private List<Integer> assign = new ArrayList<Integer>();
/*
* Names of the factors (terms)
*/
private List<String> terms;
private DesignMatrix designMatrix;
/*
* Optional, but useful
*/
private List<String> rowNames;
/*
* Used if we have missing values so QR might be different for each row (possible optimization to consider: only
* store set of variants that are actually used)
*/
private List<QRDecompositionPivoting> qrs = new ArrayList<QRDecompositionPivoting>();
/*
* Used if we have missing value so RDOF might be different for each row (we can actually get away without this)
*/
private List<Integer> residualDofs = new ArrayList<Integer>();
private boolean hasIntercept = true;
private List<List<Integer>> assigns = new ArrayList<List<Integer>>();
/*
* For weighted regression
*/
private DoubleMatrix2D weights = null;
// private List<Integer[]> pivotIndicesList = new ArrayList<Integer[]>();
private static Log log = LogFactory.getLog( LeastSquaresFit.class );
/**
* Preferred interface if you want control over how the design is set up.
*
* @param designMatrix
* @param data
*/
public LeastSquaresFit( DesignMatrix designMatrix, DoubleMatrix<String, String> data ) {
this.designMatrix = designMatrix;
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.rowNames = data.getRowNames();
this.b = new DenseDoubleMatrix2D( data.asArray() );
boolean hasInterceptTerm = this.terms.contains( LinearModelSummary.INTERCEPT_COEFFICIENT_NAME );
this.hasIntercept = designMatrix.hasIntercept();
assert hasInterceptTerm == this.hasIntercept : diagnosis( null );
lsf();
}
/**
* Stripped-down interface for simple use. ANOVA not possible (use the other constructors)
*
* @param A Design matrix, which will be used directly in least squares regression
* @param b Data matrix, containing data in rows.
*/
public LeastSquaresFit( DoubleMatrix2D A, DoubleMatrix2D b ) {
this.A = A;
this.b = b;
lsf();
}
/**
* Least squares fit between two vectors. Always adds an intercept!
*
* @param vectorA Design
* @param vectorB Data
* @param weights to be used in modifying the influence of the observations in vectorB.
*/
public LeastSquaresFit( DoubleMatrix1D vectorA, DoubleMatrix1D vectorB, final DoubleMatrix1D weights ) {
assert vectorA.size() == vectorB.size();
assert vectorA.size() == weights.size();
this.A = new DenseDoubleMatrix2D( vectorA.size(), 2 );
this.b = new DenseDoubleMatrix2D( 1, vectorB.size() );
this.weights = new DenseDoubleMatrix2D( 1, weights.size() );
for ( int i = 0; i < vectorA.size(); i++ ) {
double ws = Math.sqrt( weights.get( i ) );
A.set( i, 0, ws );
A.set( i, 1, vectorA.get( i ) * ws );
b.set( 0, i, vectorB.get( i ) * ws );
this.weights.set( 0, i, weights.get( i ) );
}
lsf();
residuals = residuals.forEachNonZero( new IntIntDoubleFunction() {
@Override
public double apply( int row, int col, double nonZeroValue ) {
return nonZeroValue / Math.sqrt( weights.get( col ) );
}
} );
DoubleMatrix1D f2 = vectorB.copy().assign( residuals.viewRow( 0 ), Functions.minus );
this.fitted.viewRow( 0 ).assign( f2 );
}
/**
* Least squares fit between two vectors. Always adds an intercept!
*
* @param vectorA Design
* @param vectorB Data
*/
public LeastSquaresFit( DoubleMatrix1D vectorA, DoubleMatrix1D vectorB ) {
assert vectorA.size() == vectorB.size();
this.A = new DenseDoubleMatrix2D( vectorA.size(), 2 );
this.b = new DenseDoubleMatrix2D( 1, vectorB.size() );
for ( int i = 0; i < vectorA.size(); i++ ) {
A.set( i, 0, 1 );
A.set( i, 1, vectorA.get( i ) );
b.set( 0, i, vectorB.get( i ) );
}
lsf();
}
/**
* @param sample information that will be converted to a design matrix; intercept term is added.
* @param data Data matrix
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> sampleInfo, DenseDoubleMatrix2D data ) {
this.designMatrix = new DesignMatrix( sampleInfo, true );
this.hasIntercept = true;
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = data;
lsf();
}
/**
* @param sampleInfo
* @param data
* @param interactions add interaction term (two-way only is supported)
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> sampleInfo, DenseDoubleMatrix2D data,
boolean interactions ) {
this.designMatrix = new DesignMatrix( sampleInfo, true );
if ( interactions ) {
addInteraction();
}
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = data;
lsf();
}
/**
* NamedMatrix allows easier handling of the results.
*
* @param sample information that will be converted to a design matrix; intercept term is added.
* @param b Data matrix
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> design, DoubleMatrix<String, String> b ) {
this.designMatrix = new DesignMatrix( design, true );
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = new DenseDoubleMatrix2D( b.asArray() );
this.rowNames = b.getRowNames();
lsf();
}
/**
* NamedMatrix allows easier handling of the results.
*
* @param sample information that will be converted to a design matrix; intercept term is added.
* @param data Data matrix
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> design, DoubleMatrix<String, String> data,
boolean interactions ) {
this.designMatrix = new DesignMatrix( design, true );
if ( interactions ) {
addInteraction();
}
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = new DenseDoubleMatrix2D( data.asArray() );
lsf();
}
/**
* Compute ANOVA based on the model fit
*
* @return
*/
public List<GenericAnovaResult> anova() {
Algebra solver = new Algebra();
DoubleMatrix1D ones = new DenseDoubleMatrix1D( residuals.columns() );
ones.assign( 1.0 );
DoubleMatrix1D residualSumsOfSquares = MatrixUtil.multWithMissing( residuals.copy().assign( Functions.square ),
ones );
DoubleMatrix2D effects = null;
if ( this.hasMissing ) {
effects = new DenseDoubleMatrix2D( this.b.rows(), this.A.columns() );
effects.assign( Double.NaN );
for ( int i = 0; i < this.b.rows(); i++ ) {
// if ( this.rowNames.get( i ).equals( "probe_60" ) ) {
// log.info( "MARV" );
// }
QRDecompositionPivoting qrd = this.qrs.get( i );
if ( qrd == null ) {
// means we did not get a fit
for ( int j = 0; j < effects.columns(); j++ ) {
effects.set( i, j, Double.NaN );
}
continue;
}
DoubleMatrix1D brow = b.viewRow( i );
DoubleMatrix1D browWithoutMissing = MatrixUtil.removeMissing( brow );
DoubleMatrix2D qrow = qrd.getQ().viewPart( 0, 0, browWithoutMissing.size(), qrd.getRank() );
// will never happen.
// if ( qrow.rows() != browWithoutMissing.size() ) {
// for ( int j = 0; j < effects.columns(); j++ ) {
// effects.set( i, j, Double.NaN );
// }
// continue;
// }
DoubleMatrix1D crow = MatrixUtil.multWithMissing( browWithoutMissing, qrow );
for ( int j = 0; j < crow.size(); j++ ) {
effects.set( i, j, crow.get( j ) );
}
}
} else {
assert this.qr != null : " QR was null. \n" + this.diagnosis( qr );
DoubleMatrix2D q = this.qr.getQ();
effects = solver.mult( this.b, q );
}
effects.assign( Functions.square );
/*
* Add up the ssr for the columns within each factor.
*/
Set<Integer> facs = new TreeSet<Integer>();
facs.addAll( assign );
DoubleMatrix2D ssq = new DenseDoubleMatrix2D( effects.rows(), facs.size() + 1 );
DoubleMatrix2D dof = new DenseDoubleMatrix2D( effects.rows(), facs.size() + 1 );
dof.assign( 0.0 );
ssq.assign( 0.0 );
List<Integer> assignToUse = assign;
for ( int i = 0; i < ssq.rows(); i++ ) {
ssq.set( i, facs.size(), residualSumsOfSquares.get( i ) );
int rdof;
if ( this.residualDofs.isEmpty() ) {
rdof = this.residualDof;
} else {
rdof = this.residualDofs.get( i );
}
/*
* Store residual DOF in the last column.
*/
dof.set( i, facs.size(), rdof );
if ( !assigns.isEmpty() ) {
assignToUse = assigns.get( i );
}
DoubleMatrix1D effectsForRow = effects.viewRow( i );
if ( assignToUse.size() != effectsForRow.size() ) {
/*
* Effects will have NaNs (FIXME: always at end?)
*/
log.debug( "Check me: effects has missing values" );
}
for ( int j = 0; j < assignToUse.size(); j++ ) {
double valueToAdd = effectsForRow.get( j );
int col = assignToUse.get( j );
// for ( Integer col : assignToUse ) {
// double valueToAdd;
if ( col > 0 && !this.hasIntercept ) {
col = col - 1;
}
/*
* Accumulate the sum. When the data is "constant" you can end up with a tiny but non-zero coefficient,
* but it's bogus. See bug 3177.
*/
if ( !Double.isNaN( valueToAdd ) && valueToAdd > Constants.SMALL ) {
/*
* Is this always true?
*/
ssq.set( i, col, ssq.get( i, col ) + valueToAdd );
dof.set( i, col, dof.get( i, col ) + 1 );
} else {
// log.warn( "Missing value in effects for row " + i
// + ( this.rowNames == null ? "" : " (row=" + this.rowNames.get( i ) + ")" )
// + this.diagnosis( null ) );
}
}
}
// one value for each term in the model
DoubleMatrix1D denominator;
if ( this.residualDofs.isEmpty() ) {
denominator = residualSumsOfSquares.copy().assign( Functions.div( residualDof ) );
} else {
denominator = new DenseDoubleMatrix1D( residualSumsOfSquares.size() );
for ( int i = 0; i < residualSumsOfSquares.size(); i++ ) {
denominator.set( i, residualSumsOfSquares.get( i ) / residualDofs.get( i ) );
}
}
DoubleMatrix2D fStats = ssq.copy().assign( dof, Functions.div );
DoubleMatrix2D pvalues = fStats.like();
computeStats( dof, fStats, denominator, pvalues );
return summarizeAnova( ssq, dof, fStats, pvalues );
}
public DoubleMatrix2D getCoefficients() {
return coefficients;
}
public DoubleMatrix2D getFitted() {
return fitted;
}
public DoubleMatrix2D getResiduals() {
return residuals;
}
/**
* @return externally studentized residuals.
*/
public DoubleMatrix2D getStudentizedResiduals() {
int dof = this.residualDof - 1; // MINUS for external studentizing!!
assert dof > 0;
if ( this.hasMissing ) {
throw new UnsupportedOperationException( "Studentizing not supported with missing values" );
}
DoubleMatrix2D result = this.residuals.like();
/*
* Diagnonal of the hat matrix at i (hi) is the squared norm of the ith row of Q
*/
DoubleMatrix2D q = qr.getQ();
DoubleMatrix1D hatdiag = new DenseDoubleMatrix1D( residuals.columns() );
for ( int j = 0; j < residuals.columns(); j++ ) {
double hj = q.viewRow( j ).aggregate( Functions.plus, Functions.square );
if ( 1.0 - hj < Constants.TINY ) {
hj = 1.0;
}
hatdiag.set( j, hj );
}
/*
* Measure sum of squares of residuals / residualDof
*/
for ( int i = 0; i < residuals.rows(); i++ ) {
// these are 'internally studentized'
// double sdhat = Math.sqrt( residuals.viewRow( i ).aggregate( Functions.plus, Functions.square ) / dof );
DoubleMatrix1D residualRow = residuals.viewRow( i );
if ( this.weights != null ) {
// use weighted residuals.
DoubleMatrix1D w = weights.viewRow( i ).copy().assign( Functions.sqrt );
residualRow = residualRow.copy().assign( w, Functions.mult );
}
double sum = residualRow.aggregate( Functions.plus, Functions.square );
for ( int j = 0; j < residualRow.size(); j++ ) {
double hj = hatdiag.get( j );
// this is how we externalize...
double sigma;
if ( hj < 1.0 ) {
sigma = Math.sqrt( ( sum - Math.pow( residualRow.get( j ), 2 ) / ( 1.0 - hj ) ) / dof );
} else {
sigma = Math.sqrt( sum / dof );
}
double res = residualRow.getQuick( j );
double studres = res / ( sigma * Math.sqrt( 1.0 - hj ) );
if ( log.isDebugEnabled() ) log.debug( "sigma=" + sigma + " hj=" + hj + " stres=" + studres );
result.set( i, j, studres );
}
}
return result;
}
public boolean isHasMissing() {
return hasMissing;
}
public void setHasMissing( boolean hasMissing ) {
this.hasMissing = hasMissing;
}
/**
* @return summaries. ANOVA will not be computed.
*/
public List<LinearModelSummary> summarize() {
return this.summarize( false );
}
/**
* @param anova if true, ANOVA will be computed
* @return
*/
public List<LinearModelSummary> summarize( boolean anova ) {
List<LinearModelSummary> lmsresults = new ArrayList<LinearModelSummary>();
List<GenericAnovaResult> anovas = null;
if ( anova ) {
anovas = this.anova();
}
for ( int i = 0; i < this.coefficients.columns(); i++ ) {
LinearModelSummary lms = summarize( i );
lms.setAnova( anovas != null ? anovas.get( i ) : null );
lmsresults.add( lms );
}
return lmsresults;
}
/**
* @param anova
* @return
*/
public Map<String, LinearModelSummary> summarizeByKeys( boolean anova ) {
List<LinearModelSummary> summaries = this.summarize( anova );
Map<String, LinearModelSummary> result = new LinkedHashMap<String, LinearModelSummary>();
for ( LinearModelSummary lms : summaries ) {
if ( StringUtils.isBlank( lms.getKey() ) ) {
/*
* Perhaps we should just use an integer.
*/
throw new IllegalStateException( "Key must not be blank" );
}
if ( result.containsKey( lms.getKey() ) ) {
throw new IllegalStateException( "Duplicate key " + lms.getKey() );
}
result.put( lms.getKey(), lms );
}
return result;
}
private void addInteraction() {
if ( designMatrix.getTerms().size() == 1 ) {
throw new IllegalArgumentException( "Need at least two factors for interactions" );
}
if ( designMatrix.getTerms().size() != 2 ) {
throw new UnsupportedOperationException( "Interactions not supported for more than two factors" );
}
this.designMatrix.addInteraction( designMatrix.getTerms().get( 0 ), designMatrix.getTerms().get( 1 ) );
}
/**
*
*/
private void checkForMissingValues() {
for ( int i = 0; i < b.rows(); i++ ) {
for ( int j = 0; j < b.columns(); j++ ) {
double v = b.get( i, j );
if ( Double.isNaN( v ) || Double.isInfinite( v ) ) {
this.hasMissing = true;
break;
}
}
}
}
/**
* Mimics functionality of chol2inv from R (which just calls LAPACK::dpotri)
*
* @param x upper triangular matrix (from qr)
* @return symmetric matrix X'X^-1
*/
private DoubleMatrix2D dpotri( DoubleMatrix2D x ) {
// this is not numerically stable
// DoubleMatrix2D mult = solver.mult( solver.transpose( qrdR ), qrdR );
// DoubleMatrix2D R = solver.inverse( mult );
DenseMatrix denseMatrix = new DenseMatrix( x.copy().toArray() );
intW status = new intW( 0 );
LAPACK.getInstance().dpotri( "U", x.columns(), denseMatrix.getData(), x.columns(), status );
if ( status.val != 0 ) {
throw new IllegalStateException( "Could not invert matrix" );
}
return new DenseDoubleMatrix2D( Matrices.getArray( denseMatrix ) );
}
/**
* Drop, and track, redundant or constant columns. This is only used if we have missing values which would require
* changing the design depending on what is missing. Otherwise the model is assumed to be clean. Note that this does
* not check the model for singularity.
* <p>
* FIXME Probably slow if we have to run this often; should cache re-used values.
*
* @param design
* @param ypsize
* @param droppedColumns
* @return
*/
private DoubleMatrix2D cleanDesign( final DoubleMatrix2D design, int ypsize, List<Integer> droppedColumns ) {
/*
* Drop constant columns or columns which are the same as another column.
*/
for ( int j = 0; j < design.columns(); j++ ) {
if ( j == 0 && this.hasIntercept ) continue;
double lastValue = Double.NaN;
boolean constant = true;
for ( int i = 0; i < design.rows(); i++ ) {
double thisvalue = design.get( i, j );
if ( i > 0 && thisvalue != lastValue ) {
constant = false;
break;
}
lastValue = thisvalue;
}
if ( constant ) {
log.debug( "Dropping constant column " + j );
droppedColumns.add( j );
continue;
}
DoubleMatrix1D col = design.viewColumn( j );
for ( int p = 0; p < j; p++ ) {
boolean redundant = true;
DoubleMatrix1D otherCol = design.viewColumn( p );
for ( int v = 0; v < col.size(); v++ ) {
if ( col.get( v ) != otherCol.get( v ) ) {
redundant = false;
break;
}
}
if ( redundant ) {
log.debug( "Dropping redundant column " + j );
droppedColumns.add( j );
break;
}
}
}
DoubleMatrix2D returnValue = MatrixUtil.dropColumns( design, droppedColumns );
return returnValue;
}
/**
* @param dof
* @param fStats
* @param denominator
* @param pvalues
*/
private void computeStats( DoubleMatrix2D dof, DoubleMatrix2D fStats, DoubleMatrix1D denominator,
DoubleMatrix2D pvalues ) {
pvalues.assign( Double.NaN );
int timesWarned = 0;
for ( int i = 0; i < fStats.rows(); i++ ) {
int rdof;
if ( this.residualDofs.isEmpty() ) {
rdof = residualDof;
} else {
rdof = this.residualDofs.get( i );
}
for ( int j = 0; j < fStats.columns(); j++ ) {
double ndof = dof.get( i, j );
if ( ndof <= 0 || rdof <= 0 ) {
pvalues.set( i, j, Double.NaN );
fStats.set( i, j, Double.NaN );
continue;
}
if ( j == fStats.columns() - 1 ) {
// don't fill in f & p values for the residual...
pvalues.set( i, j, Double.NaN );
fStats.set( i, j, Double.NaN );
continue;
}
fStats.set( i, j, fStats.get( i, j ) / denominator.get( i ) );
try {
FDistribution pf = new FDistributionImpl( ndof, rdof );
pvalues.set( i, j, 1.0 - pf.cumulativeProbability( fStats.get( i, j ) ) );
} catch ( MathException e ) {
if ( timesWarned < 10 ) {
log.warn( "Pvalue could not be computed for F=" + fStats.get( i, j ) + "; denominator was="
+ denominator.get( i ) + "; Error: " + e.getMessage()
+ " (limited warnings of this type will be given)" );
timesWarned++;
}
pvalues.set( i, j, Double.NaN );
}
}
}
}
/**
* @param qrd
* @return
*/
private String diagnosis( QRDecompositionPivoting qrd ) {
StringBuilder buf = new StringBuilder();
buf.append( "\n--------\nLM State\n--------\n" );
buf.append( "hasMissing=" + this.hasMissing + "\n" );
buf.append( "hasIntercept=" + this.hasIntercept + "\n" );
buf.append( "Design: " + this.designMatrix + "\n" );
if ( this.b.rows() < 5 ) {
buf.append( "Data matrix: " + this.b + "\n" );
} else {
buf.append( "Data (first few rows): " + this.b.viewSelection( new int[] { 0, 1, 2, 3, 4 }, null ) + "\n" );
}
buf.append( "Current QR:" + qrd + "\n" );
return buf.toString();
}
/**
* Internal function that does the hard work.
*/
private void lsf() {
checkForMissingValues();
Algebra solver = new Algebra();
/*
* Missing values result in the addition of a fair amount of extra code.
*/
if ( this.hasMissing ) {
double[][] rawResult = new double[b.rows()][];
for ( int i = 0; i < b.rows(); i++ ) {
DoubleMatrix1D row = b.viewRow( i );
DoubleMatrix1D withoutMissing = ordinaryLeastSquaresWithMissing( row, A );
if ( withoutMissing == null ) {
rawResult[i] = new double[A.columns()];
} else {
rawResult[i] = withoutMissing.toArray();
}
}
this.coefficients = solver.transpose( new DenseDoubleMatrix2D( rawResult ) );
} else {
this.qr = new QRDecompositionPivoting( A );
this.coefficients = qr.solve( solver.transpose( b ) );
this.residualDof = b.columns() - qr.getRank();
if ( residualDof <= 0 ) {
throw new IllegalArgumentException( "No residual degrees of freedom to fit the model" + diagnosis( qr ) );
}
}
assert this.assign.isEmpty() || this.assign.size() == this.coefficients.rows() : assign.size()
+ " != # coefficients " + this.coefficients.rows();
assert this.coefficients.rows() == A.columns();
this.fitted = solver.transpose( MatrixUtil.multWithMissing( A, coefficients ) );
if ( this.hasMissing ) {
MatrixUtil.maskMissing( b, fitted );
}
this.residuals = b.copy().assign( fitted, Functions.minus );
}
/**
* Has side effect of filling in this.qrs and this.residualDofs.
*
* @param y the data to fit (a.k.a. b)
* @param des the design matrix (a.k.a A)
* @return the coefficients (a.k.a. x)
*/
private DoubleMatrix1D ordinaryLeastSquaresWithMissing( DoubleMatrix1D y, DoubleMatrix2D des ) {
Algebra solver = new Algebra();
List<Double> ywithoutMissingList = new ArrayList<Double>( y.size() );
int size = y.size();
int countNonMissing = 0;
for ( int i = 0; i < size; i++ ) {
double v = y.getQuick( i );
if ( !Double.isNaN( v ) && !Double.isInfinite( v ) ) {
countNonMissing++;
}
}
if ( countNonMissing < 3 ) {
/*
* return nothing.
*/
DoubleMatrix1D re = new DenseDoubleMatrix1D( des.columns() );
re.assign( Double.NaN );
log.debug( "Not enough non-missing values" );
this.qrs.add( null );
this.residualDofs.add( countNonMissing - des.columns() );
this.assigns.add( new ArrayList<Integer>() );
// this.pivotIndicesList.add( new Integer[] {} );
return re;
}
double[][] rawDesignWithoutMissing = new double[countNonMissing][];
int index = 0;
boolean missing = false;
for ( int i = 0; i < size; i++ ) {
double yi = y.getQuick( i );
if ( Double.isNaN( yi ) || Double.isInfinite( yi ) ) {
missing = true;
continue;
}
ywithoutMissingList.add( yi );
rawDesignWithoutMissing[index++] = des.viewRow( i ).toArray();
}
double[] yWithoutMissing = ArrayUtils.toPrimitive( ywithoutMissingList.toArray( new Double[] {} ) );
DenseDoubleMatrix2D yWithoutMissingAsMatrix = new DenseDoubleMatrix2D( new double[][] { yWithoutMissing } );
DoubleMatrix2D designWithoutMissing = new DenseDoubleMatrix2D( rawDesignWithoutMissing );
boolean mustReturn = false;
List<Integer> droppedColumns = new ArrayList<Integer>();
designWithoutMissing = this.cleanDesign( designWithoutMissing, yWithoutMissingAsMatrix.size(), droppedColumns );
if ( designWithoutMissing.columns() == 0 || designWithoutMissing.columns() > designWithoutMissing.rows() ) {
mustReturn = true;
}
if ( mustReturn ) {
DoubleMatrix1D re = new DenseDoubleMatrix1D( des.columns() );
re.assign( Double.NaN );
this.qrs.add( null );
this.residualDofs.add( countNonMissing - des.columns() );
this.assigns.add( new ArrayList<Integer>() );
// this.pivotIndicesList.add( new Integer[] {} );
return re;
}
QRDecompositionPivoting rqr = null;
if ( missing ) {
rqr = new QRDecompositionPivoting( designWithoutMissing );
} else {
if ( this.qr == null ) {
qr = new QRDecompositionPivoting( des );
}
rqr = qr;
}
this.qrs.add( rqr );
int pivots = rqr.getRank();
// this.residualDof = b.columns() - A.columns();
// this.pivotIndicesList.add( pi );
// / int rdof = yWithoutMissingAsMatrix.size() - designWithoutMissing.columns();
int rdof = yWithoutMissingAsMatrix.size() - pivots;
this.residualDofs.add( rdof );
DoubleMatrix2D coefs = rqr.solve( solver.transpose( yWithoutMissingAsMatrix ) );
/*
* Put NaNs in for missing coefficients that were dropped from our estimation.
*/
if ( designWithoutMissing.columns() < des.columns() ) {
DoubleMatrix1D col = coefs.viewColumn( 0 );
DoubleMatrix1D result = new DenseDoubleMatrix1D( des.columns() );
result.assign( Double.NaN );
int k = 0;
List<Integer> assignForRow = new ArrayList<Integer>();
for ( int i = 0; i < des.columns(); i++ ) {
if ( droppedColumns.contains( i ) ) {
// leave it as NaN.
continue;
}
assignForRow.add( this.assign.get( i ) );
assert k < col.size();
result.set( i, col.get( k ) );
k++;
}
assigns.add( assignForRow );
return result;
}
assigns.add( this.assign );
return coefs.viewColumn( 0 );
}
/**
* @param ssq
* @param dof
* @param fStats
* @param pvalues
* @return
*/
private List<GenericAnovaResult> summarizeAnova( DoubleMatrix2D ssq, DoubleMatrix2D dof, DoubleMatrix2D fStats,
DoubleMatrix2D pvalues ) {
assert ssq != null;
assert dof != null;
assert fStats != null;
assert pvalues != null;
List<GenericAnovaResult> results = new ArrayList<GenericAnovaResult>();
for ( int i = 0; i < fStats.rows(); i++ ) {
Collection<AnovaEffect> efs = new ArrayList<AnovaEffect>();
/*
* Don't put in ftest results for the residual thus the -1.
*/
for ( int j = 0; j < fStats.columns() - 1; j++ ) {
String effectName = terms.get( j );
assert effectName != null;
AnovaEffect ae = new AnovaEffect( effectName, pvalues.get( i, j ), fStats.get( i, j ), ( int ) dof.get(
i, j ), ssq.get( i, j ), effectName.contains( ":" ) );
efs.add( ae );
}
/*
* Add residual
*/
int residCol = fStats.columns() - 1;
AnovaEffect ae = new AnovaEffect( "Residual", null, null, ( int ) dof.get( i, residCol ), ssq.get( i,
residCol ), false );
efs.add( ae );
GenericAnovaResult ao = new GenericAnovaResult( efs );
if ( this.rowNames != null ) ao.setKey( this.rowNames.get( i ) );
results.add( ao );
}
return results;
}
/**
* Note: does not populate the ANOVA.
*
* @param i
* @return
*/
protected LinearModelSummary summarize( int i ) {
String key = null;
if ( this.rowNames != null ) {
key = this.rowNames.get( i );
if ( key == null ) log.warn( "Key null at " + i );
}
QRDecompositionPivoting qrd = null;
if ( this.qrs.isEmpty() ) {
qrd = this.qr; // no missing values, so it's global
} else {
qrd = this.qrs.get( i ); // row-specific
}
if ( qrd == null ) {
log.debug( "QR was null for item " + i );
return new LinearModelSummary( key );
}
int rdf;
if ( this.residualDofs.isEmpty() ) {
rdf = this.residualDof; // no missing values, so it's global
} else {
rdf = this.residualDofs.get( i ); // row-specific
}
if ( rdf == 0 ) {
return new LinearModelSummary( key );
}
DoubleMatrix1D coef = coefficients.viewColumn( i );
DoubleMatrix1D r = MatrixUtil.removeMissing( this.residuals.viewRow( i ) );
DoubleMatrix1D f = MatrixUtil.removeMissing( fitted.viewRow( i ) );
DoubleMatrix1D est = MatrixUtil.removeMissing( coef );
if ( est.size() == 0 ) {
log.warn( "No coefficients estimated for row " + i + this.diagnosis( qrd ) );
log.info( "Data for this row:\n" + this.b.viewRow( i ) );
return new LinearModelSummary( key );
}
int p = qrd.getRank();
int n = qrd.getQ().rows();
assert rdf == n - p : "Rank was not correct, expected " + rdf + " but got Q rows=" + n + ", #Coef=" + p
+ diagnosis( qrd );
double mss;
if ( hasIntercept ) {
mss = f.copy().assign( Functions.minus( Descriptive.mean( new DoubleArrayList( f.toArray() ) ) ) )
.assign( Functions.square ).aggregate( Functions.plus, Functions.identity );
} else {
mss = f.copy().assign( Functions.square ).aggregate( Functions.plus, Functions.identity );
}
double rss = r.copy().assign( Functions.square ).aggregate( Functions.plus, Functions.identity );
double resvar = rss / rdf;
/*
* These next two lines could be computationally expensive; there is no need to compute these over and over in
* many cases.
*/
DoubleMatrix2D qrdR = qrd.getR();
DoubleMatrix2D R = dpotri( qrdR.viewPart( 0, 0, qrd.getRank(), qrd.getRank() ) );
// matrix to hold the coefficients.
DoubleMatrix<String, String> coeffMat = DoubleMatrixFactory.dense( coef.size(), 4 );
coeffMat.assign( Double.NaN );
coeffMat.setColumnNames( Arrays.asList( new String[] { "Estimate", "Std. Error", "t value", "Pr(>|t|)" } ) );
DoubleMatrix1D se = MatrixUtil.diagonal( R ).assign( Functions.mult( resvar ) ).assign( Functions.sqrt );
if ( est.size() != se.size() ) {
/*
* This should actually not happen, due to pivoting.
*/
if ( !hasWarned ) {
log.warn( "T statistics could not be computed because of missing values (singularity?) " + i
+ this.diagnosis( qrd ) );
log.warn( "Data for this row:\n" + this.b.viewRow( i ) );
log.warn( "Additional warnings suppressed" );
hasWarned = true;
}
return new LinearModelSummary( key, terms, ArrayUtils.toObject( this.residuals.viewRow( i ).toArray() ),
coeffMat, 0.0, 0.0, 0.0, 0, 0, null );
}
DoubleMatrix1D tval = est.copy().assign( se, Functions.div );
TDistribution tdist = new TDistributionImpl( rdf );
int j = 0;
for ( int ti = 0; ti < coef.size(); ti++ ) {
double c = coef.get( ti );
assert this.designMatrix != null;
List<String> colNames = this.designMatrix.getMatrix().getColNames();
String dmcolname;
if ( colNames == null ) {
dmcolname = "Column_" + ti;
} else {
dmcolname = colNames.get( ti );
}
/* FIXME the contrast should be stored in there. */
coeffMat.addRowName( dmcolname );
if ( Double.isNaN( c ) ) {
continue;
}
coeffMat.set( ti, 0, est.get( j ) );
coeffMat.set( ti, 1, se.get( j ) );
coeffMat.set( ti, 2, tval.get( j ) );
try {
double pval = 2.0 * ( 1.0 - tdist.cumulativeProbability( Math.abs( tval.get( j ) ) ) );
coeffMat.set( ti, 3, pval );
} catch ( MathException e ) {
coeffMat.set( ti, 3, Double.NaN );
}
j++;
}
double rsquared = 0.0;
double adjRsquared = 0.0;
double fstatistic = 0.0;
int numdf = 0;
int dendf = 0;
// is there anything besides the intercept???
if ( terms.size() > 1 || !hasIntercept ) {
int dfint = hasIntercept ? 1 : 0;
rsquared = mss / ( mss + rss );
adjRsquared = 1 - ( 1 - rsquared * ( ( n - dfint ) / ( double ) rdf ) );
fstatistic = mss / ( p - dfint ) / resvar;
numdf = p - dfint;
dendf = rdf;
} else {
// intercept only, apparently.
rsquared = 0.0;
adjRsquared = 0.0;
}
LinearModelSummary lms = new LinearModelSummary( key, terms, ArrayUtils.toObject( this.residuals.viewRow( i )
.toArray() ), coeffMat, rsquared, adjRsquared, fstatistic, numdf, dendf, null );
return lms;
}
}
| src/ubic/basecode/math/LeastSquaresFit.java | /*
* The baseCode project
*
* Copyright (c) 2011 University of British Columbia
*
* 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 ubic.basecode.math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import no.uib.cipr.matrix.DenseMatrix;
import no.uib.cipr.matrix.Matrices;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.FDistribution;
import org.apache.commons.math.distribution.FDistributionImpl;
import org.apache.commons.math.distribution.TDistribution;
import org.apache.commons.math.distribution.TDistributionImpl;
import org.netlib.lapack.LAPACK;
import org.netlib.util.intW;
import ubic.basecode.dataStructure.matrix.DoubleMatrix;
import ubic.basecode.dataStructure.matrix.DoubleMatrixFactory;
import ubic.basecode.dataStructure.matrix.MatrixUtil;
import ubic.basecode.dataStructure.matrix.ObjectMatrix;
import ubic.basecode.util.r.type.AnovaEffect;
import ubic.basecode.util.r.type.GenericAnovaResult;
import ubic.basecode.util.r.type.LinearModelSummary;
import cern.colt.function.IntIntDoubleFunction;
import cern.colt.list.DoubleArrayList;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.linalg.Algebra;
import cern.jet.math.Functions;
import cern.jet.stat.Descriptive;
/**
* For performing "bulk" linear model fits. Allows rapid fitting to large data sets.
*
* @author paul
* @version $Id$
*/
public class LeastSquaresFit {
/*
* Making this static causes problems with memory leaks/garbage that is not efficiently collected.
*/
// private static Algebra solver = new Algebra();
/**
* Model fix coefficients (the x in Ax=b)
*/
private DoubleMatrix2D coefficients = null;
/**
*
*/
private boolean hasMissing = false;
/**
* Fitted values
*/
private DoubleMatrix2D fitted;
/**
* Residuals of the fit
*/
private DoubleMatrix2D residuals;
/**
* QR decomposition of the design matrix
*/
private QRDecompositionPivoting qr;
/**
* The (raw) design matrix
*/
private DoubleMatrix2D A;
/**
* Independent variables
*/
private DoubleMatrix2D b;
private int residualDof;
private boolean hasWarned = false;
/*
* Lists which factors (terms) are associated with which columns of the design matrix; 0 indicates the intercept.
*/
private List<Integer> assign = new ArrayList<Integer>();
/*
* Names of the factors (terms)
*/
private List<String> terms;
private DesignMatrix designMatrix;
/*
* Optional, but useful
*/
private List<String> rowNames;
/*
* Used if we have missing values so QR might be different for each row (possible optimization to consider: only
* store set of variants that are actually used)
*/
private List<QRDecompositionPivoting> qrs = new ArrayList<QRDecompositionPivoting>();
/*
* Used if we have missing value so RDOF might be different for each row (we can actually get away without this)
*/
private List<Integer> residualDofs = new ArrayList<Integer>();
private boolean hasIntercept = true;
private List<List<Integer>> assigns = new ArrayList<List<Integer>>();
/*
* For weighted regression
*/
private DoubleMatrix2D weights = null;
// private List<Integer[]> pivotIndicesList = new ArrayList<Integer[]>();
private static Log log = LogFactory.getLog( LeastSquaresFit.class );
/**
* Preferred interface if you want control over how the design is set up.
*
* @param designMatrix
* @param data
*/
public LeastSquaresFit( DesignMatrix designMatrix, DoubleMatrix<String, String> data ) {
this.designMatrix = designMatrix;
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.rowNames = data.getRowNames();
this.b = new DenseDoubleMatrix2D( data.asArray() );
boolean hasInterceptTerm = this.terms.contains( LinearModelSummary.INTERCEPT_COEFFICIENT_NAME );
this.hasIntercept = designMatrix.hasIntercept();
assert hasInterceptTerm == this.hasIntercept : diagnosis( null );
lsf();
}
/**
* Stripped-down interface for simple use. ANOVA not possible (use the other constructors)
*
* @param A Design matrix, which will be used directly in least squares regression
* @param b Data matrix, containing data in rows.
*/
public LeastSquaresFit( DoubleMatrix2D A, DoubleMatrix2D b ) {
this.A = A;
this.b = b;
lsf();
}
/**
* Least squares fit between two vectors. Always adds an intercept!
*
* @param vectorA Design
* @param vectorB Data
* @param weights to be used in modifying the influence of the observations in vectorB.
*/
public LeastSquaresFit( DoubleMatrix1D vectorA, DoubleMatrix1D vectorB, final DoubleMatrix1D weights ) {
assert vectorA.size() == vectorB.size();
assert vectorA.size() == weights.size();
this.A = new DenseDoubleMatrix2D( vectorA.size(), 2 );
this.b = new DenseDoubleMatrix2D( 1, vectorB.size() );
this.weights = new DenseDoubleMatrix2D( 1, weights.size() );
for ( int i = 0; i < vectorA.size(); i++ ) {
double ws = Math.sqrt( weights.get( i ) );
A.set( i, 0, ws );
A.set( i, 1, vectorA.get( i ) * ws );
b.set( 0, i, vectorB.get( i ) * ws );
this.weights.set( 0, i, weights.get( i ) );
}
lsf();
residuals = residuals.forEachNonZero( new IntIntDoubleFunction() {
@Override
public double apply( int row, int col, double nonZeroValue ) {
return nonZeroValue / Math.sqrt( weights.get( col ) );
}
} );
DoubleMatrix1D f2 = vectorB.copy().assign( residuals.viewRow( 0 ), Functions.minus );
this.fitted.viewRow( 0 ).assign( f2 );
}
/**
* Least squares fit between two vectors. Always adds an intercept!
*
* @param vectorA Design
* @param vectorB Data
*/
public LeastSquaresFit( DoubleMatrix1D vectorA, DoubleMatrix1D vectorB ) {
assert vectorA.size() == vectorB.size();
this.A = new DenseDoubleMatrix2D( vectorA.size(), 2 );
this.b = new DenseDoubleMatrix2D( 1, vectorB.size() );
for ( int i = 0; i < vectorA.size(); i++ ) {
A.set( i, 0, 1 );
A.set( i, 1, vectorA.get( i ) );
b.set( 0, i, vectorB.get( i ) );
}
lsf();
}
/**
* @param sample information that will be converted to a design matrix; intercept term is added.
* @param data Data matrix
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> sampleInfo, DenseDoubleMatrix2D data ) {
this.designMatrix = new DesignMatrix( sampleInfo, true );
this.hasIntercept = true;
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = data;
lsf();
}
/**
* @param sampleInfo
* @param data
* @param interactions add interaction term (two-way only is supported)
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> sampleInfo, DenseDoubleMatrix2D data,
boolean interactions ) {
this.designMatrix = new DesignMatrix( sampleInfo, true );
if ( interactions ) {
addInteraction();
}
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = data;
lsf();
}
/**
* NamedMatrix allows easier handling of the results.
*
* @param sample information that will be converted to a design matrix; intercept term is added.
* @param b Data matrix
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> design, DoubleMatrix<String, String> b ) {
this.designMatrix = new DesignMatrix( design, true );
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = new DenseDoubleMatrix2D( b.asArray() );
this.rowNames = b.getRowNames();
lsf();
}
/**
* NamedMatrix allows easier handling of the results.
*
* @param sample information that will be converted to a design matrix; intercept term is added.
* @param data Data matrix
*/
public LeastSquaresFit( ObjectMatrix<String, String, Object> design, DoubleMatrix<String, String> data,
boolean interactions ) {
this.designMatrix = new DesignMatrix( design, true );
if ( interactions ) {
addInteraction();
}
DoubleMatrix2D X = designMatrix.getDoubleMatrix();
this.assign = designMatrix.getAssign();
this.terms = designMatrix.getTerms();
this.A = X;
this.b = new DenseDoubleMatrix2D( data.asArray() );
lsf();
}
/**
* Compute ANOVA based on the model fit
*
* @return
*/
public List<GenericAnovaResult> anova() {
Algebra solver = new Algebra();
DoubleMatrix1D ones = new DenseDoubleMatrix1D( residuals.columns() );
ones.assign( 1.0 );
DoubleMatrix1D residualSumsOfSquares = MatrixUtil.multWithMissing( residuals.copy().assign( Functions.square ),
ones );
DoubleMatrix2D effects = null;
if ( this.hasMissing ) {
effects = new DenseDoubleMatrix2D( this.b.rows(), this.A.columns() );
effects.assign( Double.NaN );
for ( int i = 0; i < this.b.rows(); i++ ) {
// if ( this.rowNames.get( i ).equals( "probe_60" ) ) {
// log.info( "MARV" );
// }
QRDecompositionPivoting qrd = this.qrs.get( i );
if ( qrd == null ) {
// means we did not get a fit
for ( int j = 0; j < effects.columns(); j++ ) {
effects.set( i, j, Double.NaN );
}
continue;
}
DoubleMatrix1D brow = b.viewRow( i );
DoubleMatrix1D browWithoutMissing = MatrixUtil.removeMissing( brow );
DoubleMatrix2D qrow = qrd.getQ().viewPart( 0, 0, browWithoutMissing.size(), qrd.getRank() );
// will never happen.
// if ( qrow.rows() != browWithoutMissing.size() ) {
// for ( int j = 0; j < effects.columns(); j++ ) {
// effects.set( i, j, Double.NaN );
// }
// continue;
// }
DoubleMatrix1D crow = MatrixUtil.multWithMissing( browWithoutMissing, qrow );
for ( int j = 0; j < crow.size(); j++ ) {
effects.set( i, j, crow.get( j ) );
}
}
} else {
assert this.qr != null : " QR was null. \n" + this.diagnosis( qr );
DoubleMatrix2D q = this.qr.getQ();
effects = solver.mult( this.b, q );
}
effects.assign( Functions.square );
/*
* Add up the ssr for the columns within each factor.
*/
Set<Integer> facs = new TreeSet<Integer>();
facs.addAll( assign );
DoubleMatrix2D ssq = new DenseDoubleMatrix2D( effects.rows(), facs.size() + 1 );
DoubleMatrix2D dof = new DenseDoubleMatrix2D( effects.rows(), facs.size() + 1 );
dof.assign( 0.0 );
ssq.assign( 0.0 );
List<Integer> assignToUse = assign;
for ( int i = 0; i < ssq.rows(); i++ ) {
ssq.set( i, facs.size(), residualSumsOfSquares.get( i ) );
int rdof;
if ( this.residualDofs.isEmpty() ) {
rdof = this.residualDof;
} else {
rdof = this.residualDofs.get( i );
}
/*
* Store residual DOF in the last column.
*/
dof.set( i, facs.size(), rdof );
if ( !assigns.isEmpty() ) {
assignToUse = assigns.get( i );
}
DoubleMatrix1D effectsForRow = effects.viewRow( i );
if ( assignToUse.size() != effectsForRow.size() ) {
/*
* Effects will have NaNs (FIXME: always at end?)
*/
log.debug( "Check me: effects has missing values" );
}
for ( int j = 0; j < assignToUse.size(); j++ ) {
double valueToAdd = effectsForRow.get( j );
int col = assignToUse.get( j );
// for ( Integer col : assignToUse ) {
// double valueToAdd;
if ( col > 0 && !this.hasIntercept ) {
col = col - 1;
}
/*
* Accumulate the sum. When the data is "constant" you can end up with a tiny but non-zero coefficient,
* but it's bogus. See bug 3177.
*/
if ( !Double.isNaN( valueToAdd ) && valueToAdd > Constants.TINY ) {
/*
* Is this always true?
*/
ssq.set( i, col, ssq.get( i, col ) + valueToAdd );
dof.set( i, col, dof.get( i, col ) + 1 );
} else {
// log.warn( "Missing value in effects for row " + i
// + ( this.rowNames == null ? "" : " (row=" + this.rowNames.get( i ) + ")" )
// + this.diagnosis( null ) );
}
}
}
// one value for each term in the model
DoubleMatrix1D denominator;
if ( this.residualDofs.isEmpty() ) {
denominator = residualSumsOfSquares.copy().assign( Functions.div( residualDof ) );
} else {
denominator = new DenseDoubleMatrix1D( residualSumsOfSquares.size() );
for ( int i = 0; i < residualSumsOfSquares.size(); i++ ) {
denominator.set( i, residualSumsOfSquares.get( i ) / residualDofs.get( i ) );
}
}
DoubleMatrix2D fStats = ssq.copy().assign( dof, Functions.div );
DoubleMatrix2D pvalues = fStats.like();
computeStats( dof, fStats, denominator, pvalues );
return summarizeAnova( ssq, dof, fStats, pvalues );
}
public DoubleMatrix2D getCoefficients() {
return coefficients;
}
public DoubleMatrix2D getFitted() {
return fitted;
}
public DoubleMatrix2D getResiduals() {
return residuals;
}
/**
* @return externally studentized residuals.
*/
public DoubleMatrix2D getStudentizedResiduals() {
int dof = this.residualDof - 1; // MINUS for external studentizing!!
assert dof > 0;
if ( this.hasMissing ) {
throw new UnsupportedOperationException( "Studentizing not supported with missing values" );
}
DoubleMatrix2D result = this.residuals.like();
/*
* Diagnonal of the hat matrix at i (hi) is the squared norm of the ith row of Q
*/
DoubleMatrix2D q = qr.getQ();
DoubleMatrix1D hatdiag = new DenseDoubleMatrix1D( residuals.columns() );
for ( int j = 0; j < residuals.columns(); j++ ) {
double hj = q.viewRow( j ).aggregate( Functions.plus, Functions.square );
if ( 1.0 - hj < Constants.TINY ) {
hj = 1.0;
}
hatdiag.set( j, hj );
}
/*
* Measure sum of squares of residuals / residualDof
*/
for ( int i = 0; i < residuals.rows(); i++ ) {
// these are 'internally studentized'
// double sdhat = Math.sqrt( residuals.viewRow( i ).aggregate( Functions.plus, Functions.square ) / dof );
DoubleMatrix1D residualRow = residuals.viewRow( i );
if ( this.weights != null ) {
// use weighted residuals.
DoubleMatrix1D w = weights.viewRow( i ).copy().assign( Functions.sqrt );
residualRow = residualRow.copy().assign( w, Functions.mult );
}
double sum = residualRow.aggregate( Functions.plus, Functions.square );
for ( int j = 0; j < residualRow.size(); j++ ) {
double hj = hatdiag.get( j );
// this is how we externalize...
double sigma;
if ( hj < 1.0 ) {
sigma = Math.sqrt( ( sum - Math.pow( residualRow.get( j ), 2 ) / ( 1.0 - hj ) ) / dof );
} else {
sigma = Math.sqrt( sum / dof );
}
double res = residualRow.getQuick( j );
double studres = res / ( sigma * Math.sqrt( 1.0 - hj ) );
if ( log.isDebugEnabled() ) log.debug( "sigma=" + sigma + " hj=" + hj + " stres=" + studres );
result.set( i, j, studres );
}
}
return result;
}
public boolean isHasMissing() {
return hasMissing;
}
public void setHasMissing( boolean hasMissing ) {
this.hasMissing = hasMissing;
}
/**
* @return summaries. ANOVA will not be computed.
*/
public List<LinearModelSummary> summarize() {
return this.summarize( false );
}
/**
* @param anova if true, ANOVA will be computed
* @return
*/
public List<LinearModelSummary> summarize( boolean anova ) {
List<LinearModelSummary> lmsresults = new ArrayList<LinearModelSummary>();
List<GenericAnovaResult> anovas = null;
if ( anova ) {
anovas = this.anova();
}
for ( int i = 0; i < this.coefficients.columns(); i++ ) {
LinearModelSummary lms = summarize( i );
lms.setAnova( anovas != null ? anovas.get( i ) : null );
lmsresults.add( lms );
}
return lmsresults;
}
/**
* @param anova
* @return
*/
public Map<String, LinearModelSummary> summarizeByKeys( boolean anova ) {
List<LinearModelSummary> summaries = this.summarize( anova );
Map<String, LinearModelSummary> result = new LinkedHashMap<String, LinearModelSummary>();
for ( LinearModelSummary lms : summaries ) {
if ( StringUtils.isBlank( lms.getKey() ) ) {
/*
* Perhaps we should just use an integer.
*/
throw new IllegalStateException( "Key must not be blank" );
}
if ( result.containsKey( lms.getKey() ) ) {
throw new IllegalStateException( "Duplicate key " + lms.getKey() );
}
result.put( lms.getKey(), lms );
}
return result;
}
private void addInteraction() {
if ( designMatrix.getTerms().size() == 1 ) {
throw new IllegalArgumentException( "Need at least two factors for interactions" );
}
if ( designMatrix.getTerms().size() != 2 ) {
throw new UnsupportedOperationException( "Interactions not supported for more than two factors" );
}
this.designMatrix.addInteraction( designMatrix.getTerms().get( 0 ), designMatrix.getTerms().get( 1 ) );
}
/**
*
*/
private void checkForMissingValues() {
for ( int i = 0; i < b.rows(); i++ ) {
for ( int j = 0; j < b.columns(); j++ ) {
double v = b.get( i, j );
if ( Double.isNaN( v ) || Double.isInfinite( v ) ) {
this.hasMissing = true;
break;
}
}
}
}
/**
* Mimics functionality of chol2inv from R (which just calls LAPACK::dpotri)
*
* @param x upper triangular matrix (from qr)
* @return symmetric matrix X'X^-1
*/
private DoubleMatrix2D dpotri( DoubleMatrix2D x ) {
// this is not numerically stable
// DoubleMatrix2D mult = solver.mult( solver.transpose( qrdR ), qrdR );
// DoubleMatrix2D R = solver.inverse( mult );
DenseMatrix denseMatrix = new DenseMatrix( x.copy().toArray() );
intW status = new intW( 0 );
LAPACK.getInstance().dpotri( "U", x.columns(), denseMatrix.getData(), x.columns(), status );
if ( status.val != 0 ) {
throw new IllegalStateException( "Could not invert matrix" );
}
return new DenseDoubleMatrix2D( Matrices.getArray( denseMatrix ) );
}
/**
* Drop, and track, redundant or constant columns. This is only used if we have missing values which would require
* changing the design depending on what is missing. Otherwise the model is assumed to be clean. Note that this does
* not check the model for singularity.
* <p>
* FIXME Probably slow if we have to run this often; should cache re-used values.
*
* @param design
* @param ypsize
* @param droppedColumns
* @return
*/
private DoubleMatrix2D cleanDesign( final DoubleMatrix2D design, int ypsize, List<Integer> droppedColumns ) {
/*
* Drop constant columns or columns which are the same as another column.
*/
for ( int j = 0; j < design.columns(); j++ ) {
if ( j == 0 && this.hasIntercept ) continue;
double lastValue = Double.NaN;
boolean constant = true;
for ( int i = 0; i < design.rows(); i++ ) {
double thisvalue = design.get( i, j );
if ( i > 0 && thisvalue != lastValue ) {
constant = false;
break;
}
lastValue = thisvalue;
}
if ( constant ) {
log.debug( "Dropping constant column " + j );
droppedColumns.add( j );
continue;
}
DoubleMatrix1D col = design.viewColumn( j );
for ( int p = 0; p < j; p++ ) {
boolean redundant = true;
DoubleMatrix1D otherCol = design.viewColumn( p );
for ( int v = 0; v < col.size(); v++ ) {
if ( col.get( v ) != otherCol.get( v ) ) {
redundant = false;
break;
}
}
if ( redundant ) {
log.debug( "Dropping redundant column " + j );
droppedColumns.add( j );
break;
}
}
}
DoubleMatrix2D returnValue = MatrixUtil.dropColumns( design, droppedColumns );
return returnValue;
}
/**
* @param dof
* @param fStats
* @param denominator
* @param pvalues
*/
private void computeStats( DoubleMatrix2D dof, DoubleMatrix2D fStats, DoubleMatrix1D denominator,
DoubleMatrix2D pvalues ) {
pvalues.assign( Double.NaN );
int timesWarned = 0;
for ( int i = 0; i < fStats.rows(); i++ ) {
int rdof;
if ( this.residualDofs.isEmpty() ) {
rdof = residualDof;
} else {
rdof = this.residualDofs.get( i );
}
for ( int j = 0; j < fStats.columns(); j++ ) {
double ndof = dof.get( i, j );
if ( ndof <= 0 || rdof <= 0 ) {
pvalues.set( i, j, Double.NaN );
fStats.set( i, j, Double.NaN );
continue;
}
if ( j == fStats.columns() - 1 ) {
// don't fill in f & p values for the residual...
pvalues.set( i, j, Double.NaN );
fStats.set( i, j, Double.NaN );
continue;
}
fStats.set( i, j, fStats.get( i, j ) / denominator.get( i ) );
try {
FDistribution pf = new FDistributionImpl( ndof, rdof );
pvalues.set( i, j, 1.0 - pf.cumulativeProbability( fStats.get( i, j ) ) );
} catch ( MathException e ) {
if ( timesWarned < 10 ) {
log.warn( "Pvalue could not be computed for F=" + fStats.get( i, j ) + "; denominator was="
+ denominator.get( i ) + "; Error: " + e.getMessage()
+ " (limited warnings of this type will be given)" );
timesWarned++;
}
pvalues.set( i, j, Double.NaN );
}
}
}
}
/**
* @param qrd
* @return
*/
private String diagnosis( QRDecompositionPivoting qrd ) {
StringBuilder buf = new StringBuilder();
buf.append( "\n--------\nLM State\n--------\n" );
buf.append( "hasMissing=" + this.hasMissing + "\n" );
buf.append( "hasIntercept=" + this.hasIntercept + "\n" );
buf.append( "Design: " + this.designMatrix + "\n" );
if ( this.b.rows() < 5 ) {
buf.append( "Data matrix: " + this.b + "\n" );
} else {
buf.append( "Data (first few rows): " + this.b.viewSelection( new int[] { 0, 1, 2, 3, 4 }, null ) + "\n" );
}
buf.append( "Current QR:" + qrd + "\n" );
return buf.toString();
}
/**
* Internal function that does the hard work.
*/
private void lsf() {
checkForMissingValues();
Algebra solver = new Algebra();
/*
* Missing values result in the addition of a fair amount of extra code.
*/
if ( this.hasMissing ) {
double[][] rawResult = new double[b.rows()][];
for ( int i = 0; i < b.rows(); i++ ) {
DoubleMatrix1D row = b.viewRow( i );
DoubleMatrix1D withoutMissing = ordinaryLeastSquaresWithMissing( row, A );
if ( withoutMissing == null ) {
rawResult[i] = new double[A.columns()];
} else {
rawResult[i] = withoutMissing.toArray();
}
}
this.coefficients = solver.transpose( new DenseDoubleMatrix2D( rawResult ) );
} else {
this.qr = new QRDecompositionPivoting( A );
this.coefficients = qr.solve( solver.transpose( b ) );
this.residualDof = b.columns() - qr.getRank();
if ( residualDof <= 0 ) {
throw new IllegalArgumentException( "No residual degrees of freedom to fit the model" + diagnosis( qr ) );
}
}
assert this.assign.isEmpty() || this.assign.size() == this.coefficients.rows() : assign.size()
+ " != # coefficients " + this.coefficients.rows();
assert this.coefficients.rows() == A.columns();
this.fitted = solver.transpose( MatrixUtil.multWithMissing( A, coefficients ) );
if ( this.hasMissing ) {
MatrixUtil.maskMissing( b, fitted );
}
this.residuals = b.copy().assign( fitted, Functions.minus );
}
/**
* Has side effect of filling in this.qrs and this.residualDofs.
*
* @param y the data to fit (a.k.a. b)
* @param des the design matrix (a.k.a A)
* @return the coefficients (a.k.a. x)
*/
private DoubleMatrix1D ordinaryLeastSquaresWithMissing( DoubleMatrix1D y, DoubleMatrix2D des ) {
Algebra solver = new Algebra();
List<Double> ywithoutMissingList = new ArrayList<Double>( y.size() );
int size = y.size();
int countNonMissing = 0;
for ( int i = 0; i < size; i++ ) {
double v = y.getQuick( i );
if ( !Double.isNaN( v ) && !Double.isInfinite( v ) ) {
countNonMissing++;
}
}
if ( countNonMissing < 3 ) {
/*
* return nothing.
*/
DoubleMatrix1D re = new DenseDoubleMatrix1D( des.columns() );
re.assign( Double.NaN );
log.debug( "Not enough non-missing values" );
this.qrs.add( null );
this.residualDofs.add( countNonMissing - des.columns() );
this.assigns.add( new ArrayList<Integer>() );
// this.pivotIndicesList.add( new Integer[] {} );
return re;
}
double[][] rawDesignWithoutMissing = new double[countNonMissing][];
int index = 0;
boolean missing = false;
for ( int i = 0; i < size; i++ ) {
double yi = y.getQuick( i );
if ( Double.isNaN( yi ) || Double.isInfinite( yi ) ) {
missing = true;
continue;
}
ywithoutMissingList.add( yi );
rawDesignWithoutMissing[index++] = des.viewRow( i ).toArray();
}
double[] yWithoutMissing = ArrayUtils.toPrimitive( ywithoutMissingList.toArray( new Double[] {} ) );
DenseDoubleMatrix2D yWithoutMissingAsMatrix = new DenseDoubleMatrix2D( new double[][] { yWithoutMissing } );
DoubleMatrix2D designWithoutMissing = new DenseDoubleMatrix2D( rawDesignWithoutMissing );
boolean mustReturn = false;
List<Integer> droppedColumns = new ArrayList<Integer>();
designWithoutMissing = this.cleanDesign( designWithoutMissing, yWithoutMissingAsMatrix.size(), droppedColumns );
if ( designWithoutMissing.columns() == 0 || designWithoutMissing.columns() > designWithoutMissing.rows() ) {
mustReturn = true;
}
if ( mustReturn ) {
DoubleMatrix1D re = new DenseDoubleMatrix1D( des.columns() );
re.assign( Double.NaN );
this.qrs.add( null );
this.residualDofs.add( countNonMissing - des.columns() );
this.assigns.add( new ArrayList<Integer>() );
// this.pivotIndicesList.add( new Integer[] {} );
return re;
}
QRDecompositionPivoting rqr = null;
if ( missing ) {
rqr = new QRDecompositionPivoting( designWithoutMissing );
} else {
if ( this.qr == null ) {
qr = new QRDecompositionPivoting( des );
}
rqr = qr;
}
this.qrs.add( rqr );
int pivots = rqr.getRank();
// this.residualDof = b.columns() - A.columns();
// this.pivotIndicesList.add( pi );
// / int rdof = yWithoutMissingAsMatrix.size() - designWithoutMissing.columns();
int rdof = yWithoutMissingAsMatrix.size() - pivots;
this.residualDofs.add( rdof );
DoubleMatrix2D coefs = rqr.solve( solver.transpose( yWithoutMissingAsMatrix ) );
/*
* Put NaNs in for missing coefficients that were dropped from our estimation.
*/
if ( designWithoutMissing.columns() < des.columns() ) {
DoubleMatrix1D col = coefs.viewColumn( 0 );
DoubleMatrix1D result = new DenseDoubleMatrix1D( des.columns() );
result.assign( Double.NaN );
int k = 0;
List<Integer> assignForRow = new ArrayList<Integer>();
for ( int i = 0; i < des.columns(); i++ ) {
if ( droppedColumns.contains( i ) ) {
// leave it as NaN.
continue;
}
assignForRow.add( this.assign.get( i ) );
assert k < col.size();
result.set( i, col.get( k ) );
k++;
}
assigns.add( assignForRow );
return result;
}
assigns.add( this.assign );
return coefs.viewColumn( 0 );
}
/**
* @param ssq
* @param dof
* @param fStats
* @param pvalues
* @return
*/
private List<GenericAnovaResult> summarizeAnova( DoubleMatrix2D ssq, DoubleMatrix2D dof, DoubleMatrix2D fStats,
DoubleMatrix2D pvalues ) {
assert ssq != null;
assert dof != null;
assert fStats != null;
assert pvalues != null;
List<GenericAnovaResult> results = new ArrayList<GenericAnovaResult>();
for ( int i = 0; i < fStats.rows(); i++ ) {
Collection<AnovaEffect> efs = new ArrayList<AnovaEffect>();
/*
* Don't put in ftest results for the residual thus the -1.
*/
for ( int j = 0; j < fStats.columns() - 1; j++ ) {
String effectName = terms.get( j );
assert effectName != null;
AnovaEffect ae = new AnovaEffect( effectName, pvalues.get( i, j ), fStats.get( i, j ), ( int ) dof.get(
i, j ), ssq.get( i, j ), effectName.contains( ":" ) );
efs.add( ae );
}
/*
* Add residual
*/
int residCol = fStats.columns() - 1;
AnovaEffect ae = new AnovaEffect( "Residual", null, null, ( int ) dof.get( i, residCol ), ssq.get( i,
residCol ), false );
efs.add( ae );
GenericAnovaResult ao = new GenericAnovaResult( efs );
if ( this.rowNames != null ) ao.setKey( this.rowNames.get( i ) );
results.add( ao );
}
return results;
}
/**
* Note: does not populate the ANOVA.
*
* @param i
* @return
*/
protected LinearModelSummary summarize( int i ) {
String key = null;
if ( this.rowNames != null ) {
key = this.rowNames.get( i );
if ( key == null ) log.warn( "Key null at " + i );
}
QRDecompositionPivoting qrd = null;
if ( this.qrs.isEmpty() ) {
qrd = this.qr; // no missing values, so it's global
} else {
qrd = this.qrs.get( i ); // row-specific
}
if ( qrd == null ) {
log.debug( "QR was null for item " + i );
return new LinearModelSummary( key );
}
int rdf;
if ( this.residualDofs.isEmpty() ) {
rdf = this.residualDof; // no missing values, so it's global
} else {
rdf = this.residualDofs.get( i ); // row-specific
}
if ( rdf == 0 ) {
return new LinearModelSummary( key );
}
DoubleMatrix1D coef = coefficients.viewColumn( i );
DoubleMatrix1D r = MatrixUtil.removeMissing( this.residuals.viewRow( i ) );
DoubleMatrix1D f = MatrixUtil.removeMissing( fitted.viewRow( i ) );
DoubleMatrix1D est = MatrixUtil.removeMissing( coef );
if ( est.size() == 0 ) {
log.warn( "No coefficients estimated for row " + i + this.diagnosis( qrd ) );
log.info( "Data for this row:\n" + this.b.viewRow( i ) );
return new LinearModelSummary( key );
}
int p = qrd.getRank();
int n = qrd.getQ().rows();
assert rdf == n - p : "Rank was not correct, expected " + rdf + " but got Q rows=" + n + ", #Coef=" + p
+ diagnosis( qrd );
double mss;
if ( hasIntercept ) {
mss = f.copy().assign( Functions.minus( Descriptive.mean( new DoubleArrayList( f.toArray() ) ) ) )
.assign( Functions.square ).aggregate( Functions.plus, Functions.identity );
} else {
mss = f.copy().assign( Functions.square ).aggregate( Functions.plus, Functions.identity );
}
double rss = r.copy().assign( Functions.square ).aggregate( Functions.plus, Functions.identity );
double resvar = rss / rdf;
/*
* These next two lines could be computationally expensive; there is no need to compute these over and over in
* many cases.
*/
DoubleMatrix2D qrdR = qrd.getR();
DoubleMatrix2D R = dpotri( qrdR.viewPart( 0, 0, qrd.getRank(), qrd.getRank() ) );
// matrix to hold the coefficients.
DoubleMatrix<String, String> coeffMat = DoubleMatrixFactory.dense( coef.size(), 4 );
coeffMat.assign( Double.NaN );
coeffMat.setColumnNames( Arrays.asList( new String[] { "Estimate", "Std. Error", "t value", "Pr(>|t|)" } ) );
DoubleMatrix1D se = MatrixUtil.diagonal( R ).assign( Functions.mult( resvar ) ).assign( Functions.sqrt );
if ( est.size() != se.size() ) {
/*
* This should actually not happen, due to pivoting.
*/
if ( !hasWarned ) {
log.warn( "T statistics could not be computed because of missing values (singularity?) " + i
+ this.diagnosis( qrd ) );
log.warn( "Data for this row:\n" + this.b.viewRow( i ) );
log.warn( "Additional warnings suppressed" );
hasWarned = true;
}
return new LinearModelSummary( key, terms, ArrayUtils.toObject( this.residuals.viewRow( i ).toArray() ),
coeffMat, 0.0, 0.0, 0.0, 0, 0, null );
}
DoubleMatrix1D tval = est.copy().assign( se, Functions.div );
TDistribution tdist = new TDistributionImpl( rdf );
int j = 0;
for ( int ti = 0; ti < coef.size(); ti++ ) {
double c = coef.get( ti );
assert this.designMatrix != null;
List<String> colNames = this.designMatrix.getMatrix().getColNames();
String dmcolname;
if ( colNames == null ) {
dmcolname = "Column_" + ti;
} else {
dmcolname = colNames.get( ti );
}
/* FIXME the contrast should be stored in there. */
coeffMat.addRowName( dmcolname );
if ( Double.isNaN( c ) ) {
continue;
}
coeffMat.set( ti, 0, est.get( j ) );
coeffMat.set( ti, 1, se.get( j ) );
coeffMat.set( ti, 2, tval.get( j ) );
try {
double pval = 2.0 * ( 1.0 - tdist.cumulativeProbability( Math.abs( tval.get( j ) ) ) );
coeffMat.set( ti, 3, pval );
} catch ( MathException e ) {
coeffMat.set( ti, 3, Double.NaN );
}
j++;
}
double rsquared = 0.0;
double adjRsquared = 0.0;
double fstatistic = 0.0;
int numdf = 0;
int dendf = 0;
// is there anything besides the intercept???
if ( terms.size() > 1 || !hasIntercept ) {
int dfint = hasIntercept ? 1 : 0;
rsquared = mss / ( mss + rss );
adjRsquared = 1 - ( 1 - rsquared * ( ( n - dfint ) / ( double ) rdf ) );
fstatistic = mss / ( p - dfint ) / resvar;
numdf = p - dfint;
dendf = rdf;
} else {
// intercept only, apparently.
rsquared = 0.0;
adjRsquared = 0.0;
}
LinearModelSummary lms = new LinearModelSummary( key, terms, ArrayUtils.toObject( this.residuals.viewRow( i )
.toArray() ), coeffMat, rsquared, adjRsquared, fstatistic, numdf, dendf, null );
return lms;
}
}
| change threshold for coefficients
| src/ubic/basecode/math/LeastSquaresFit.java | change threshold for coefficients | <ide><path>rc/ubic/basecode/math/LeastSquaresFit.java
<ide> * Accumulate the sum. When the data is "constant" you can end up with a tiny but non-zero coefficient,
<ide> * but it's bogus. See bug 3177.
<ide> */
<del> if ( !Double.isNaN( valueToAdd ) && valueToAdd > Constants.TINY ) {
<add> if ( !Double.isNaN( valueToAdd ) && valueToAdd > Constants.SMALL ) {
<ide> /*
<ide> * Is this always true?
<ide> */ |
|
Java | apache-2.0 | eafe63870c2d732a5b84dbf30b70ce4acca78b5f | 0 | apache/camel,christophd/camel,christophd/camel,cunningt/camel,apache/camel,apache/camel,christophd/camel,christophd/camel,apache/camel,tadayosi/camel,christophd/camel,tadayosi/camel,tadayosi/camel,cunningt/camel,tadayosi/camel,cunningt/camel,tadayosi/camel,cunningt/camel,christophd/camel,tadayosi/camel,cunningt/camel,apache/camel,apache/camel,cunningt/camel | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.jms;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TwoConsumerOnSameTopicTest extends AbstractPersistentJMSTest {
@Nested
class MultipleMessagesTest {
@Test
public void testMultipleMessagesOnSameTopic() throws Exception {
getMockEndpoint("mock:a").expectedBodiesReceived("Hello Camel 1", "Hello Camel 2", "Hello Camel 3",
"Hello Camel 4");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello Camel 1", "Hello Camel 2", "Hello Camel 3",
"Hello Camel 4");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 1");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 2");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 3");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 4");
assertMockEndpointsSatisfied();
}
}
@Nested
class SingleMessageTest {
@BeforeEach
void prepare() {
getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello World");
}
@Test
void testTwoConsumerOnSameTopic() throws Exception {
assertMockEndpointsSatisfied();
}
@Test
void testStopAndStartOneRoute() throws Exception {
assertMockEndpointsSatisfied();
// now stop route A
context.getRouteController().stopRoute("a");
// send new message should go to B only
resetMocks();
getMockEndpoint("mock:a").expectedMessageCount(0);
getMockEndpoint("mock:b").expectedBodiesReceived("Bye World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Bye World");
assertMockEndpointsSatisfied();
// send new message should go to both A and B
resetMocks();
// now start route A
context.getRouteController().startRoute("a");
getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello World");
}
@Test
void testRemoveOneRoute() throws Exception {
assertMockEndpointsSatisfied();
// now stop and remove route A
context.getRouteController().stopRoute("a");
assertTrue(context.removeRoute("a"));
// send new message should go to B only
resetMocks();
getMockEndpoint("mock:a").expectedMessageCount(0);
getMockEndpoint("mock:b").expectedBodiesReceived("Bye World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Bye World");
assertMockEndpointsSatisfied();
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("activemq:topic:TwoConsumerOnSameTopicTest").routeId("a")
.to("log:a", "mock:a");
from("activemq:topic:TwoConsumerOnSameTopicTest").routeId("b")
.to("log:b", "mock:b");
}
};
}
}
| components/camel-jms/src/test/java/org/apache/camel/component/jms/TwoConsumerOnSameTopicTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.jms;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TwoConsumerOnSameTopicTest extends AbstractPersistentJMSTest {
@Nested
class MultipleMessagesTest {
@Test
public void testMultipleMessagesOnSameTopic() throws Exception {
getMockEndpoint("mock:a").expectedBodiesReceived("Hello Camel 1", "Hello Camel 2", "Hello Camel 3",
"Hello Camel 4");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello Camel 1", "Hello Camel 2", "Hello Camel 3",
"Hello Camel 4");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 1");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 2");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 3");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello Camel 4");
assertMockEndpointsSatisfied();
}
}
@Nested
class SingleMessageTest {
@BeforeEach
void prepare() throws Exception {
getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello World");
}
@Test
void testTwoConsumerOnSameTopic() throws Exception {
assertMockEndpointsSatisfied();
}
@Test
void testStopAndStartOneRoute() throws Exception {
assertMockEndpointsSatisfied();
// now stop route A
context.getRouteController().stopRoute("a");
// send new message should go to B only
resetMocks();
getMockEndpoint("mock:a").expectedMessageCount(0);
getMockEndpoint("mock:b").expectedBodiesReceived("Bye World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Bye World");
assertMockEndpointsSatisfied();
// send new message should go to both A and B
resetMocks();
// now start route A
context.getRouteController().startRoute("a");
getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Hello World");
}
@Test
void testRemoveOneRoute() throws Exception {
assertMockEndpointsSatisfied();
// now stop and remove route A
context.getRouteController().stopRoute("a");
assertTrue(context.removeRoute("a"));
// send new message should go to B only
resetMocks();
getMockEndpoint("mock:a").expectedMessageCount(0);
getMockEndpoint("mock:b").expectedBodiesReceived("Bye World");
template.sendBody("activemq:topic:TwoConsumerOnSameTopicTest", "Bye World");
assertMockEndpointsSatisfied();
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("activemq:topic:TwoConsumerOnSameTopicTest").routeId("a")
.to("log:a", "mock:a");
from("activemq:topic:TwoConsumerOnSameTopicTest").routeId("b")
.to("log:b", "mock:b");
}
};
}
}
| (chores) camel-jms: remove an unused exception
| components/camel-jms/src/test/java/org/apache/camel/component/jms/TwoConsumerOnSameTopicTest.java | (chores) camel-jms: remove an unused exception | <ide><path>omponents/camel-jms/src/test/java/org/apache/camel/component/jms/TwoConsumerOnSameTopicTest.java
<ide> class SingleMessageTest {
<ide>
<ide> @BeforeEach
<del> void prepare() throws Exception {
<add> void prepare() {
<ide> getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
<ide> getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
<ide> |
|
JavaScript | mit | 7ed9279c5042b91512ee751584eb48117716a21d | 0 | ScottLogic/bitflux-openfin,owennw/OpenFinD3FC,ScottLogic/StockFlux,owennw/OpenFinD3FC,ScottLogic/bitflux-openfin,ScottLogic/StockFlux | import React, { useState, useEffect } from 'react';
import WatchlistCard from '../watchlist-card/WatchlistCard';
import Components from 'stockflux-components';
import { StockFluxHooks, OpenfinApiHelpers, Launchers } from 'stockflux-core';
import * as fdc3 from 'openfin-fdc3';
import {
useInterApplicationBusSubscribe,
useOptions
} from 'openfin-react-hooks';
import {
onDragStart,
onDragOver,
resetDragState,
onDrop
} from '../watchlist-card/WatchlistCard.Dragging';
import { useNotification } from 'openfin-react-hooks';
import './Watchlist.css';
let latestListener;
const NOTIFICATION_OPTIONS = {
cssUrl: './notification.css',
parentDocument: document,
shouldInheritCss: true
};
const getDistinctElementArray = array => [...new Set(array)];
const Watchlist = () => {
const [dragOverIndex, setDragOverIndex] = useState(null);
const [unwatchedSymbol, setUnwatchedSymbol] = useState(null);
const [displayPreview, setDisplayPreview] = useState(false);
const [newSymbol, setNewSymbol] = useState(null);
const [windowOptions, setWindowOptions] = useState(null);
const [previewDetails, setPreviewDetails] = useState({
position: { top: 0, left: 0 },
size: { height: 300, width: 300 }
});
const [watchlist, setWatchlist] = StockFluxHooks.useLocalStorage(
'watchlist',
['AAPL', 'AAP', 'CC', 'MS', 'JPS']
);
const WINDOW_OFFSET = 5;
const [options] = useOptions();
const notification = useNotification(NOTIFICATION_OPTIONS);
const displayNotification = newSymbol => {
setNewSymbol(newSymbol);
if (notification) {
notification.launch({
url: 'notification.html'
});
}
};
const addToWatchlist = symbol => {
setWatchlist(getDistinctElementArray([symbol, ...watchlist]));
displayNotification(symbol);
};
const { data } = useInterApplicationBusSubscribe(
{ uuid: options ? options.uuid : '*' },
'stockflux-watchlist'
);
useEffect(() => {
if (notification.state === 'LAUNCHED') {
const alreadyInWatchlist = watchlist.includes(newSymbol);
notification.populate(
<>
<div className="notification-icon">
<img
id="icon"
className={alreadyInWatchlist ? 'arrow-up' : 'card-icon'}
src={alreadyInWatchlist ? 'ArrowUp.png' : 'CardIcon.png'}
alt="Notification Icon"
/>
</div>
<div id="notification-content">
<p id="title">WATCHLIST UPDATED</p>
<hr />
<p id="info">
<span id="symbol">{newSymbol}</span>
<span id="message">{`${
alreadyInWatchlist ? ' moved' : ' added'
} to the top`}</span>
</p>
</div>
</>
);
}
});
useEffect(() => {
if (data && data.message) {
if (data.message.symbol) {
addToWatchlist(data.message.symbol);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
const onIconClick = symbol => {
return e => {
setUnwatchedSymbol(symbol);
e.preventDefault();
};
};
const onModalConfirmClick = symbol => {
setUnwatchedSymbol(null);
const symbolIndex = getSymbolIndex(symbol);
let tempwatchlist = [
...watchlist.slice(0, symbolIndex),
...watchlist.slice(symbolIndex + 1)
];
setWatchlist(tempwatchlist);
};
const onModalBackdropClick = e => {
setUnwatchedSymbol(null);
e.stopPropagation();
};
const getSymbolIndex = symbol => watchlist.indexOf(symbol);
const onDropOutside = (symbol, stockName) => {
if (windowOptions) {
/*Always recalculate where the target window should drop, for is the window has been moved. */
const dropPosition = {
left: calcLeftPosition(windowOptions.defaultWidth, WINDOW_OFFSET),
top: window.screenTop
};
Launchers.launchChart(symbol, stockName, dropPosition);
}
};
const bindings = {
onModalConfirmClick: onModalConfirmClick,
onModalBackdropClick: onModalBackdropClick,
onIconClick: onIconClick,
resetDragState: resetDragState,
onDropOutside: onDropOutside
};
/*
* This is a temorary solution for
* 1) not being able to unsubscribe intentListeners
* 2) not being able to addIntentListener in useEffect due to the race condition
* 3) being forced to create a new intentListener every render (memory leak)
* This works due to us manually using only the latest intentListener
*/
const currentListener = fdc3.addIntentListener('WatchlistAdd', context => {
if (context && currentListener === latestListener) {
const newSymbol = context.id.default;
setWatchlist(getDistinctElementArray([newSymbol, ...watchlist]));
displayNotification(newSymbol);
}
});
latestListener = currentListener;
const removeFromWatchList = symbol => {
setWatchlist(watchlist.filter(item => item !== symbol));
};
const getWindowOptions = async () => {
const targetApplication = await OpenfinApiHelpers.getStockFluxApp(
'stockflux-chart'
);
const manifestContents = await fetch(targetApplication.manifest, {
method: 'GET'
});
const info = await manifestContents.json();
return info.startup_app;
};
useEffect(() => {
getWindowOptions().then(value => {
setWindowOptions(value);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const screenLeft = () =>
window.screenLeft > 0
? window.screenLeft
: window.screen.availWidth + window.screenLeft;
const leftPosition = (targetWidth, offset) =>
window.screen.availWidth -
(window.outerWidth + screenLeft() + offset + targetWidth) >
0
? window.outerWidth + screenLeft() + offset
: screenLeft() - offset - targetWidth;
const calcLeftPosition = (targetWidth, offset) =>
leftPosition(targetWidth, offset) > window.screen.availLeft
? window.screenleft > 0
? leftPosition(targetWidth, offset)
: window.screen.availLeft + leftPosition(targetWidth, offset)
: window.outerWidth + screenLeft() + offset;
useEffect(() => {
if (windowOptions) {
setPreviewDetails({
...previewDetails,
position: {
left: calcLeftPosition(windowOptions.defaultWidth, WINDOW_OFFSET),
top: window.screenTop
},
size: {
height: windowOptions.defaultHeight,
width: windowOptions.defaultWidth
}
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [displayPreview, windowOptions]);
return (
<div
className="watchlist"
onDragStart={e => {
onDragStart(e, watchlist, setDragOverIndex);
setDisplayPreview(true);
}}
onDragOver={e => {
onDragOver(e, watchlist, dragOverIndex, setDragOverIndex);
}}
onDragEnd={() => {
setDisplayPreview(false);
resetDragState(setDragOverIndex);
}}
onDrop={e => {
setDisplayPreview(false);
onDrop(e, watchlist, getSymbolIndex, setWatchlist, dragOverIndex);
}}
>
<Components.PreviewWindow
windowName="chart-preview"
display={displayPreview}
htmlPath="preview-chart.html"
position={previewDetails.position}
size={previewDetails.size}
></Components.PreviewWindow>
<Components.ScrollWrapperY>
{watchlist.length === 0 ? (
<div className="no-watchlist">
<p>You have no stocks to display.</p>
<p>Use StockFlux Search app to add new stocks to the list.</p>
</div>
) : (
watchlist.map((symbol, i) => (
<WatchlistCard
key={symbol}
symbol={symbol}
bindings={bindings}
isUnwatching={unwatchedSymbol === symbol}
dragOver={dragOverIndex === i}
dragOverBottom={
dragOverIndex === watchlist.length && i === watchlist.length - 1
}
removeFromWatchList={removeFromWatchList}
/>
))
)}
</Components.ScrollWrapperY>
</div>
);
};
export default Watchlist;
| packages/stockflux-watchlist/src/components/watchlist/Watchlist.js | import React, { useState, useEffect } from 'react';
import WatchlistCard from '../watchlist-card/WatchlistCard';
import Components from 'stockflux-components';
import { StockFluxHooks, OpenfinApiHelpers, Launchers } from 'stockflux-core';
import * as fdc3 from 'openfin-fdc3';
import {
useInterApplicationBusSubscribe,
useOptions
} from 'openfin-react-hooks';
import {
onDragStart,
onDragOver,
resetDragState,
onDrop
} from '../watchlist-card/WatchlistCard.Dragging';
import { useNotification } from 'openfin-react-hooks';
import './Watchlist.css';
let latestListener;
const NOTIFICATION_OPTIONS = {
cssUrl: './notification.css',
parentDocument: document,
shouldInheritCss: true
};
const getDistinctElementArray = array => [...new Set(array)];
const Watchlist = () => {
const [dragOverIndex, setDragOverIndex] = useState(null);
const [unwatchedSymbol, setUnwatchedSymbol] = useState(null);
const [displayPreview, setDisplayPreview] = useState(false);
const [newSymbol, setNewSymbol] = useState(null);
const [windowOptions, setWindowOptions] = useState(null);
const [previewDetails, setPreviewDetails] = useState({
position: { top: 0, left: 0 },
size: { height: 300, width: 300 }
});
const [watchlist, setWatchlist] = StockFluxHooks.useLocalStorage(
'watchlist',
['AAPL', 'AAP', 'CC', 'MS', 'JPS']
);
const WINDOW_OFFSET = 5;
const [options] = useOptions();
const notification = useNotification(NOTIFICATION_OPTIONS);
const displayNotification = newSymbol => {
setNewSymbol(newSymbol);
if (notification) {
notification.launch({
url: 'notification.html',
timeout: 'never'
});
}
};
const addToWatchlist = symbol => {
setWatchlist(getDistinctElementArray([symbol, ...watchlist]));
displayNotification(symbol);
};
const { data } = useInterApplicationBusSubscribe(
{ uuid: options ? options.uuid : '*' },
'stockflux-watchlist'
);
useEffect(() => {
if (notification.state === 'LAUNCHED') {
const alreadyInWatchlist = watchlist.includes(newSymbol);
notification.populate(
<>
<div className="notification-icon">
<img
id="icon"
className={alreadyInWatchlist ? 'arrow-up' : 'card-icon'}
src={alreadyInWatchlist ? 'ArrowUp.png' : 'CardIcon.png'}
alt="Notification Icon"
/>
</div>
<div id="notification-content">
<p id="title">WATCHLIST UPDATED</p>
<hr />
<p id="info">
<span id="symbol">{newSymbol}</span>
<span id="message">{`${
alreadyInWatchlist ? ' moved' : ' added'
} to the top`}</span>
</p>
</div>
</>
);
}
});
useEffect(() => {
if (data && data.message) {
if (data.message.symbol) {
addToWatchlist(data.message.symbol);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
const onIconClick = symbol => {
return e => {
setUnwatchedSymbol(symbol);
e.preventDefault();
};
};
const onModalConfirmClick = symbol => {
setUnwatchedSymbol(null);
const symbolIndex = getSymbolIndex(symbol);
let tempwatchlist = [
...watchlist.slice(0, symbolIndex),
...watchlist.slice(symbolIndex + 1)
];
setWatchlist(tempwatchlist);
};
const onModalBackdropClick = e => {
setUnwatchedSymbol(null);
e.stopPropagation();
};
const getSymbolIndex = symbol => watchlist.indexOf(symbol);
const onDropOutside = (symbol, stockName) => {
if (windowOptions) {
/*Always recalculate where the target window should drop, for is the window has been moved. */
const dropPosition = {
left: calcLeftPosition(windowOptions.defaultWidth, WINDOW_OFFSET),
top: window.screenTop
};
Launchers.launchChart(symbol, stockName, dropPosition);
}
};
const bindings = {
onModalConfirmClick: onModalConfirmClick,
onModalBackdropClick: onModalBackdropClick,
onIconClick: onIconClick,
resetDragState: resetDragState,
onDropOutside: onDropOutside
};
/*
* This is a temorary solution for
* 1) not being able to unsubscribe intentListeners
* 2) not being able to addIntentListener in useEffect due to the race condition
* 3) being forced to create a new intentListener every render (memory leak)
* This works due to us manually using only the latest intentListener
*/
const currentListener = fdc3.addIntentListener('WatchlistAdd', context => {
if (context && currentListener === latestListener) {
const newSymbol = context.id.default;
setWatchlist(getDistinctElementArray([newSymbol, ...watchlist]));
displayNotification(newSymbol);
}
});
latestListener = currentListener;
const removeFromWatchList = symbol => {
setWatchlist(watchlist.filter(item => item !== symbol));
};
const getWindowOptions = async () => {
const targetApplication = await OpenfinApiHelpers.getStockFluxApp(
'stockflux-chart'
);
const manifestContents = await fetch(targetApplication.manifest, {
method: 'GET'
});
const info = await manifestContents.json();
return info.startup_app;
};
useEffect(() => {
getWindowOptions().then(value => {
setWindowOptions(value);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const screenLeft = () =>
window.screenLeft > 0
? window.screenLeft
: window.screen.availWidth + window.screenLeft;
const leftPosition = (targetWidth, offset) =>
window.screen.availWidth -
(window.outerWidth + screenLeft() + offset + targetWidth) >
0
? window.outerWidth + screenLeft() + offset
: screenLeft() - offset - targetWidth;
const calcLeftPosition = (targetWidth, offset) =>
leftPosition(targetWidth, offset) > window.screen.availLeft
? window.screenleft > 0
? leftPosition(targetWidth, offset)
: window.screen.availLeft + leftPosition(targetWidth, offset)
: window.outerWidth + screenLeft() + offset;
useEffect(() => {
if (windowOptions) {
setPreviewDetails({
...previewDetails,
position: {
left: calcLeftPosition(windowOptions.defaultWidth, WINDOW_OFFSET),
top: window.screenTop
},
size: {
height: windowOptions.defaultHeight,
width: windowOptions.defaultWidth
}
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [displayPreview, windowOptions]);
return (
<div
className="watchlist"
onDragStart={e => {
onDragStart(e, watchlist, setDragOverIndex);
setDisplayPreview(true);
}}
onDragOver={e => {
onDragOver(e, watchlist, dragOverIndex, setDragOverIndex);
}}
onDragEnd={() => {
setDisplayPreview(false);
resetDragState(setDragOverIndex);
}}
onDrop={e => {
setDisplayPreview(false);
onDrop(e, watchlist, getSymbolIndex, setWatchlist, dragOverIndex);
}}
>
<Components.PreviewWindow
windowName="chart-preview"
display={displayPreview}
htmlPath="preview-chart.html"
position={previewDetails.position}
size={previewDetails.size}
></Components.PreviewWindow>
<Components.ScrollWrapperY>
{watchlist.length === 0 ? (
<div className="no-watchlist">
<p>You have no stocks to display.</p>
<p>Use StockFlux Search app to add new stocks to the list.</p>
</div>
) : (
watchlist.map((symbol, i) => (
<WatchlistCard
key={symbol}
symbol={symbol}
bindings={bindings}
isUnwatching={unwatchedSymbol === symbol}
dragOver={dragOverIndex === i}
dragOverBottom={
dragOverIndex === watchlist.length && i === watchlist.length - 1
}
removeFromWatchList={removeFromWatchList}
/>
))
)}
</Components.ScrollWrapperY>
</div>
);
};
export default Watchlist;
| Remove timeout altogether
| packages/stockflux-watchlist/src/components/watchlist/Watchlist.js | Remove timeout altogether | <ide><path>ackages/stockflux-watchlist/src/components/watchlist/Watchlist.js
<ide> setNewSymbol(newSymbol);
<ide> if (notification) {
<ide> notification.launch({
<del> url: 'notification.html',
<del> timeout: 'never'
<add> url: 'notification.html'
<ide> });
<ide> }
<ide> }; |
|
Java | mit | b0446acea3860a0e8bb5ab81d509d28f024db42e | 0 | lipiji/tabula-java,redmyers/484_P7_1,mcharters/tabula-java,melisabok/tabula-java,tabulapdf/tabula-java,RavnSystems/tabula-java | package org.nerdpower.tabula;
import java.awt.Image;
import java.awt.Shape;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.apache.pdfbox.exceptions.CryptographyException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.encryption.BadSecurityHandlerException;
import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.apache.pdfbox.pdmodel.graphics.PDGraphicsState;
import org.apache.pdfbox.pdmodel.text.PDTextState;
import org.apache.pdfbox.util.TextPosition;
public class ObjectExtractor extends org.apache.pdfbox.pdfviewer.PageDrawer {
class PointComparator implements Comparator<Point2D> {
@Override
public int compare(Point2D o1, Point2D o2) {
float o1X = Utils.round(o1.getX(), 2);
float o1Y = Utils.round(o1.getY(), 2);
float o2X = Utils.round(o2.getX(), 2);
float o2Y = Utils.round(o2.getY(), 2);
if (o1Y > o2Y)
return 1;
if (o1Y < o2Y)
return -1;
if (o1X > o2X)
return 1;
if (o1X < o2X)
return -1;
return 0;
}
}
private static final char[] spaceLikeChars = { ' ', '-', '1', 'i' };
private static final String NBSP = "\u00A0";
private float minCharWidth = Float.MAX_VALUE,
minCharHeight = Float.MAX_VALUE;
private List<TextElement> characters;
private List<Ruling> rulings;
private RectangleSpatialIndex<TextElement> spatialIndex;
private AffineTransform pageTransform;
private Shape clippingPath;
public List<Shape> clippingPaths = new ArrayList<Shape>();
private boolean debugClippingPaths = false;
private Rectangle2D transformedClippingPathBounds;
private Shape transformedClippingPath;
private boolean extractRulingLines = true;
private final PDDocument pdf_document;
protected List pdf_document_pages;
public ObjectExtractor(PDDocument pdf_document) throws IOException {
this(pdf_document, null);
}
public ObjectExtractor(PDDocument pdf_document, String password)
throws IOException {
super();
// turns off PDFBox's logging, which we usually don't care about.
Logger.getLogger("org.apache.pdfbox").setLevel(Level.OFF);
if (pdf_document.isEncrypted()) {
try {
pdf_document
.openProtection(new StandardDecryptionMaterial(password));
} catch (BadSecurityHandlerException e) {
// TODO Auto-generated catch block
throw new IOException("BadSecurityHandler");
} catch (CryptographyException e) {
throw new IOException("Document is encrypted");
}
}
this.pdf_document = pdf_document;
this.pdf_document_pages = this.pdf_document.getDocumentCatalog()
.getAllPages();
}
protected Page extractPage(Integer page_number) throws IOException {
if (page_number - 1 > this.pdf_document_pages.size() || page_number < 1) {
throw new java.lang.IndexOutOfBoundsException(
"Page number does not exist");
}
PDPage p = (PDPage) this.pdf_document_pages.get(page_number - 1);
PDStream contents = p.getContents();
if (contents == null) {
return null;
}
this.clear();
this.drawPage(p);
Utils.sort(this.characters);
float w, h;
int pageRotation = p.findRotation();
if (Math.abs(pageRotation) == 90 || Math.abs(pageRotation) == 270) {
w = p.findCropBox().getHeight();
h = p.findCropBox().getWidth();
}
else {
w = p.findCropBox().getWidth();
h = p.findCropBox().getHeight();
}
return new Page(0, 0, w, h, pageRotation, page_number, this.characters,
this.getRulings(), this.minCharWidth, this.minCharHeight,
this.spatialIndex);
}
public PageIterator extract(Iterable<Integer> pages) {
return new PageIterator(this, pages);
}
public PageIterator extract() {
return extract(Utils.range(1, this.pdf_document_pages.size() + 1));
}
public Page extract(int pageNumber) {
return extract(Utils.range(pageNumber, pageNumber + 1)).next();
}
public void close() throws IOException {
this.pdf_document.close();
}
public void drawPage(PDPage p) throws IOException {
page = p;
PDStream contents = p.getContents();
if (contents != null) {
ensurePageSize();
this.processStream(p, p.findResources(), contents.getStream());
}
}
private void ensurePageSize() {
if (this.pageSize == null && this.page != null) {
PDRectangle cropBox = this.page.findCropBox();
this.pageSize = cropBox == null ? null : cropBox
.createDimension();
}
}
private void clear() {
this.characters = new ArrayList<TextElement>();
this.rulings = new ArrayList<Ruling>();
this.pageTransform = null;
this.spatialIndex = new RectangleSpatialIndex<TextElement>();
this.minCharWidth = Float.MAX_VALUE;
this.minCharHeight = Float.MAX_VALUE;
}
@Override
public void drawImage(Image awtImage, AffineTransform at) {
// we just ignore images (for now)
}
public void strokeOrFillPath(boolean isFill) {
GeneralPath path = this.getLinePath();
if (!this.extractRulingLines) {
this.getLinePath().reset();
return;
}
PathIterator pi = path.getPathIterator(this.getPageTransform());
float[] c = new float[6];
int currentSegment;
// skip paths whose first operation is not a MOVETO
// or contains operations other than LINETO, MOVETO or CLOSE
if ((pi.currentSegment(c) != PathIterator.SEG_MOVETO)) {
path.reset();
return;
}
pi.next();
while (!pi.isDone()) {
currentSegment = pi.currentSegment(c);
if (currentSegment != PathIterator.SEG_LINETO
&& currentSegment != PathIterator.SEG_CLOSE
&& currentSegment != PathIterator.SEG_MOVETO) {
path.reset();
return;
}
pi.next();
}
// TODO: how to implement color filter?
// skip the first path operation and save it as the starting position
float[] first = new float[6];
pi = path.getPathIterator(this.getPageTransform());
pi.currentSegment(first);
// last move
Point2D.Float start_pos = new Point2D.Float(Utils.round(first[0], 2), Utils.round(first[1], 2));
Point2D.Float last_move = start_pos;
Point2D.Float end_pos = null;
Line2D.Float line;
PointComparator pc = new PointComparator();
while (!pi.isDone()) {
pi.next();
currentSegment = pi.currentSegment(c);
switch (currentSegment) {
case PathIterator.SEG_LINETO:
end_pos = new Point2D.Float(c[0], c[1]);
line = pc.compare(start_pos, end_pos) == -1 ? new Line2D.Float(
start_pos, end_pos) : new Line2D.Float(end_pos,
start_pos);
if (line.intersects(this.currentClippingPath())) {
Ruling r = new Ruling(line.getP1(), line.getP2())
.intersect(this.currentClippingPath());
if (r.length() > 0.01) {
this.rulings.add(r);
}
}
break;
case PathIterator.SEG_MOVETO:
last_move = new Point2D.Float(c[0], c[1]);
end_pos = last_move;
break;
case PathIterator.SEG_CLOSE:
// according to PathIterator docs:
// "the preceding subpath should be closed by appending a line
// segment
// back to the point corresponding to the most recent
// SEG_MOVETO."
line = pc.compare(end_pos, last_move) == -1 ? new Line2D.Float(
end_pos, last_move) : new Line2D.Float(last_move,
end_pos);
if (line.intersects(this.currentClippingPath())) {
Ruling r = new Ruling(line.getP1(), line.getP2())
.intersect(this.currentClippingPath());
if (r.length() > 0.01) {
this.rulings.add(r);
}
}
break;
}
start_pos = end_pos;
}
path.reset();
}
@Override
public void strokePath() throws IOException {
this.strokeOrFillPath(false);
}
@Override
public void fillPath(int windingRule) throws IOException {
//
// float[] color_comps =
// this.getGraphicsState().getNonStrokingColor().getJavaColor().getRGBColorComponents(null);
float[] color = this.getGraphicsState().getNonStrokingColor().getJavaColor().getComponents(null);
// TODO use color_comps as filter_by_color
this.strokeOrFillPath(true);
}
private float currentSpaceWidth() {
PDGraphicsState gs = this.getGraphicsState();
PDTextState ts = gs.getTextState();
PDFont font = ts.getFont();
float fontSizeText = ts.getFontSize();
float horizontalScalingText = ts.getHorizontalScalingPercent() / 100.0f;
float spaceWidthText = 1000;
if (font instanceof PDType3Font) {
// TODO WHAT?
}
for (int i = 0; i < spaceLikeChars.length; i++) {
spaceWidthText = font.getFontWidth(spaceLikeChars[i]);
if (spaceWidthText > 0)
break;
}
float ctm00 = gs.getCurrentTransformationMatrix().getValue(0, 0);
return (float) ((spaceWidthText / 1000.0) * fontSizeText
* horizontalScalingText * (ctm00 == 0 ? 1 : ctm00));
}
@Override
protected void processTextPosition(TextPosition textPosition) {
String c = textPosition.getCharacter();
// if c not printable, return
if (!isPrintable(c)) {
return;
}
Float h = textPosition.getHeightDir();
if (c.equals(NBSP)) { // replace non-breaking space for space
c = " ";
}
float wos = textPosition.getWidthOfSpace();
TextElement te = new TextElement(
Utils.round(textPosition.getYDirAdj() - h, 2),
Utils.round(textPosition.getXDirAdj(), 2),
Utils.round(textPosition.getWidthDirAdj(), 2),
Utils.round(textPosition.getHeightDir(), 2),
textPosition.getFont(),
textPosition.getFontSize(),
c,
// workaround a possible bug in PDFBox:
// https://issues.apache.org/jira/browse/PDFBOX-1755
(Float.isNaN(wos) || wos == 0) ? this.currentSpaceWidth() : wos,
textPosition.getDir());
if (this.currentClippingPath().intersects(te)) {
this.minCharWidth = (float) Math.min(this.minCharWidth, te.getWidth());
this.minCharHeight = (float) Math.min(this.minCharHeight, te.getHeight());
this.spatialIndex.add(te);
this.characters.add(te);
}
if (this.isDebugClippingPaths() && !this.clippingPaths.contains(this.currentClippingPath())) {
this.clippingPaths.add(this.currentClippingPath());
}
}
public float getMinCharWidth() {
return minCharWidth;
}
public float getMinCharHeight() {
return minCharHeight;
}
public AffineTransform getPageTransform() {
if (this.pageTransform != null) {
return this.pageTransform;
}
PDRectangle cb = page.findCropBox();
int rotation = Math.abs(page.findRotation());
this.pageTransform = new AffineTransform();
if (rotation == 90 || rotation == 270) {
this.pageTransform = AffineTransform.getRotateInstance(rotation * (Math.PI / 180.0), 0, 0);
this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
this.pageTransform.concatenate(AffineTransform.getTranslateInstance(0, cb.getHeight()));
this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
}
return this.pageTransform;
}
//public Rectangle2D currentClippingPath() {
public Rectangle2D currentClippingPath() {
// Shape cp = this.getGraphicsState().getCurrentClippingPath();
// if (cp == this.clippingPath) {
// return this.transformedClippingPathBounds;
// }
this.clippingPath = this.getGraphicsState().getCurrentClippingPath();
this.transformedClippingPath = this.getPageTransform()
.createTransformedShape(this.clippingPath);
this.transformedClippingPathBounds = this.transformedClippingPath
.getBounds2D();
return this.transformedClippingPathBounds;
}
public boolean isExtractRulingLines() {
return extractRulingLines;
}
public void setExtractRulingLines(boolean extractRulingLines) {
this.extractRulingLines = extractRulingLines;
}
public List<Ruling> getRulings() {
return rulings;
}
public List<TextElement> getCharacters() {
return characters;
}
private static boolean isPrintable(String s) {
Character c = s.charAt(0);
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
return (!Character.isISOControl(c)) && c != KeyEvent.CHAR_UNDEFINED
&& block != null && block != Character.UnicodeBlock.SPECIALS;
}
public boolean isDebugClippingPaths() {
return debugClippingPaths;
}
public void setDebugClippingPaths(boolean debugClippingPaths) {
this.debugClippingPaths = debugClippingPaths;
}
public int getPageCount() {
return this.pdf_document_pages.size();
}
}
| src/main/java/org/nerdpower/tabula/ObjectExtractor.java | package org.nerdpower.tabula;
import java.awt.Image;
import java.awt.Shape;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.apache.pdfbox.exceptions.CryptographyException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.encryption.BadSecurityHandlerException;
import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.apache.pdfbox.pdmodel.graphics.PDGraphicsState;
import org.apache.pdfbox.pdmodel.text.PDTextState;
import org.apache.pdfbox.util.TextPosition;
public class ObjectExtractor extends org.apache.pdfbox.pdfviewer.PageDrawer {
class PointComparator implements Comparator<Point2D> {
@Override
public int compare(Point2D o1, Point2D o2) {
float o1X = Utils.round(o1.getX(), 2);
float o1Y = Utils.round(o1.getY(), 2);
float o2X = Utils.round(o2.getX(), 2);
float o2Y = Utils.round(o2.getY(), 2);
if (o1Y > o2Y)
return 1;
if (o1Y < o2Y)
return -1;
if (o1X > o2X)
return 1;
if (o1X < o2X)
return -1;
return 0;
}
}
private static final char[] spaceLikeChars = { ' ', '-', '1', 'i' };
private static final String NBSP = "\u00A0";
private float minCharWidth = Float.MAX_VALUE,
minCharHeight = Float.MAX_VALUE;
private List<TextElement> characters;
private List<Ruling> rulings;
private RectangleSpatialIndex<TextElement> spatialIndex;
private AffineTransform pageTransform;
private Shape clippingPath;
public List<Shape> clippingPaths = new ArrayList<Shape>();
private boolean debugClippingPaths = false;
private Rectangle2D transformedClippingPathBounds;
private Shape transformedClippingPath;
private boolean extractRulingLines = true;
private final PDDocument pdf_document;
protected List pdf_document_pages;
public ObjectExtractor(PDDocument pdf_document) throws IOException {
this(pdf_document, null);
}
public ObjectExtractor(PDDocument pdf_document, String password)
throws IOException {
super();
if (pdf_document.isEncrypted()) {
try {
pdf_document
.openProtection(new StandardDecryptionMaterial(password));
} catch (BadSecurityHandlerException e) {
// TODO Auto-generated catch block
throw new IOException("BadSecurityHandler");
} catch (CryptographyException e) {
throw new IOException("Document is encrypted");
}
}
this.pdf_document = pdf_document;
this.pdf_document_pages = this.pdf_document.getDocumentCatalog()
.getAllPages();
}
protected Page extractPage(Integer page_number) throws IOException {
if (page_number - 1 > this.pdf_document_pages.size() || page_number < 1) {
throw new java.lang.IndexOutOfBoundsException(
"Page number does not exist");
}
PDPage p = (PDPage) this.pdf_document_pages.get(page_number - 1);
PDStream contents = p.getContents();
if (contents == null) {
return null;
}
this.clear();
this.drawPage(p);
Utils.sort(this.characters);
float w, h;
int pageRotation = p.findRotation();
if (Math.abs(pageRotation) == 90 || Math.abs(pageRotation) == 270) {
w = p.findCropBox().getHeight();
h = p.findCropBox().getWidth();
}
else {
w = p.findCropBox().getWidth();
h = p.findCropBox().getHeight();
}
return new Page(0, 0, w, h, pageRotation, page_number, this.characters,
this.getRulings(), this.minCharWidth, this.minCharHeight,
this.spatialIndex);
}
public PageIterator extract(Iterable<Integer> pages) {
return new PageIterator(this, pages);
}
public PageIterator extract() {
return extract(Utils.range(1, this.pdf_document_pages.size() + 1));
}
public Page extract(int pageNumber) {
return extract(Utils.range(pageNumber, pageNumber + 1)).next();
}
public void close() throws IOException {
this.pdf_document.close();
}
public void drawPage(PDPage p) throws IOException {
page = p;
PDStream contents = p.getContents();
if (contents != null) {
ensurePageSize();
this.processStream(p, p.findResources(), contents.getStream());
}
}
private void ensurePageSize() {
if (this.pageSize == null && this.page != null) {
PDRectangle cropBox = this.page.findCropBox();
this.pageSize = cropBox == null ? null : cropBox
.createDimension();
}
}
private void clear() {
this.characters = new ArrayList<TextElement>();
this.rulings = new ArrayList<Ruling>();
this.pageTransform = null;
this.spatialIndex = new RectangleSpatialIndex<TextElement>();
this.minCharWidth = Float.MAX_VALUE;
this.minCharHeight = Float.MAX_VALUE;
}
@Override
public void drawImage(Image awtImage, AffineTransform at) {
// we just ignore images (for now)
}
public void strokeOrFillPath(boolean isFill) {
GeneralPath path = this.getLinePath();
if (!this.extractRulingLines) {
this.getLinePath().reset();
return;
}
PathIterator pi = path.getPathIterator(this.getPageTransform());
float[] c = new float[6];
int currentSegment;
// skip paths whose first operation is not a MOVETO
// or contains operations other than LINETO, MOVETO or CLOSE
if ((pi.currentSegment(c) != PathIterator.SEG_MOVETO)) {
path.reset();
return;
}
pi.next();
while (!pi.isDone()) {
currentSegment = pi.currentSegment(c);
if (currentSegment != PathIterator.SEG_LINETO
&& currentSegment != PathIterator.SEG_CLOSE
&& currentSegment != PathIterator.SEG_MOVETO) {
path.reset();
return;
}
pi.next();
}
// TODO: how to implement color filter?
// skip the first path operation and save it as the starting position
float[] first = new float[6];
pi = path.getPathIterator(this.getPageTransform());
pi.currentSegment(first);
// last move
Point2D.Float start_pos = new Point2D.Float(Utils.round(first[0], 2), Utils.round(first[1], 2));
Point2D.Float last_move = start_pos;
Point2D.Float end_pos = null;
Line2D.Float line;
PointComparator pc = new PointComparator();
while (!pi.isDone()) {
pi.next();
currentSegment = pi.currentSegment(c);
switch (currentSegment) {
case PathIterator.SEG_LINETO:
end_pos = new Point2D.Float(c[0], c[1]);
line = pc.compare(start_pos, end_pos) == -1 ? new Line2D.Float(
start_pos, end_pos) : new Line2D.Float(end_pos,
start_pos);
if (line.intersects(this.currentClippingPath())) {
Ruling r = new Ruling(line.getP1(), line.getP2())
.intersect(this.currentClippingPath());
if (r.length() > 0.01) {
this.rulings.add(r);
}
}
break;
case PathIterator.SEG_MOVETO:
last_move = new Point2D.Float(c[0], c[1]);
end_pos = last_move;
break;
case PathIterator.SEG_CLOSE:
// according to PathIterator docs:
// "the preceding subpath should be closed by appending a line
// segment
// back to the point corresponding to the most recent
// SEG_MOVETO."
line = pc.compare(end_pos, last_move) == -1 ? new Line2D.Float(
end_pos, last_move) : new Line2D.Float(last_move,
end_pos);
if (line.intersects(this.currentClippingPath())) {
Ruling r = new Ruling(line.getP1(), line.getP2())
.intersect(this.currentClippingPath());
if (r.length() > 0.01) {
this.rulings.add(r);
}
}
break;
}
start_pos = end_pos;
}
path.reset();
}
@Override
public void strokePath() throws IOException {
this.strokeOrFillPath(false);
}
@Override
public void fillPath(int windingRule) throws IOException {
//
// float[] color_comps =
// this.getGraphicsState().getNonStrokingColor().getJavaColor().getRGBColorComponents(null);
float[] color = this.getGraphicsState().getNonStrokingColor().getJavaColor().getComponents(null);
// TODO use color_comps as filter_by_color
this.strokeOrFillPath(true);
}
private float currentSpaceWidth() {
PDGraphicsState gs = this.getGraphicsState();
PDTextState ts = gs.getTextState();
PDFont font = ts.getFont();
float fontSizeText = ts.getFontSize();
float horizontalScalingText = ts.getHorizontalScalingPercent() / 100.0f;
float spaceWidthText = 1000;
if (font instanceof PDType3Font) {
// TODO WHAT?
}
for (int i = 0; i < spaceLikeChars.length; i++) {
spaceWidthText = font.getFontWidth(spaceLikeChars[i]);
if (spaceWidthText > 0)
break;
}
float ctm00 = gs.getCurrentTransformationMatrix().getValue(0, 0);
return (float) ((spaceWidthText / 1000.0) * fontSizeText
* horizontalScalingText * (ctm00 == 0 ? 1 : ctm00));
}
@Override
protected void processTextPosition(TextPosition textPosition) {
String c = textPosition.getCharacter();
// if c not printable, return
if (!isPrintable(c)) {
return;
}
Float h = textPosition.getHeightDir();
if (c.equals(NBSP)) { // replace non-breaking space for space
c = " ";
}
float wos = textPosition.getWidthOfSpace();
TextElement te = new TextElement(
Utils.round(textPosition.getYDirAdj() - h, 2),
Utils.round(textPosition.getXDirAdj(), 2),
Utils.round(textPosition.getWidthDirAdj(), 2),
Utils.round(textPosition.getHeightDir(), 2),
textPosition.getFont(),
textPosition.getFontSize(),
c,
// workaround a possible bug in PDFBox:
// https://issues.apache.org/jira/browse/PDFBOX-1755
(Float.isNaN(wos) || wos == 0) ? this.currentSpaceWidth() : wos,
textPosition.getDir());
if (this.currentClippingPath().intersects(te)) {
this.minCharWidth = (float) Math.min(this.minCharWidth, te.getWidth());
this.minCharHeight = (float) Math.min(this.minCharHeight, te.getHeight());
this.spatialIndex.add(te);
this.characters.add(te);
}
if (this.isDebugClippingPaths() && !this.clippingPaths.contains(this.currentClippingPath())) {
this.clippingPaths.add(this.currentClippingPath());
}
}
public float getMinCharWidth() {
return minCharWidth;
}
public float getMinCharHeight() {
return minCharHeight;
}
public AffineTransform getPageTransform() {
if (this.pageTransform != null) {
return this.pageTransform;
}
PDRectangle cb = page.findCropBox();
int rotation = Math.abs(page.findRotation());
this.pageTransform = new AffineTransform();
if (rotation == 90 || rotation == 270) {
this.pageTransform = AffineTransform.getRotateInstance(rotation * (Math.PI / 180.0), 0, 0);
this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
this.pageTransform.concatenate(AffineTransform.getTranslateInstance(0, cb.getHeight()));
this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
}
return this.pageTransform;
}
//public Rectangle2D currentClippingPath() {
public Rectangle2D currentClippingPath() {
// Shape cp = this.getGraphicsState().getCurrentClippingPath();
// if (cp == this.clippingPath) {
// return this.transformedClippingPathBounds;
// }
this.clippingPath = this.getGraphicsState().getCurrentClippingPath();
this.transformedClippingPath = this.getPageTransform()
.createTransformedShape(this.clippingPath);
this.transformedClippingPathBounds = this.transformedClippingPath
.getBounds2D();
return this.transformedClippingPathBounds;
}
public boolean isExtractRulingLines() {
return extractRulingLines;
}
public void setExtractRulingLines(boolean extractRulingLines) {
this.extractRulingLines = extractRulingLines;
}
public List<Ruling> getRulings() {
return rulings;
}
public List<TextElement> getCharacters() {
return characters;
}
private static boolean isPrintable(String s) {
Character c = s.charAt(0);
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
return (!Character.isISOControl(c)) && c != KeyEvent.CHAR_UNDEFINED
&& block != null && block != Character.UnicodeBlock.SPECIALS;
}
public boolean isDebugClippingPaths() {
return debugClippingPaths;
}
public void setDebugClippingPaths(boolean debugClippingPaths) {
this.debugClippingPaths = debugClippingPaths;
}
public int getPageCount() {
return this.pdf_document_pages.size();
}
}
| turns off PDFBox logging, closes #16
| src/main/java/org/nerdpower/tabula/ObjectExtractor.java | turns off PDFBox logging, closes #16 | <ide><path>rc/main/java/org/nerdpower/tabula/ObjectExtractor.java
<ide> import java.util.ArrayList;
<ide> import java.util.Comparator;
<ide> import java.util.List;
<add>import java.util.logging.Logger;
<add>import java.util.logging.Level;
<ide>
<ide> import org.apache.pdfbox.exceptions.CryptographyException;
<ide> import org.apache.pdfbox.pdmodel.PDDocument;
<ide> public ObjectExtractor(PDDocument pdf_document, String password)
<ide> throws IOException {
<ide> super();
<add>
<add> // turns off PDFBox's logging, which we usually don't care about.
<add> Logger.getLogger("org.apache.pdfbox").setLevel(Level.OFF);
<add>
<ide> if (pdf_document.isEncrypted()) {
<ide> try {
<ide> pdf_document |
|
Java | apache-2.0 | f3be08e68e62a843f5b5eacf3ec51a6ca50861c4 | 0 | jenkinsci/codedx-plugin,jenkinsci/codedx-plugin | package com.secdec.codedx.security;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class JenkinsSSLConnectionSocketFactoryFactory {
public static SSLConnectionSocketFactory getFactory(String fingerprint, String host) throws GeneralSecurityException {
// set up the certificate management
ExtraCertManager certManager = new SingleCertManager("floopydoop");
// get the default hostname verifier that gets used by the modified one
// and the invalid cert dialog
X509HostnameVerifier defaultHostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
// invalid cert strat that pops up a dialog asking the user if they want
// to accept the cert
FingerprintStrategy certificateStrategy = new FingerprintStrategy(fingerprint);
/*
* Set up a composite trust manager that uses the default trust manager
* before delegating to the "reloadable" trust manager that allows users
* to accept invalid certificates.
*/
List<X509TrustManager> trustManagersForComposite = new LinkedList<X509TrustManager>();
X509TrustManager systemTrustManager = getDefaultTrustManager();
ReloadableX509TrustManager customTrustManager = new ReloadableX509TrustManager(certManager, certificateStrategy);
trustManagersForComposite.add(systemTrustManager);
trustManagersForComposite.add(customTrustManager);
X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite);
// setup the SSLContext using the custom trust manager
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[] { trustManager }, null);
// the actual hostname verifier that will be used with the socket
// factory
Set<String> allowedHosts = new HashSet<String>();
allowedHosts.add(host);
X509HostnameVerifier modifiedHostnameVerifier = new X509HostnameVerifierWithExceptions(defaultHostnameVerifier, allowedHosts);
return new SSLConnectionSocketFactory(sslContext, modifiedHostnameVerifier);
}
private static X509TrustManager getDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory defaultFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
defaultFactory.init((KeyStore) null);
TrustManager[] managers = defaultFactory.getTrustManagers();
for (TrustManager mgr : managers) {
if (mgr instanceof X509TrustManager) {
return (X509TrustManager) mgr;
}
}
return null;
}
}
| src/main/java/com/secdec/codedx/security/JenkinsSSLConnectionSocketFactoryFactory.java | package com.secdec.codedx.security;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class JenkinsSSLConnectionSocketFactoryFactory {
public static SSLConnectionSocketFactory getFactory(String fingerprint, String host) throws GeneralSecurityException {
// set up the certificate management
ExtraCertManager certManager = new SingleCertManager("floopydoop");
// get the default hostname verifier that gets used by the modified one
// and the invalid cert dialog
X509HostnameVerifier defaultHostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
// invalid cert strat that pops up a dialog asking the user if they want
// to accept the cert
FingerprintStrategy certificateStrategy = new FingerprintStrategy(fingerprint);
/*
* Set up a composite trust manager that uses the default trust manager
* before delegating to the "reloadable" trust manager that allows users
* to accept invalid certificates.
*/
List<X509TrustManager> trustManagersForComposite = new LinkedList<X509TrustManager>();
X509TrustManager systemTrustManager = getDefaultTrustManager();
ReloadableX509TrustManager customTrustManager = new ReloadableX509TrustManager(certManager, certificateStrategy);
trustManagersForComposite.add(systemTrustManager);
trustManagersForComposite.add(customTrustManager);
X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite);
// setup the SSLContext using the custom trust manager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
// the actual hostname verifier that will be used with the socket
// factory
Set<String> allowedHosts = new HashSet<String>();
allowedHosts.add(host);
X509HostnameVerifier modifiedHostnameVerifier = new X509HostnameVerifierWithExceptions(defaultHostnameVerifier, allowedHosts);
return new SSLConnectionSocketFactory(sslContext, modifiedHostnameVerifier);
}
private static X509TrustManager getDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory defaultFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
defaultFactory.init((KeyStore) null);
TrustManager[] managers = defaultFactory.getTrustManagers();
for (TrustManager mgr : managers) {
if (mgr instanceof X509TrustManager) {
return (X509TrustManager) mgr;
}
}
return null;
}
}
| Add support for more advanced TLS
Unless the later version is specified, it apparently defaults to TLSv1, which is no longer considered secure, even if the JVM is run with TLSv1.1 or TLSv1.2 enabled. Users will still need to enable TLSv1.2 (or TLSv1.1) explicitly for the JVM running Jenkins for this functionality to take effect, at least for Java7.
| src/main/java/com/secdec/codedx/security/JenkinsSSLConnectionSocketFactoryFactory.java | Add support for more advanced TLS | <ide><path>rc/main/java/com/secdec/codedx/security/JenkinsSSLConnectionSocketFactoryFactory.java
<ide> X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite);
<ide>
<ide> // setup the SSLContext using the custom trust manager
<del> SSLContext sslContext = SSLContext.getInstance("TLS");
<add> SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
<ide> sslContext.init(null, new TrustManager[] { trustManager }, null);
<ide>
<ide> // the actual hostname verifier that will be used with the socket |
|
Java | lgpl-2.1 | d8a58cb033cc58277d7a4ebf0225f5325d9b6f5c | 0 | aruanruan/hivedb,britt/hivedb | package org.hivedb.util.database;
import java.sql.DriverManager;
import java.util.Arrays;
import java.util.Collection;
import org.hivedb.util.functional.Transform;
import org.hivedb.util.functional.Unary;
import org.testng.annotations.BeforeMethod;
public class MysqlTestCase {
protected boolean recycleDatabase = true;
// Data nodes are inserted in the hive's node_metadata table. The databases
// are never actually created,
// since the hive never interacts directly with the data nodes.
protected String[] dataNodes = new String[] { "data1", "data2", "data3" };
public Collection<String> getDataUris() {
return Transform.map(new Unary<String, String>() {
public String f(String dataNodeName) {
return getDataNodeConnectString(dataNodeName);
}
}, Arrays.asList(dataNodes));
}
@BeforeMethod
public void setUp() {
recycleDatabase();
}
protected String getDataNodeConnectString(String name) {
return String.format(
"jdbc:mysql://localhost/%s?user=test&password=test", name);
}
protected String getDatabaseName() {
return "test";
}
protected void recycleDatabase() {
recycleDatabase(getDatabaseName());
}
protected void recycleDatabase(String databaseName) {
if (recycleDatabase) {
java.sql.Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
.getConnection(getDatabaseAgnosticConnectString());
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
connection.prepareStatement("drop database " + databaseName)
.execute();
} catch (Exception e) {
throw new RuntimeException("Unable to drop database "
+ databaseName, e);
}
try {
connection.prepareStatement("create database " + databaseName)
.execute();
connection.close();
} catch (Exception e) {
throw new RuntimeException("Unable to drop database "
+ databaseName, e);
}
}
}
protected String getDatabaseAgnosticConnectString() {
return "jdbc:mysql://localhost/?user=test&password=test";
}
protected String getConnectString() {
return "jdbc:mysql://localhost/" + getDatabaseName()
+ "?user=test&password=test";
}
}
| src/main/java/org/hivedb/util/database/MysqlTestCase.java | package org.hivedb.util.database;
import java.sql.DriverManager;
import java.util.Arrays;
import java.util.Collection;
import org.hivedb.util.functional.Transform;
import org.hivedb.util.functional.Unary;
import org.testng.annotations.BeforeMethod;
public class MysqlTestCase {
// Data nodes are inserted in the hive's node_metadata table. The databases are never actually created,
// since the hive never interacts directly with the data nodes.
protected String[] dataNodes = new String[] { "data1", "data2", "data3" };
public Collection<String> getDataUris() {
return Transform.map(new Unary<String, String>() {
public String f(String dataNodeName) {
return getDataNodeConnectString(dataNodeName);
}},
Arrays.asList(dataNodes));
}
@BeforeMethod
public void setUp() {
recycleDatabase();
}
private String getDataNodeConnectString(String name){
return String.format("jdbc:mysql://localhost/%s?user=test&password=test",name);
}
protected String getDatabaseName() {
return "test";
}
protected void recycleDatabase() {
recycleDatabase(getDatabaseName());
}
protected void recycleDatabase(String databaseName) {
java.sql.Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection( getDatabaseAgnosticConnectString() );
}
catch (Exception e) {
throw new RuntimeException(e);
}
try {
connection.prepareStatement("drop database " + databaseName).execute();
}
catch (Exception e) {
throw new RuntimeException("Unable to drop database " + databaseName,e);
}
try{
connection.prepareStatement("create database " + databaseName).execute();
connection.close();
}
catch (Exception e) {
throw new RuntimeException("Unable to drop database " + databaseName,e);
}
}
protected String getDatabaseAgnosticConnectString() {
return "jdbc:mysql://localhost/?user=test&password=test";
}
protected String getConnectString() {
return "jdbc:mysql://localhost/"+getDatabaseName()+"?user=test&password=test";
}
}
|
git-svn-id: svn+ssh://svn.hivedb.org/svn/hivedb/trunk@298 8f33570f-f526-0410-8023-93ba2dbcbd24
| src/main/java/org/hivedb/util/database/MysqlTestCase.java | <ide><path>rc/main/java/org/hivedb/util/database/MysqlTestCase.java
<ide> import org.testng.annotations.BeforeMethod;
<ide>
<ide> public class MysqlTestCase {
<del>
<del> // Data nodes are inserted in the hive's node_metadata table. The databases are never actually created,
<add> protected boolean recycleDatabase = true;
<add>
<add> // Data nodes are inserted in the hive's node_metadata table. The databases
<add> // are never actually created,
<ide> // since the hive never interacts directly with the data nodes.
<del> protected String[] dataNodes = new String[] { "data1", "data2", "data3" };
<del>
<add> protected String[] dataNodes = new String[] { "data1", "data2", "data3" };
<add>
<ide> public Collection<String> getDataUris() {
<ide> return Transform.map(new Unary<String, String>() {
<del> public String f(String dataNodeName) {
<del> return getDataNodeConnectString(dataNodeName);
<del> }},
<del> Arrays.asList(dataNodes));
<add> public String f(String dataNodeName) {
<add> return getDataNodeConnectString(dataNodeName);
<add> }
<add> }, Arrays.asList(dataNodes));
<ide> }
<ide>
<ide> @BeforeMethod
<ide> public void setUp() {
<ide> recycleDatabase();
<ide> }
<del>
<del> private String getDataNodeConnectString(String name){
<del> return String.format("jdbc:mysql://localhost/%s?user=test&password=test",name);
<add>
<add> protected String getDataNodeConnectString(String name) {
<add> return String.format(
<add> "jdbc:mysql://localhost/%s?user=test&password=test", name);
<ide> }
<del>
<add>
<ide> protected String getDatabaseName() {
<ide> return "test";
<ide> }
<del>
<add>
<ide> protected void recycleDatabase() {
<ide> recycleDatabase(getDatabaseName());
<ide> }
<del>
<add>
<ide> protected void recycleDatabase(String databaseName) {
<del>
<del> java.sql.Connection connection = null;
<del> try {
<del> Class.forName("com.mysql.jdbc.Driver");
<del> connection = DriverManager.getConnection( getDatabaseAgnosticConnectString() );
<del> }
<del> catch (Exception e) {
<del> throw new RuntimeException(e);
<del> }
<del> try {
<del> connection.prepareStatement("drop database " + databaseName).execute();
<del> }
<del> catch (Exception e) {
<del> throw new RuntimeException("Unable to drop database " + databaseName,e);
<del> }
<del> try{
<del> connection.prepareStatement("create database " + databaseName).execute();
<del> connection.close();
<del> }
<del> catch (Exception e) {
<del> throw new RuntimeException("Unable to drop database " + databaseName,e);
<add> if (recycleDatabase) {
<add> java.sql.Connection connection = null;
<add> try {
<add> Class.forName("com.mysql.jdbc.Driver");
<add> connection = DriverManager
<add> .getConnection(getDatabaseAgnosticConnectString());
<add> } catch (Exception e) {
<add> throw new RuntimeException(e);
<add> }
<add> try {
<add> connection.prepareStatement("drop database " + databaseName)
<add> .execute();
<add> } catch (Exception e) {
<add> throw new RuntimeException("Unable to drop database "
<add> + databaseName, e);
<add> }
<add> try {
<add> connection.prepareStatement("create database " + databaseName)
<add> .execute();
<add> connection.close();
<add> } catch (Exception e) {
<add> throw new RuntimeException("Unable to drop database "
<add> + databaseName, e);
<add> }
<ide> }
<ide> }
<del>
<add>
<ide> protected String getDatabaseAgnosticConnectString() {
<ide> return "jdbc:mysql://localhost/?user=test&password=test";
<ide> }
<del>
<add>
<ide> protected String getConnectString() {
<del> return "jdbc:mysql://localhost/"+getDatabaseName()+"?user=test&password=test";
<add> return "jdbc:mysql://localhost/" + getDatabaseName()
<add> + "?user=test&password=test";
<ide> }
<ide> } |
||
Java | apache-2.0 | 0c2f7aaf748699bba42cb6fd6574c4aa2a2c3cae | 0 | hekate-io/hekate | /*
* Copyright 2018 The Hekate Project
*
* The Hekate Project 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 io.hekate.rpc;
import io.hekate.core.internal.util.ArgAssert;
import io.hekate.core.internal.util.StreamUtils;
import io.hekate.util.format.ToString;
import io.hekate.util.format.ToStringIgnore;
import java.util.List;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
/**
* Meta-information about an {@link Rpc}-annotated interface.
*
* @param <T> Interface type.
*
* @see RpcServerInfo#interfaces()
*/
public class RpcInterfaceInfo<T> {
private final Class<T> javaType;
private final int version;
private final int minClientVersion;
@ToStringIgnore
private final String versionedName;
@ToStringIgnore
private final List<RpcMethodInfo> methods;
/**
* Constructs a new instance.
*
* @param javaType See {@link #javaType()}.
* @param version See {@link #version()}
* @param minClientVersion See {@link #minClientVersion()}.
* @param methods See {@link #methods()}.
*/
public RpcInterfaceInfo(Class<T> javaType, int version, int minClientVersion, List<RpcMethodInfo> methods) {
ArgAssert.notNull(javaType, "Type");
ArgAssert.notNull(methods, "Methods list");
this.javaType = javaType;
this.version = version;
this.minClientVersion = minClientVersion;
this.versionedName = javaType.getName() + ':' + version;
this.methods = unmodifiableList(StreamUtils.nullSafe(methods).collect(toList()));
}
/**
* Returns the RPC interface name.
*
* <p>
* This method is merely a shortcut for {@link #javaType()}{@code .getName()}.
* </p>
*
* @return RPC interface name.
*/
public String name() {
return javaType.getName();
}
/**
* Returns the versioned name of this RPC interface.
*
* <p>
* Versioned name is a combination of {@link #name()} and {@link #version()}.
* </p>
*
* @return Versioned name.
*/
public String versionedName() {
return versionedName;
}
/**
* Returns the Java type of this RPC interface.
*
* @return Java type of this RPC interface.
*/
public Class<T> javaType() {
return javaType;
}
/**
* Returns the version of this RPC interface.
*
* @return Version of this RPC interface.
*
* @see Rpc#version()
*/
public int version() {
return version;
}
/**
* Returns the minimum client version that is supported by this RPC interface.
*
* @return Minimum client version that is supported by this RPC interface.
*
* @see Rpc#minClientVersion()
*/
public int minClientVersion() {
return minClientVersion;
}
/**
* Returns the meta-information about this RPC interface's methods.
*
* @return meta-information about this RPC interface's methods.
*/
public List<RpcMethodInfo> methods() {
return methods;
}
@Override
public String toString() {
return ToString.format(this);
}
}
| hekate-core/src/main/java/io/hekate/rpc/RpcInterfaceInfo.java | /*
* Copyright 2018 The Hekate Project
*
* The Hekate Project 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 io.hekate.rpc;
import io.hekate.core.internal.util.ArgAssert;
import io.hekate.core.internal.util.StreamUtils;
import io.hekate.util.format.ToString;
import io.hekate.util.format.ToStringIgnore;
import java.util.List;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
/**
* Meta-information about an {@link Rpc}-annotated interface.
*
* @param <T> Interface type.
*
* @see RpcServerInfo#interfaces()
*/
public class RpcInterfaceInfo<T> {
private final Class<T> javaType;
private final int version;
private final int minClientVersion;
@ToStringIgnore
private final String versionedName;
@ToStringIgnore
private final List<RpcMethodInfo> methods;
/**
* Constructs a new instance.
*
* @param javaType See {@link #javaType()}.
* @param version See {@link #version()}
* @param minClientVersion See {@link #minClientVersion()}.
* @param methods See {@link #methods()}.
*/
public RpcInterfaceInfo(Class<T> javaType, int version, int minClientVersion, List<RpcMethodInfo> methods) {
ArgAssert.notNull(javaType, "Type");
ArgAssert.notNull(methods, "Methods list");
this.javaType = javaType;
this.version = version;
this.minClientVersion = minClientVersion;
this.versionedName = name() + ':' + version;
this.methods = unmodifiableList(StreamUtils.nullSafe(methods).collect(toList()));
}
/**
* Returns the RPC interface name.
*
* <p>
* This method is merely a shortcut for {@link #javaType()}{@code .getName()}.
* </p>
*
* @return RPC interface name.
*/
public String name() {
return javaType.getName();
}
/**
* Returns the versioned name of this RPC interface.
*
* <p>
* Versioned name is a combination of {@link #name()} and {@link #version()}.
* </p>
*
* @return Versioned name.
*/
public String versionedName() {
return versionedName;
}
/**
* Returns the Java type of this RPC interface.
*
* @return Java type of this RPC interface.
*/
public Class<T> javaType() {
return javaType;
}
/**
* Returns the version of this RPC interface.
*
* @return Version of this RPC interface.
*
* @see Rpc#version()
*/
public int version() {
return version;
}
/**
* Returns the minimum client version that is supported by this RPC interface.
*
* @return Minimum client version that is supported by this RPC interface.
*
* @see Rpc#minClientVersion()
*/
public int minClientVersion() {
return minClientVersion;
}
/**
* Returns the meta-information about this RPC interface's methods.
*
* @return meta-information about this RPC interface's methods.
*/
public List<RpcMethodInfo> methods() {
return methods;
}
@Override
public String toString() {
return ToString.format(this);
}
}
| PMD:ConstructorCallsOverridableMethod.
| hekate-core/src/main/java/io/hekate/rpc/RpcInterfaceInfo.java | PMD:ConstructorCallsOverridableMethod. | <ide><path>ekate-core/src/main/java/io/hekate/rpc/RpcInterfaceInfo.java
<ide> this.javaType = javaType;
<ide> this.version = version;
<ide> this.minClientVersion = minClientVersion;
<del> this.versionedName = name() + ':' + version;
<add> this.versionedName = javaType.getName() + ':' + version;
<ide> this.methods = unmodifiableList(StreamUtils.nullSafe(methods).collect(toList()));
<ide> }
<ide> |
|
Java | apache-2.0 | a4765d25b53e2f43498ebe3ae38028ca222db49e | 0 | idf/commons-util | package io.deepreader.java.commons.util;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* User: Danyang
* Date: 1/7/2015
* Time: 14:57
*/
public class Transformer {
/**
* Template
* Fork -> Process -> Join
* Notice that parallelStream has much more overhead than stream.
* Method reference increases level of encapsulation
* @param map
* @param kp
* @param vp
* @param <K>
* @param <V>
* @return
*/
private static <K, V> Map<K, V> transform(Map<K, V> map, Function<K, K> kp, Function<V, V> vp) {
return map.entrySet()
.parallelStream()
.collect(Collectors.toConcurrentMap(Map.Entry::getKey, Map.Entry::getValue));
}
/**
* source -> filter -> map -> consume
* Equivalent to aggregate operations that accept Lambda expressions as parameters
* Local variables referenced from a lambda expression must be final or effectively final (FP Closure)
*
* <i>External Iteration</i> as compared to <i>Internal Iteration</i> using aggregate operations
* @param source
* @param tester .test()
* @param mapper .apply()
* @param block .accept()
* @param <X>
* @param <Y>
*/
public static <X, Y> void transform(
Iterable<X> source,
Predicate<X> tester,
Function <X, Y> mapper,
Consumer<Y> block) {
for (X p : source) {
if (tester.test(p)) {
Y data = mapper.apply(p);
block.accept(data);
}
}
}
/**
* Template
*/
private static <K, V> Map<K, V> merge(Map<K, V> a, Map<K, V> mx, BiFunction<? super V, ? super V, ? extends V> remappingFunc) {
a.forEach((k, v) -> mx.merge(k, v, remappingFunc));
return mx;
}
/**
* Constructor example:
* List<Integer> weights = Arrays.asList(7, 3, 4, 10);
* List<Apple> apples = map(weights, Apple::new);
* @param lst
* @param f
* @param <T>
* @param <R>
* @return
*/
public static <T, R> List<R> transform(List<T> lst, Function<T, R> f) {
return lst.parallelStream()
.map(f)
.collect(Collectors.toList());
}
/**
* Flat a stream
* @param words
* @return
*/
public static List<String> flatString(List<String> words) {
return words.parallelStream()
.map(elt -> elt.split(""))
.flatMap(Arrays::stream)
.collect(Collectors.toList());
}
/**
* TODO: replace Object[]
* @param lstA
* @param lstB
* @param <T>
* @return
*/
public static <T> List<Object[]> pair(List<T> lstA, List<T> lstB) {
return lstA.parallelStream()
.flatMap(i -> lstB.parallelStream()
.map(j -> new Object[] {i, j})
)
.collect(Collectors.toList());
}
/**
* Group the indexes of the elements by each element's value.
* http://stackoverflow.com/questions/27980488/java-8-stream-of-integer-grouping-indexes-of-a-stream-by-the-integers
* @param nums
* @return
*/
public static <T> Map<T, List<Integer>> groupListIndexByValue(List<T> nums) {
return IntStream.range(0, nums.size())
.boxed()
.parallel()
.collect(Collectors.groupingBy(nums::get));
}
/**
* Group the indexes of the elements by each element's value
* @param nums
* @param <T>
* @return
*/
public static <T> Map<T, List<Integer>> groupListToMap(Stream<T> nums) {
PrimitiveIterator.OfInt indexes = IntStream.iterate(0, x -> x + 1).iterator();
Map<T, List<Integer>> result = new HashMap<>();
nums.iterator().forEachRemaining(i -> result.merge(i,
new ArrayList<>(Arrays.asList(indexes.next())),
(l1, l2) -> {l1.addAll(l2); return l1;}
)
);
return result;
}
/**
* Group the list of T and show their counts
* @param s
* @param <T>
* @return
*/
public static <T> Map<T, Long> groupAndCount(Stream<T> s) {
return s.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
}
/**
* Remove an entry from a map by key
* @param map the targeting map
* @param tester predicate
* @param <K>
* @param <V>
*/
public static <K, V> void removeByKey(Map<K, V> map, Predicate<K> tester) {
Iterator<K> itr = map.keySet().iterator();
while(itr.hasNext()) {
if(tester.test(itr.next()))
itr.remove();
}
}
/**
* Remove an entry from a map by value
* @param map the targeting map
* @param tester predicate
* @param <K>
* @param <V>
*/
public static <K, V> void removeByValue(Map<K, V> map, Predicate<V> tester) {
Iterator<V> itr = map.values().iterator();
while (itr.hasNext()) {
if(tester.test(itr.next()))
itr.remove();
}
}
/**
* Flatten map's value to a list
* @param map must be sorted
* @param <K>
* @param <V>
* @return
*/
public static <K, V> List<V> toList(SortedMap<K, V>map) {
return map.entrySet().stream()
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
/**
* Flatten map's value to a list. Order is not guaranteed
* @param map generic
* @param <K>
* @param <V>
* @return
*/
public static <K, V> List<V> toList(Map<K, V> map) {
return map.entrySet().stream()
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
}
| src/main/java/io/deepreader/java/commons/util/Transformer.java | package io.deepreader.java.commons.util;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* User: Danyang
* Date: 1/7/2015
* Time: 14:57
*/
public class Transformer {
/**
* Template
* Fork -> Process -> Join
* Notice that parallelStream has much more overhead than stream.
* Method reference increases level of encapsulation
* @param map
* @param kp
* @param vp
* @param <K>
* @param <V>
* @return
*/
private static <K, V> Map<K, V> transform(Map<K, V> map, Function<K, K> kp, Function<V, V> vp) {
return map.entrySet()
.parallelStream()
.collect(Collectors.toConcurrentMap(Map.Entry::getKey, Map.Entry::getValue));
}
/**
* source -> filter -> map -> consume
* Equivalent to aggregate operations that accept Lambda expressions as parameters
* Local variables referenced from a lambda expression must be final or effectively final (FP Closure)
*
* <i>External Iteration</i> as compared to <i>Internal Iteration</i> using aggregate operations
* @param source
* @param tester .test()
* @param mapper .apply()
* @param block .accept()
* @param <X>
* @param <Y>
*/
public static <X, Y> void transform(
Iterable<X> source,
Predicate<X> tester,
Function <X, Y> mapper,
Consumer<Y> block) {
for (X p : source) {
if (tester.test(p)) {
Y data = mapper.apply(p);
block.accept(data);
}
}
}
/**
* Template
*/
private static <K, V> Map<K, V> merge(Map<K, V> a, Map<K, V> mx, BiFunction<? super V, ? super V, ? extends V> remappingFunc) {
a.forEach((k, v) -> mx.merge(k, v, remappingFunc));
return mx;
}
/**
* Constructor example:
* List<Integer> weights = Arrays.asList(7, 3, 4, 10);
* List<Apple> apples = map(weights, Apple::new);
* @param lst
* @param f
* @param <T>
* @param <R>
* @return
*/
public static <T, R> List<R> transform(List<T> lst, Function<T, R> f) {
return lst.parallelStream()
.map(f)
.collect(Collectors.toList());
}
/**
* Flat a stream
* @param words
* @return
*/
public static List<String> flatString(List<String> words) {
return words.parallelStream()
.map(elt -> elt.split(""))
.flatMap(Arrays::stream)
.collect(Collectors.toList());
}
/**
* TODO: replace Object[]
* @param lstA
* @param lstB
* @param <T>
* @return
*/
public static <T> List<Object[]> pair(List<T> lstA, List<T> lstB) {
return lstA.parallelStream()
.flatMap(i -> lstB.parallelStream()
.map(j -> new Object[] {i, j})
)
.collect(Collectors.toList());
}
/**
* Group the indexes of the elements by each element's value.
* http://stackoverflow.com/questions/27980488/java-8-stream-of-integer-grouping-indexes-of-a-stream-by-the-integers
* @param nums
* @return
*/
public static <T> Map<T, List<Integer>> groupListIndexByValue(List<T> nums) {
return IntStream.range(0, nums.size())
.boxed()
.parallel()
.collect(Collectors.groupingBy(nums::get));
}
/**
* Group the indexes of the elements by each element's value
* @param nums
* @param <T>
* @return
*/
public static <T> Map<T, List<Integer>> groupListToMap(Stream<T> nums) {
PrimitiveIterator.OfInt indexes = IntStream.iterate(0, x -> x + 1).iterator();
Map<T, List<Integer>> result = new HashMap<>();
nums.iterator().forEachRemaining(i -> result.merge(i,
new ArrayList<>(Arrays.asList(indexes.next())),
(l1, l2) -> {l1.addAll(l2); return l1;}
)
);
return result;
}
/**
* Group the list of T and show their counts
* @param s
* @param <T>
* @return
*/
public static <T> Map<T, Long> groupAndCount(Stream<T> s) {
return s.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
}
/**
* Remove an entry from a map by key
* @param map the targeting map
* @param tester predicate
* @param <K>
* @param <V>
*/
public static <K, V> void removeByKey(Map<K, V> map, Predicate<K> tester) {
Iterator<K> itr = map.keySet().iterator();
while(itr.hasNext()) {
if(tester.test(itr.next()))
itr.remove();
}
}
/**
* Remove an entry from a map by value
* @param map the targeting map
* @param tester predicate
* @param <K>
* @param <V>
*/
public static <K, V> void removeByValue(Map<K, V> map, Predicate<V> tester) {
Iterator<V> itr = map.values().iterator();
while (itr.hasNext()) {
if(tester.test(itr.next()))
itr.remove();
}
}
}
| Flatten map's value to a list
| src/main/java/io/deepreader/java/commons/util/Transformer.java | Flatten map's value to a list | <ide><path>rc/main/java/io/deepreader/java/commons/util/Transformer.java
<ide> itr.remove();
<ide> }
<ide> }
<add>
<add> /**
<add> * Flatten map's value to a list
<add> * @param map must be sorted
<add> * @param <K>
<add> * @param <V>
<add> * @return
<add> */
<add> public static <K, V> List<V> toList(SortedMap<K, V>map) {
<add> return map.entrySet().stream()
<add> .map(Map.Entry::getValue)
<add> .collect(Collectors.toList());
<add> }
<add>
<add> /**
<add> * Flatten map's value to a list. Order is not guaranteed
<add> * @param map generic
<add> * @param <K>
<add> * @param <V>
<add> * @return
<add> */
<add> public static <K, V> List<V> toList(Map<K, V> map) {
<add> return map.entrySet().stream()
<add> .map(Map.Entry::getValue)
<add> .collect(Collectors.toList());
<add> }
<ide> } |
|
Java | apache-2.0 | c9fb6018ca3a20f6467f89ea7488db4fe8aac78b | 0 | yuxiangtong/svntask,lookfirst/svntask,RaaaGEE/svntask | package com.googlecode.svntask.command;
import java.io.File;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import com.googlecode.svntask.Command;
/**
* Used for executing svn update. Defaults to recursive and force == true.
*
* @author jonstevens
*/
public class Update extends Command
{
private String path;
private SVNRevision revision = SVNRevision.HEAD;
private SVNDepth depth = SVNDepth.INFINITY;
private boolean recursive = true;
private boolean force = true;
@Override
public void execute() throws Exception
{
File filePath = new File(this.path);
this.getTask().log("update " + filePath.getCanonicalPath());
// Get the Update Client
SVNUpdateClient client = this.getTask().getSvnClient().getUpdateClient();
// Execute svn info
client.doUpdate(filePath, this.revision, this.depth, this.recursive, this.force);
}
/** */
@Override
protected void validateAttributes() throws Exception
{
if (this.path == null)
throw new Exception("path cannot be null");
}
/** */
public void setPath(String path)
{
this.path = path;
}
/** */
public void setRevision(long revision)
{
this.revision = SVNRevision.create(revision);
}
/** */
public void setDepth(String depth)
{
this.depth = SVNDepth.fromString(depth);
}
/** */
public void setRecursive(boolean recursive)
{
this.recursive = recursive;
}
/** */
public void setForce(boolean force)
{
this.force = force;
}
}
| src/com/googlecode/svntask/command/Update.java | package com.googlecode.svntask.command;
import java.io.File;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import com.googlecode.svntask.Command;
/**
* Used for executing svn update. Defaults to recursive and force == true.
*
* @author jonstevens
*/
public class Update extends Command
{
private String path;
private boolean recursive = true;
private boolean force = true;
@Override
public void execute() throws Exception
{
File filePath = new File(this.path);
this.getTask().log("update " + filePath.getCanonicalPath());
// Get the Update Client
SVNUpdateClient client = this.getTask().getSvnClient().getUpdateClient();
// Execute svn info
client.doUpdate(filePath, SVNRevision.HEAD, SVNDepth.INFINITY, this.recursive, this.force);
}
@Override
protected void validateAttributes() throws Exception
{
if (this.path == null)
throw new Exception("path cannot be null");
}
public void setPath(String path)
{
this.path = path;
}
public void setRecursive(boolean recursive)
{
this.recursive = recursive;
}
public void setForce(boolean force)
{
this.force = force;
}
}
| add setters for configurable properties. | src/com/googlecode/svntask/command/Update.java | add setters for configurable properties. | <ide><path>rc/com/googlecode/svntask/command/Update.java
<ide> public class Update extends Command
<ide> {
<ide> private String path;
<add> private SVNRevision revision = SVNRevision.HEAD;
<add> private SVNDepth depth = SVNDepth.INFINITY;
<ide> private boolean recursive = true;
<ide> private boolean force = true;
<ide>
<ide> SVNUpdateClient client = this.getTask().getSvnClient().getUpdateClient();
<ide>
<ide> // Execute svn info
<del> client.doUpdate(filePath, SVNRevision.HEAD, SVNDepth.INFINITY, this.recursive, this.force);
<add> client.doUpdate(filePath, this.revision, this.depth, this.recursive, this.force);
<ide> }
<ide>
<add> /** */
<ide> @Override
<ide> protected void validateAttributes() throws Exception
<ide> {
<ide> throw new Exception("path cannot be null");
<ide> }
<ide>
<add> /** */
<ide> public void setPath(String path)
<ide> {
<ide> this.path = path;
<ide> }
<ide>
<add> /** */
<add> public void setRevision(long revision)
<add> {
<add> this.revision = SVNRevision.create(revision);
<add> }
<add>
<add> /** */
<add> public void setDepth(String depth)
<add> {
<add> this.depth = SVNDepth.fromString(depth);
<add> }
<add>
<add> /** */
<ide> public void setRecursive(boolean recursive)
<ide> {
<ide> this.recursive = recursive;
<ide> }
<ide>
<add> /** */
<ide> public void setForce(boolean force)
<ide> {
<ide> this.force = force; |
|
JavaScript | bsd-3-clause | 069d5b3db98349d57fa44fe59ec7db2eddf2a44b | 0 | yurydelendik/gaia,yurydelendik/gaia | /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
/*const*/var kUseGL = 1;
/*const*/var kSnapToWholePixels = !kUseGL;
function abort(why) { alert(why); throw why; }
function assert(cond, msg) { if (!cond) abort(msg); }
// Return the current time of the "animation clock", which ticks on
// each frame drawn.
function GetAnimationClockTime() {
return window.mozAnimationStartTime ||
window.webkitAnimationStartTime ||
window.animationStartTime;
}
function RequestAnimationFrame() {
if (window.mozRequestAnimationFrame)
window.mozRequestAnimationFrame();
else if (window.webkitRequestAnimationFrame)
window.webkitRequestAnimationFrame();
else if (window.requestAnimationFrame)
window.requestAnimationFrame();
}
var Physics = {
Linear: function(elapsed, start, current, target) {
return start + (target - start) * elapsed;
},
Spring: function(elapsed, start, current, target) {
return current + (target - current) * elapsed;
}
}
function Sprite(width, height) {
var canvas = document.createElement('canvas');
this.width = canvas.width = width;
this.height = canvas.height = height;
this.canvas = canvas;
this.setPosition(0, 0);
this.setScale(1);
}
Sprite.prototype = {
getContext2D: function() {
var ctx = this.canvas.getContext('2d');
// XXX it appears that canvases aren't translated into GL
// coordinates before uploading, unlike <img>s :/. So hack
// here. Need to figure out if that's a FF bug or actually
// spec'd like that.
if (kUseGL) {
ctx.translate(0, this.height);
ctx.scale(1, -1);
}
return ctx;
},
setPosition: function(targetX, targetY, duration, fn) {
RequestAnimationFrame();
if (duration && (this.x != targetX || this.y != targetY)) {
this.startX = this.x;
this.startY = this.y;
this.targetX = targetX;
this.targetY = targetY;
this.moveStart = GetAnimationClockTime();
this.moveStop = this.moveStart + duration;
this.moveFunction = fn || Physics.Linear;
return;
}
this.x = targetX;
this.y = targetY;
this.moveFuncton = null;
},
setScale: function(targetScale, duration, fn) {
RequestAnimationFrame();
if (duration && this.scale != targetScale) {
this.startScale = this.scale;
this.targetScale = targetScale;
this.scaleStart = GetAnimationClockTime();
this.scaleStop = this.scaleStart + duration;
this.scaleFunction = fn || Physics.Linear;
return;
}
this.scale = targetScale;
this.scaleFunction = null;
},
animate: function(now) {
function GetElapsed(start, stop, now) {
return (now < start || now > stop) ? 1 : ((now - start) / (stop - start));
}
if (this.moveFunction) {
var elapsed = GetElapsed(this.moveStart, this.moveStop, now);
this.x = this.moveFunction(elapsed, this.startX, this.x, this.targetX);
this.y = this.moveFunction(elapsed, this.startY, this.y, this.targetY);
if (elapsed == 1)
this.moveFunction = null;
}
if (this.scaleFunction) {
var elapsed = GetElapsed(this.scaleStart, this.scaleStop, now);
this.scale = this.scaleFunction(elapsed, this.startScale, this.scale, this.targetScale);
if (elapsed == 1)
this.scaleFunction = null;
}
return this.moveFunction || this.scaleFunction;
}
}
function SceneGraph(canvas) {
this.blitter =
kUseGL ? new SpriteBlitterGL(canvas) : new SpriteBlitter2D(canvas);
this.canvas = canvas;
this.sprites = [];
this.background = null;
this.x = 0;
this.y = 0;
var self = this;
window.addEventListener("MozBeforePaint", function(event) {
var now = GetAnimationClockTime();
// continue painting until we are run out of animations
if (self.animate(now))
RequestAnimationFrame();
self.draw();
}, false);
}
SceneGraph.prototype = {
// add a sprite to the scene graph
add: function(sprite) {
this.blitter.spriteAdded(sprite);
var sprites = this.sprites;
sprite.index = sprites.length;
sprites.push(sprite);
},
// remove a sprite from the scene graph
remove: function(sprite) {
this.sprites.splice(sprite.index, 1);
this.blitter.spriteRemoved(sprite);
},
// animate the scene graph, returning false if the animation is done
animate: function(now) {
function GetElapsed(start, stop, now) {
return (now < start || now > stop) ? 1 : ((now - start) / (stop - start));
}
var more = false;
if (this.scrollFunction) {
var elapsed = GetElapsed(this.scrollStart, this.scrollStop, now);
this.x = this.scrollFunction(elapsed, this.startX, this.x, this.targetX);
this.y = this.scrollFunction(elapsed, this.startY, this.y, this.targetY);
if (elapsed == 1)
this.scrollFunction = null;
else
more = true;
}
var sprites = this.sprites;
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
if (sprite.animate(now))
more = true;
}
return more;
},
draw: function() {
var x = this.x, y = this.y;
if (kSnapToWholePixels) {
x |= 0;
y |= 0;
}
this.blitter.draw(x, y, this.sprites);
},
// walk over all sprites in the scene
forAll: function(callback) {
var sprites = this.sprites;
for (var n = 0; n < sprites.length; ++n)
callback(sprites[n]);
},
forHit: function(x, y, callback) {
var sprites = this.sprites;
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
if (x >= sprite.x && x < sprite.x + sprite.width &&
y >= sprite.y && y < sprite.y + sprite.height) {
callback(sprite);
return;
}
}
},
setBackground: function(imageUrl) {
var bgImg = document.createElement('img');
bgImg.src = imageUrl;
bgImg.sceneGraph = this;
bgImg.onload = function() {
var sceneGraph = this.sceneGraph;
sceneGraph.background = this;
sceneGraph.blitter.backgroundChanged(this);
RequestAnimationFrame();
};
},
setViewportTopLeft: function(targetX, targetY, duration, fn) {
RequestAnimationFrame();
if (duration && (this.x != targetX || this.y != targetY)) {
this.startX = this.x;
this.startY = this.y;
this.targetX = targetX;
this.targetY = targetY;
this.scrollStart = GetAnimationClockTime();
this.scrollStop = this.scrollStart + duration;
this.scrollFunction = fn || Physics.Linear;
return;
}
this.x = targetX;
this.y = targetY;
this.scrollFuncton = null;
}
}
// fallback 2D canvas backend
function SpriteBlitter2D(canvas) {
this.background = 'black';
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
}
SpriteBlitter2D.prototype = {
draw: function(x, y, sprites, background) {
var canvas = this.canvas;
var ctx = this.ctx;
var width = canvas.width;
var height = canvas.height;
ctx.fillStyle = this.background;
ctx.fillRect(0, 0, width, height);
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
var canvas = sprite.canvas;
if (canvas) {
var scale = sprite.scale;
ctx.drawImage(canvas, sprite.x - x, sprite.y - y, canvas.width * scale, canvas.height * scale);
}
}
},
backgroundChanged: function(background) {
this.background = this.ctx.createPattern(background, 'repeat');
},
// nothing to do here
spriteAdded: function(sprite) {},
spriteRemoved: function(sprite) {}
};
// blt using WebGL. This should be as fast or faster than using a 2D
// drawing context when the browser engine is drawing with OpenGL (and
// so doesn't need to read back from the WebGL context).
var kVertexShader = [
'attribute vec4 aPosAndTexCoord;',
'uniform mat4 uProjection;',
'varying vec2 vTexCoord;',
'',
'void main(void) {',
' vTexCoord = aPosAndTexCoord.zw;',
' vec4 transformedPos = vec4(aPosAndTexCoord.x, aPosAndTexCoord.y, 0.0, 1.0);',
' gl_Position = uProjection * transformedPos;',
'}'
].join("\n");
var kFragmentShader = [
'#ifdef GL_ES',
'precision highp float;',
'#endif',
'',
'varying vec2 vTexCoord;',
'uniform sampler2D uTexture;',
'',
'void main(void) {',
' vec4 texColor;',
' texColor = texture2D(uTexture, vTexCoord);',
' gl_FragColor = texColor;',
'}'
].join("\n");
var kMaxTextureSize = 0;
// NB: sprites really need a depth value since they can overlap. As
// it stands we should assume that they're drawn in an undefined
// z-order (GL may actually specify that, not sure).
function SpriteBlitterGL(canvas) {
this.backgroundTexture = null;
this.canvas = canvas;
var gl =
this.gl = canvas.getContext('experimental-webgl');
this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
this.posAndTexCoordArray = new Float32Array(4/*vertices*/ * 4/*elements per vertex*/);
this.posAndTexCoordBuffer = gl.createBuffer();
var program =
this.program = compileGLProgram(gl, kVertexShader, kFragmentShader);
this.projectionMatrix = new Float32Array(
[ 2.0, 0.0, 0.0, 0.0,
0.0, -2.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
-1.0, 1.0, 0.0, 1.0 ]);
this.viewportWidth = canvas.width;
this.viewportHeight = canvas.height;
gl.useProgram(program);
program.aPosAndTexCoord = gl.getAttribLocation(program, 'aPosAndTexCoord');
gl.enableVertexAttribArray(program.aPosAndTexCoord);
program.uProjection = gl.getUniformLocation(program, 'uProjection');
program.uTexture = gl.getUniformLocation(program, 'uTexture');
gl.clearColor(0.0, 0.0, 0.0, 1.0);
}
SpriteBlitterGL.prototype = {
draw: function(x, y, sprites) {
var gl = this.gl;
var posAndTexCoordArray = this.posAndTexCoordArray;
var posAndTexCoordBuffer = this.posAndTexCoordBuffer;
var program = this.program;
var viewportWidth = this.viewportWidth, viewportHeight = this.viewportHeight;
gl.viewport(0, 0, viewportWidth, viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT);
// XXX we need to enable blending to deal with overlapping
// sprites, but doing so causes the appearance of fonts to worsen.
// Need to investigate that.
gl.enable(gl.BLEND);
// "over" operator
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.uniformMatrix4fv(program.uProjection, false, this.projectionMatrix);
gl.uniform1i(program.uTexture, 0);
var translateX = x;
var translateY = y;
// Draw a quad at <x, y, width, height> textured by |texture|.
function drawTexturedQuad(texture, x, y, width, height) {
x /= viewportWidth;
y /= viewportHeight;
var xmost = x + width / viewportWidth;
var ymost = y + height / viewportHeight;
var i = 0;
// bottom left
posAndTexCoordArray[i++] = x;
posAndTexCoordArray[i++] = ymost;
posAndTexCoordArray[i++] = 0;
posAndTexCoordArray[i++] = 0;
// bottom right
posAndTexCoordArray[i++] = xmost;
posAndTexCoordArray[i++] = ymost;
posAndTexCoordArray[i++] = 1;
posAndTexCoordArray[i++] = 0;
// top left
posAndTexCoordArray[i++] = x;
posAndTexCoordArray[i++] = y;
posAndTexCoordArray[i++] = 0;
posAndTexCoordArray[i++] = 1;
// top right
posAndTexCoordArray[i++] = xmost;
posAndTexCoordArray[i++] = y;
posAndTexCoordArray[i++] = 1;
posAndTexCoordArray[i++] = 1;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.bindBuffer(gl.ARRAY_BUFFER, posAndTexCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, posAndTexCoordArray, gl.STREAM_DRAW);
gl.vertexAttribPointer(program.aPosition, 4, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
// draw the background
// NB: this will dumbly rescale the background image
drawTexturedQuad(this.backgroundTexture,
0, 0, viewportWidth, viewportHeight);
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
var canvas = sprite.canvas;
var scale = sprite.scale;
var x = sprite.x - translateX;
var y = sprite.y - translateY;
var width = canvas.width * scale;
var height = canvas.height * scale;
drawTexturedQuad(sprite.texture, x, y, width, height);
}
gl.bindTexture(gl.TEXTURE_2D, null);
},
backgroundChanged: function(background) {
var gl = this.gl;
var oldTexture = this.backgroundTexture;
if (oldTexture !== null) {
gl.deleteTexture(sprite.texture);
}
var texture = this.backgroundTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,
background);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
// XXX it'd be great to wrap with GL_REPEAT and not worry about
// size, but that would constrain us to POT textures or POT tiles.
// The former severely limits background design, and the former is
// annoying. Punt for now. There might also be cases in which
// we'd prefer to rescale the background or center-fit it.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
},
spriteAdded: function(sprite) {
if (('texture' in sprite) && sprite.texture !== null)
return;
var canvas = sprite.canvas;
assert(canvas.width <= this.maxTextureSize
&& canvas.height <= this.maxTextureSize,
"Sprite canvas must be smaller than max texture dimension");
var gl = this.gl;
var texture = sprite.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,
canvas);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// XXX mipmap if we start downscaling a lot
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
},
spriteRemoved: function(sprite) {
gl.deleteTexture(sprite.texture);
sprite.texture = null;
}
};
function compileGLProgram(gl, vxShader, pixShader) {
function compileShader(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
assert(gl.getShaderParameter(shader, gl.COMPILE_STATUS),
"Compile error for "+ type +": "+ gl.getShaderInfoLog(shader));
return shader;
}
var p = gl.createProgram();
var vs = compileShader(gl.VERTEX_SHADER, vxShader);
var fs = compileShader(gl.FRAGMENT_SHADER, pixShader);
gl.attachShader(p, vs); gl.deleteShader(vs);
gl.attachShader(p, fs); gl.deleteShader(fs);
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS))
// FIXME fall back on 2d
abort("Failed to compile shaders.");
return p;
}
| scenegraph.js | /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
/*const*/var kUseGL = 1;
/*const*/var kSnapToWholePixels = !kUseGL;
function abort(why) { alert(why); throw why; }
function assert(cond, msg) { if (!cond) abort(msg); }
// Return the current time of the "animation clock", which ticks on
// each frame drawn.
function GetAnimationClockTime() {
return window.mozAnimationStartTime ||
window.webkitAnimationStartTime ||
window.animationStartTime;
}
function RequestAnimationFrame() {
if (window.mozRequestAnimationFrame)
window.mozRequestAnimationFrame();
else if (window.webkitRequestAnimationFrame)
window.webkitRequestAnimationFrame();
else if (window.requestAnimationFrame)
window.requestAnimationFrame();
}
var Physics = {
Linear: function(elapsed, start, current, target) {
return start + (target - start) * elapsed;
},
Spring: function(elapsed, start, current, target) {
return current + (target - current) * elapsed;
}
}
function Sprite(width, height) {
var canvas = document.createElement('canvas');
this.width = canvas.width = width;
this.height = canvas.height = height;
this.canvas = canvas;
this.setPosition(0, 0);
this.setScale(1);
}
Sprite.prototype = {
getContext2D: function() {
var ctx = this.canvas.getContext('2d');
// XXX it appears that canvases aren't translated into GL
// coordinates before uploading, unlike <img>s :/. So hack
// here. Need to figure out if that's a FF bug or actually
// spec'd like that.
if (kUseGL) {
ctx.translate(0, this.height);
ctx.scale(1, -1);
}
return ctx;
},
setPosition: function(targetX, targetY, duration, fn) {
RequestAnimationFrame();
if (duration && (this.x != targetX || this.y != targetY)) {
this.startX = this.x;
this.startY = this.y;
this.targetX = targetX;
this.targetY = targetY;
this.moveStart = GetAnimationClockTime();
this.moveStop = this.moveStart + duration;
this.moveFunction = fn || Physics.Linear;
return;
}
this.x = targetX;
this.y = targetY;
this.moveFuncton = null;
},
setScale: function(targetScale, duration, fn) {
RequestAnimationFrame();
if (duration && this.scale != targetScale) {
this.startScale = this.scale;
this.targetScale = targetScale;
this.scaleStart = GetAnimationClockTime();
this.scaleStop = this.scaleStart + duration;
this.scaleFunction = fn || Physics.Linear;
return;
}
this.scale = targetScale;
this.scaleFunction = null;
},
animate: function(now) {
function GetElapsed(start, stop, now) {
return (now < start || now > stop) ? 1 : ((now - start) / (stop - start));
}
if (this.moveFunction) {
var elapsed = GetElapsed(this.moveStart, this.moveStop, now);
this.x = this.moveFunction(elapsed, this.startX, this.x, this.targetX);
this.y = this.moveFunction(elapsed, this.startY, this.y, this.targetY);
if (elapsed == 1)
this.moveFunction = null;
}
if (this.scaleFunction) {
var elapsed = GetElapsed(this.scaleStart, this.scaleStop, now);
this.scale = this.scaleFunction(elapsed, this.startScale, this.scale, this.targetScale);
if (elapsed == 1)
this.scaleFunction = null;
}
return this.moveFunction || this.scaleFunction;
}
}
function SceneGraph(canvas) {
this.blitter =
kUseGL ? new SpriteBlitterGL(canvas) : new SpriteBlitter2D(canvas);
this.canvas = canvas;
this.sprites = [];
this.background = null;
this.x = 0;
this.y = 0;
var self = this;
window.addEventListener("MozBeforePaint", function(event) {
var now = GetAnimationClockTime();
// continue painting until we are run out of animations
if (self.animate(now))
RequestAnimationFrame();
self.draw();
}, false);
}
SceneGraph.prototype = {
// add a sprite to the scene graph
add: function(sprite) {
this.blitter.spriteAdded(sprite);
var sprites = this.sprites;
sprite.index = sprites.length;
sprites.push(sprite);
},
// remove a sprite from the scene graph
remove: function(sprite) {
this.sprites.splice(sprite.index, 1);
this.blitter.spriteRemoved(sprite);
},
// animate the scene graph, returning false if the animation is done
animate: function(now) {
function GetElapsed(start, stop, now) {
return (now < start || now > stop) ? 1 : ((now - start) / (stop - start));
}
var more = false;
if (this.scrollFunction) {
var elapsed = GetElapsed(this.scrollStart, this.scrollStop, now);
this.x = this.scrollFunction(elapsed, this.startX, this.x, this.targetX);
this.y = this.scrollFunction(elapsed, this.startY, this.y, this.targetY);
if (elapsed == 1)
this.scrollFunction = null;
else
more = true;
}
var sprites = this.sprites;
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
if (sprite.animate(now))
more = true;
}
return more;
},
draw: function() {
var x = this.x, y = this.y;
if (kSnapToWholePixels) {
x |= 0;
y |= 0;
}
this.blitter.draw(x, y, this.sprites);
},
// walk over all sprites in the scene
forAll: function(callback) {
var sprites = this.sprites;
for (var n = 0; n < sprites.length; ++n)
callback(sprites[n]);
},
forHit: function(x, y, callback) {
var sprites = this.sprites;
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
if (x >= sprite.x && x < sprite.x + sprite.width &&
y >= sprite.y && y < sprite.y + sprite.height) {
callback(sprite);
return;
}
}
},
setBackground: function(imageUrl) {
var bgImg = document.createElement('img');
bgImg.src = imageUrl;
bgImg.sceneGraph = this;
bgImg.onload = function() {
var sceneGraph = this.sceneGraph;
sceneGraph.background = this;
sceneGraph.blitter.backgroundChanged(this);
RequestAnimationFrame();
};
},
setViewportTopLeft: function(targetX, targetY, duration, fn) {
RequestAnimationFrame();
if (duration && (this.x != targetX || this.y != targetY)) {
this.startX = this.x;
this.startY = this.y;
this.targetX = targetX;
this.targetY = targetY;
this.scrollStart = GetAnimationClockTime();
this.scrollStop = this.scrollStart + duration;
this.scrollFunction = fn || Physics.Linear;
return;
}
this.x = targetX;
this.y = targetY;
this.scrollFuncton = null;
}
}
// fallback 2D canvas backend
function SpriteBlitter2D(canvas) {
this.background = 'black';
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
}
SpriteBlitter2D.prototype = {
draw: function(x, y, sprites, background) {
var canvas = this.canvas;
var ctx = this.ctx;
var width = canvas.width;
var height = canvas.height;
ctx.fillStyle = this.background;
ctx.fillRect(0, 0, width, height);
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
var canvas = sprite.canvas;
if (canvas) {
var scale = sprite.scale;
ctx.drawImage(canvas, sprite.x - x, sprite.y - y, canvas.width * scale, canvas.height * scale);
}
}
},
backgroundChanged: function(background) {
this.background = this.ctx.createPattern(background, 'repeat');
},
// nothing to do here
spriteAdded: function(sprite) {},
spriteRemoved: function(sprite) {}
};
// blt using WebGL. This should be as fast or faster than using a 2D
// drawing context when the browser engine is drawing with OpenGL (and
// so doesn't need to read back from the WebGL context).
var kVertexShader = [
'attribute vec4 aPosAndTexCoord;',
'uniform mat4 uProjection;',
'varying vec2 vTexCoord;',
'',
'void main(void) {',
' vTexCoord = aPosAndTexCoord.zw;',
' vec4 transformedPos = vec4(aPosAndTexCoord.x, aPosAndTexCoord.y, 0.0, 1.0);',
' gl_Position = uProjection * transformedPos;',
'}'
].join("\n");
var kFragmentShader = [
'#ifdef GL_ES',
'precision highp float;',
'#endif',
'',
'varying vec2 vTexCoord;',
'uniform sampler2D uTexture;',
'',
'void main(void) {',
' vec4 texColor;',
' texColor = texture2D(uTexture, vTexCoord);',
' gl_FragColor = texColor;',
'}'
].join("\n");
var kMaxTextureSize = 0;
// NB: sprites really need a depth value since they can overlap. As
// it stands we should assume that they're drawn in an undefined
// z-order (GL may actually specify that, not sure).
function SpriteBlitterGL(canvas) {
this.canvas = canvas;
var gl =
this.gl = canvas.getContext('experimental-webgl');
this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
this.posAndTexCoordArray = new Float32Array(4/*vertices*/ * 4/*elements per vertex*/);
this.posAndTexCoordBuffer = gl.createBuffer();
var program =
this.program = compileGLProgram(gl, kVertexShader, kFragmentShader);
this.projectionMatrix = new Float32Array(
[ 2.0, 0.0, 0.0, 0.0,
0.0, -2.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
-1.0, 1.0, 0.0, 1.0 ]);
this.viewportWidth = canvas.width;
this.viewportHeight = canvas.height;
gl.useProgram(program);
program.aPosAndTexCoord = gl.getAttribLocation(program, 'aPosAndTexCoord');
gl.enableVertexAttribArray(program.aPosAndTexCoord);
program.uProjection = gl.getUniformLocation(program, 'uProjection');
program.uTexture = gl.getUniformLocation(program, 'uTexture');
gl.clearColor(0.0, 0.0, 0.0, 1.0);
}
SpriteBlitterGL.prototype = {
draw: function(x, y, sprites) {
var gl = this.gl;
var posAndTexCoordArray = this.posAndTexCoordArray;
var posAndTexCoordBuffer = this.posAndTexCoordBuffer;
var program = this.program;
var viewportWidth = this.viewportWidth, viewportHeight = this.viewportHeight;
gl.viewport(0, 0, viewportWidth, viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT);
// XXX we need to enable blending to deal with overlapping
// sprites, but doing so causes the appearance of fonts to worsen.
// Need to investigate that.
gl.enable(gl.BLEND);
// "over" operator
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.uniformMatrix4fv(program.uProjection, false, this.projectionMatrix);
gl.uniform1i(program.uTexture, 0);
var translateX = x;
var translateY = y;
for (var n = 0; n < sprites.length; ++n) {
var sprite = sprites[n];
var canvas = sprite.canvas;
var scale = sprite.scale;
var x = (sprite.x - translateX) / viewportWidth;
var y = (sprite.y - translateY) / viewportHeight;
var width = canvas.width * scale;
var height = canvas.height * scale;
var xmost = x + width / viewportWidth;
var ymost = y + height / viewportHeight;
var i = 0;
// bottom left
posAndTexCoordArray[i++] = x;
posAndTexCoordArray[i++] = ymost;
posAndTexCoordArray[i++] = 0;
posAndTexCoordArray[i++] = 0;
// bottom right
posAndTexCoordArray[i++] = xmost;
posAndTexCoordArray[i++] = ymost;
posAndTexCoordArray[i++] = 1;
posAndTexCoordArray[i++] = 0;
// top left
posAndTexCoordArray[i++] = x;
posAndTexCoordArray[i++] = y;
posAndTexCoordArray[i++] = 0;
posAndTexCoordArray[i++] = 1;
// top right
posAndTexCoordArray[i++] = xmost;
posAndTexCoordArray[i++] = y;
posAndTexCoordArray[i++] = 1;
posAndTexCoordArray[i++] = 1;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, sprite.texture);
gl.bindBuffer(gl.ARRAY_BUFFER, posAndTexCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, posAndTexCoordArray, gl.STREAM_DRAW);
gl.vertexAttribPointer(program.aPosition, 4, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
gl.bindTexture(gl.TEXTURE_2D, null);
},
backgroundChanged: function(background) {
// TODO
},
spriteAdded: function(sprite) {
if (('texture' in sprite) && sprite.texture !== null)
return;
var canvas = sprite.canvas;
assert(canvas.width <= this.maxTextureSize
&& canvas.height <= this.maxTextureSize,
"Sprite canvas must be smaller than max texture dimension");
var gl = this.gl;
var texture = sprite.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,
canvas);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// XXX mipmap if we start downscaling a lot
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
},
spriteRemoved: function(sprite) {
gl.deleteTexture(sprite.texture);
sprite.texture = null;
}
};
function compileGLProgram(gl, vxShader, pixShader) {
function compileShader(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
assert(gl.getShaderParameter(shader, gl.COMPILE_STATUS),
"Compile error for "+ type +": "+ gl.getShaderInfoLog(shader));
return shader;
}
var p = gl.createProgram();
var vs = compileShader(gl.VERTEX_SHADER, vxShader);
var fs = compileShader(gl.FRAGMENT_SHADER, pixShader);
gl.attachShader(p, vs); gl.deleteShader(vs);
gl.attachShader(p, fs); gl.deleteShader(fs);
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS))
// FIXME fall back on 2d
abort("Failed to compile shaders.");
return p;
}
| draw the background in webgl backend
| scenegraph.js | draw the background in webgl backend | <ide><path>cenegraph.js
<ide> // it stands we should assume that they're drawn in an undefined
<ide> // z-order (GL may actually specify that, not sure).
<ide> function SpriteBlitterGL(canvas) {
<add> this.backgroundTexture = null;
<ide> this.canvas = canvas;
<ide> var gl =
<ide> this.gl = canvas.getContext('experimental-webgl');
<ide> var translateX = x;
<ide> var translateY = y;
<ide>
<del> for (var n = 0; n < sprites.length; ++n) {
<del> var sprite = sprites[n];
<del> var canvas = sprite.canvas;
<del> var scale = sprite.scale;
<del> var x = (sprite.x - translateX) / viewportWidth;
<del> var y = (sprite.y - translateY) / viewportHeight;
<del> var width = canvas.width * scale;
<del> var height = canvas.height * scale;
<add> // Draw a quad at <x, y, width, height> textured by |texture|.
<add> function drawTexturedQuad(texture, x, y, width, height) {
<add> x /= viewportWidth;
<add> y /= viewportHeight;
<ide> var xmost = x + width / viewportWidth;
<ide> var ymost = y + height / viewportHeight;
<ide>
<ide> posAndTexCoordArray[i++] = 1;
<ide>
<ide> gl.activeTexture(gl.TEXTURE0);
<del> gl.bindTexture(gl.TEXTURE_2D, sprite.texture);
<add> gl.bindTexture(gl.TEXTURE_2D, texture);
<ide>
<ide> gl.bindBuffer(gl.ARRAY_BUFFER, posAndTexCoordBuffer);
<ide> gl.bufferData(gl.ARRAY_BUFFER, posAndTexCoordArray, gl.STREAM_DRAW);
<ide> gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
<ide> }
<ide>
<add> // draw the background
<add> // NB: this will dumbly rescale the background image
<add> drawTexturedQuad(this.backgroundTexture,
<add> 0, 0, viewportWidth, viewportHeight);
<add>
<add> for (var n = 0; n < sprites.length; ++n) {
<add> var sprite = sprites[n];
<add> var canvas = sprite.canvas;
<add> var scale = sprite.scale;
<add> var x = sprite.x - translateX;
<add> var y = sprite.y - translateY;
<add> var width = canvas.width * scale;
<add> var height = canvas.height * scale;
<add>
<add> drawTexturedQuad(sprite.texture, x, y, width, height);
<add> }
<add>
<ide> gl.bindTexture(gl.TEXTURE_2D, null);
<ide> },
<ide> backgroundChanged: function(background) {
<del> // TODO
<add> var gl = this.gl;
<add> var oldTexture = this.backgroundTexture;
<add> if (oldTexture !== null) {
<add> gl.deleteTexture(sprite.texture);
<add> }
<add> var texture = this.backgroundTexture = gl.createTexture();
<add>
<add> gl.bindTexture(gl.TEXTURE_2D, texture);
<add> gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,
<add> background);
<add> gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
<add> gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
<add> // XXX it'd be great to wrap with GL_REPEAT and not worry about
<add> // size, but that would constrain us to POT textures or POT tiles.
<add> // The former severely limits background design, and the former is
<add> // annoying. Punt for now. There might also be cases in which
<add> // we'd prefer to rescale the background or center-fit it.
<add> gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
<add> gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
<add> gl.bindTexture(gl.TEXTURE_2D, null);
<ide> },
<ide> spriteAdded: function(sprite) {
<ide> if (('texture' in sprite) && sprite.texture !== null) |
|
Java | apache-2.0 | d9e976a4bb74c54b94cc13d14944412eec6dc84e | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2007 University of British Columbia
*
* 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 ubic.gemma.core.ontology;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.compass.core.util.concurrent.ConcurrentHashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.basecode.ontology.model.OntologyIndividual;
import ubic.basecode.ontology.model.OntologyResource;
import ubic.basecode.ontology.model.OntologyTerm;
import ubic.basecode.ontology.model.OntologyTermSimple;
import ubic.basecode.ontology.providers.*;
import ubic.basecode.ontology.search.OntologySearch;
import ubic.basecode.util.Configuration;
import ubic.gemma.core.genome.gene.service.GeneService;
import ubic.gemma.core.ontology.providers.GemmaOntologyService;
import ubic.gemma.core.ontology.providers.GeneOntologyService;
import ubic.gemma.core.search.SearchResult;
import ubic.gemma.core.search.SearchService;
import ubic.gemma.model.association.GOEvidenceCode;
import ubic.gemma.model.common.description.Characteristic;
import ubic.gemma.model.common.search.SearchSettings;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.gene.GeneValueObject;
import ubic.gemma.model.genome.gene.phenotype.valueObject.CharacteristicValueObject;
import ubic.gemma.persistence.service.common.description.CharacteristicService;
import ubic.gemma.persistence.service.expression.biomaterial.BioMaterialService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
/**
* Has a static method for finding out which ontologies are loaded into the system and a general purpose find method
* that delegates to the many ontology services. NOTE: Logging messages from this service are important for tracking
* changes to annotations.
*
* @author pavlidis
*/
@Service
public class OntologyServiceImpl implements OntologyService {
/**
* Throttle how many ontology terms we retrieve. We search the ontologies in a favored order, so we can stop when we
* find "enough stuff".
*/
private static final int MAX_TERMS_TO_FETCH = 200;
private static final Log log = LogFactory.getLog( OntologyServiceImpl.class.getName() );
private static Collection<OntologyTerm> categoryTerms = null;
private final CellLineOntologyService cellLineOntologyService = new CellLineOntologyService();
private final CellTypeOntologyService cellTypeOntologyService = new CellTypeOntologyService();
private final ChebiOntologyService chebiOntologyService = new ChebiOntologyService();
private final DiseaseOntologyService diseaseOntologyService = new DiseaseOntologyService();
private final ExperimentalFactorOntologyService experimentalFactorOntologyService = new ExperimentalFactorOntologyService();
@Deprecated
private final FMAOntologyService fmaOntologyService = new FMAOntologyService();
private final GemmaOntologyService gemmaOntologyService = new GemmaOntologyService();
private final HumanDevelopmentOntologyService humanDevelopmentOntologyService = new HumanDevelopmentOntologyService();
private final HumanPhenotypeOntologyService humanPhenotypeOntologyService = new HumanPhenotypeOntologyService();
private final MammalianPhenotypeOntologyService mammalianPhenotypeOntologyService = new MammalianPhenotypeOntologyService();
private final MouseDevelopmentOntologyService mouseDevelopmentOntologyService = new MouseDevelopmentOntologyService();
@Deprecated
private final NIFSTDOntologyService nifstdOntologyService = new NIFSTDOntologyService();
private final ObiService obiService = new ObiService();
private final Collection<AbstractOntologyService> ontologyServices = new ArrayList<>();
private final SequenceOntologyService sequenceOntologyService = new SequenceOntologyService();
private final UberonOntologyService uberonOntologyService = new UberonOntologyService();
private BioMaterialService bioMaterialService;
private CharacteristicService characteristicService;
private SearchService searchService;
private GeneOntologyService geneOntologyService;
private GeneService geneService;
@Autowired
public void setBioMaterialService( BioMaterialService bioMaterialService ) {
this.bioMaterialService = bioMaterialService;
}
@Autowired
public void setCharacteristicService( CharacteristicService characteristicService ) {
this.characteristicService = characteristicService;
}
@Autowired
public void setSearchService( SearchService searchService ) {
this.searchService = searchService;
}
@Autowired
public void setGeneOntologyService( GeneOntologyService geneOntologyService ) {
this.geneOntologyService = geneOntologyService;
}
@Autowired
public void setGeneService( GeneService geneService ) {
this.geneService = geneService;
}
@Override
public void afterPropertiesSet() {
this.ontologyServices.add( this.gemmaOntologyService );
this.ontologyServices.add( this.experimentalFactorOntologyService );
this.ontologyServices.add( this.obiService );
this.ontologyServices.add( this.nifstdOntologyService ); // DEPRECATED
this.ontologyServices.add( this.fmaOntologyService ); // DEPRECATED
this.ontologyServices.add( this.diseaseOntologyService );
this.ontologyServices.add( this.cellTypeOntologyService );
this.ontologyServices.add( this.chebiOntologyService );
this.ontologyServices.add( this.mammalianPhenotypeOntologyService );
this.ontologyServices.add( this.humanPhenotypeOntologyService );
this.ontologyServices.add( this.mouseDevelopmentOntologyService );
this.ontologyServices.add( this.humanDevelopmentOntologyService );
this.ontologyServices.add( this.sequenceOntologyService );
this.ontologyServices.add( this.cellLineOntologyService );
this.ontologyServices.add( this.uberonOntologyService );
/*
* If this load.ontologies is NOT configured, we go ahead (per-ontology config will be checked).
*/
String doLoad = Configuration.getString( "load.ontologies" );
if ( StringUtils.isBlank( doLoad ) || Configuration.getBoolean( "load.ontologies" ) ) {
for ( AbstractOntologyService serv : this.ontologyServices ) {
serv.startInitializationThread( false, false );
}
} else {
log.info( "Auto-loading of ontologies suppressed" );
}
}
@SuppressWarnings({ "unused", "WeakerAccess" }) // Possible external use
public void countOccurrences( Collection<CharacteristicValueObject> searchResults,
Map<String, CharacteristicValueObject> previouslyUsedInSystem ) {
StopWatch watch = new StopWatch();
watch.start();
Set<String> uris = new HashSet<>();
for ( CharacteristicValueObject cvo : searchResults ) {
uris.add( cvo.getValueUri() );
}
Collection<Characteristic> existingCharacteristicsUsingTheseTerms = characteristicService.findByUri( uris );
for ( Characteristic c : existingCharacteristicsUsingTheseTerms ) {
// count up number of usages; see bug 3897
String key = this.foundValueKey( c );
if ( previouslyUsedInSystem.containsKey( key ) ) {
previouslyUsedInSystem.get( key ).incrementOccurrenceCount();
continue;
}
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log.debug( "saw " + key + " (" + key + ")" );
CharacteristicValueObject vo = new CharacteristicValueObject( c );
vo.setCategory( null );
vo.setCategoryUri( null ); // to avoid us counting separately by category.
vo.setAlreadyPresentInDatabase( true );
vo.incrementOccurrenceCount();
previouslyUsedInSystem.put( key, vo );
}
if ( OntologyServiceImpl.log.isDebugEnabled() || ( watch.getTime() > 100
&& previouslyUsedInSystem.size() > 0 ) )
OntologyServiceImpl.log
.info( "found " + previouslyUsedInSystem.size() + " matching characteristics used in the database"
+ " in " + watch.getTime() + " ms " + " Filtered from initial set of "
+ existingCharacteristicsUsingTheseTerms.size() );
}
/**
* Using the ontology and values in the database, for a search searchQuery given by the client give an ordered list
* of possible choices
*/
@Override
public Collection<CharacteristicValueObject> findExperimentsCharacteristicTags( String searchQueryString,
boolean useNeuroCartaOntology ) {
String searchQuery = OntologySearch.stripInvalidCharacters( searchQueryString );
if ( searchQuery.length() < 3 ) {
return new HashSet<>();
}
// this will do like %search%
Collection<CharacteristicValueObject> characteristicsFromDatabase = CharacteristicValueObject
.characteristic2CharacteristicVO( this.characteristicService.findByValue( "%" + searchQuery ) );
Map<String, CharacteristicValueObject> characteristicFromDatabaseWithValueUri = new HashMap<>();
Collection<CharacteristicValueObject> characteristicFromDatabaseFreeText = new HashSet<>();
for ( CharacteristicValueObject characteristicInDatabase : characteristicsFromDatabase ) {
// flag to let know that it was found in the database
characteristicInDatabase.setAlreadyPresentInDatabase( true );
if ( characteristicInDatabase.getValueUri() != null && !characteristicInDatabase.getValueUri()
.equals( "" ) ) {
characteristicFromDatabaseWithValueUri
.put( characteristicInDatabase.getValueUri(), characteristicInDatabase );
} else {
// free txt, no value uri
characteristicFromDatabaseFreeText.add( characteristicInDatabase );
}
}
// search the ontology for the given searchTerm, but if already found in the database dont add it again
Collection<CharacteristicValueObject> characteristicsFromOntology = this
.findCharacteristicsFromOntology( searchQuery, useNeuroCartaOntology,
characteristicFromDatabaseWithValueUri );
// order to show the the term: 1-exactMatch, 2-startWith, 3-substring and 4- no rule
// order to show values for each List : 1-From database with Uri, 2- from Ontology, 3- from from database with
// no Uri
Collection<CharacteristicValueObject> characteristicsWithExactMatch = new ArrayList<>();
Collection<CharacteristicValueObject> characteristicsStartWithQuery = new ArrayList<>();
Collection<CharacteristicValueObject> characteristicsSubstring = new ArrayList<>();
Collection<CharacteristicValueObject> characteristicsNoRuleFound = new ArrayList<>();
// from the database with a uri
this.putCharacteristicsIntoSpecificList( searchQuery, characteristicFromDatabaseWithValueUri.values(),
characteristicsWithExactMatch, characteristicsStartWithQuery, characteristicsSubstring,
characteristicsNoRuleFound );
// from the ontology
this.putCharacteristicsIntoSpecificList( searchQuery, characteristicsFromOntology,
characteristicsWithExactMatch, characteristicsStartWithQuery, characteristicsSubstring,
characteristicsNoRuleFound );
// from the database with no uri
this.putCharacteristicsIntoSpecificList( searchQuery, characteristicFromDatabaseFreeText,
characteristicsWithExactMatch, characteristicsStartWithQuery, characteristicsSubstring,
characteristicsNoRuleFound );
List<CharacteristicValueObject> allCharacteristicsFound = new ArrayList<>();
allCharacteristicsFound.addAll( characteristicsWithExactMatch );
allCharacteristicsFound.addAll( characteristicsStartWithQuery );
allCharacteristicsFound.addAll( characteristicsSubstring );
allCharacteristicsFound.addAll( characteristicsNoRuleFound );
// limit the size of the returned phenotypes to 100 terms
if ( allCharacteristicsFound.size() > 100 ) {
return allCharacteristicsFound.subList( 0, 100 );
}
return allCharacteristicsFound;
}
@Override
public Collection<OntologyIndividual> findIndividuals( String givenSearch ) {
String query = OntologySearch.stripInvalidCharacters( givenSearch );
Collection<OntologyIndividual> results = new HashSet<>();
for ( AbstractOntologyService ontology : ontologyServices ) {
Collection<OntologyIndividual> found = ontology.findIndividuals( query );
if ( found != null )
results.addAll( found );
}
return results;
}
@Override
public Collection<Characteristic> findTermAsCharacteristic( String search ) {
String query = OntologySearch.stripInvalidCharacters( search );
Collection<Characteristic> results = new HashSet<>();
if ( StringUtils.isBlank( query ) ) {
return results;
}
for ( AbstractOntologyService ontology : ontologyServices ) {
Collection<OntologyTerm> found = ontology.findTerm( query );
if ( found != null )
results.addAll( this.convert( new HashSet<OntologyResource>( found ) ) );
}
return results;
}
@Override
public Collection<OntologyTerm> findTerms( String search ) {
Collection<OntologyTerm> results = new HashSet<>();
/*
* URI input: just retrieve the term.
*/
if ( search.startsWith( "http://" ) ) {
for ( AbstractOntologyService ontology : ontologyServices ) {
if ( ontology.isOntologyLoaded() ) {
OntologyTerm found = ontology.getTerm( search );
if ( found != null ) {
results.add( found );
}
}
}
return results;
}
/*
* Other queries:
*/
String query = OntologySearch.stripInvalidCharacters( search );
if ( StringUtils.isBlank( query ) ) {
return results;
}
for ( AbstractOntologyService ontology : ontologyServices ) {
if ( ontology.isOntologyLoaded() ) {
Collection<OntologyTerm> found = ontology.findTerm( query );
if ( found != null ) {
for ( OntologyTerm t : found ) {
if ( !t.isTermObsolete() ) {
results.add( t );
}
}
}
}
}
if ( geneOntologyService.isReady() )
results.addAll( geneOntologyService.findTerm( search ) );
return results;
}
@Override
public Collection<CharacteristicValueObject> findTermsInexact( String givenQueryString, Taxon taxon ) {
if ( StringUtils.isBlank( givenQueryString ) )
return null;
StopWatch watch = new StopWatch();
watch.start();
String queryString = OntologySearch.stripInvalidCharacters( givenQueryString );
if ( StringUtils.isBlank( queryString ) ) {
OntologyServiceImpl.log.warn( "The query was not valid (ended up being empty): " + givenQueryString );
return new HashSet<>();
}
if ( OntologyServiceImpl.log.isDebugEnabled() ) {
OntologyServiceImpl.log
.debug( "starting findExactTerm for " + queryString + ". Timing information begins from here" );
}
Collection<? extends OntologyResource> results = null;
Collection<CharacteristicValueObject> searchResults = new HashSet<>();
Map<String, CharacteristicValueObject> previouslyUsedInSystem = new HashMap<>();
this.countOccurrences( queryString, previouslyUsedInSystem );
this.searchForGenes( queryString, taxon, searchResults );
for ( AbstractOntologyService service : this.ontologyServices ) {
if ( !service.isOntologyLoaded() )
continue;
try {
results = service.findResources( queryString );
} catch ( Exception e ) {
OntologyServiceImpl.log.warn( e.getMessage() ); // parse errors, etc.
}
if ( results == null || results.isEmpty() )
continue;
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log
.debug( "found " + results.size() + " from " + service.getClass().getSimpleName() + " in "
+ watch.getTime() + " ms" );
searchResults.addAll( CharacteristicValueObject
.characteristic2CharacteristicVO( this.termsToCharacteristics( results ) ) );
if ( searchResults.size() > OntologyServiceImpl.MAX_TERMS_TO_FETCH ) {
break;
}
}
this.countOccurrences( searchResults, previouslyUsedInSystem );
// get GO terms, if we don't already have a lot of possibilities. (might have to adjust this)
if ( searchResults.size() < OntologyServiceImpl.MAX_TERMS_TO_FETCH && geneOntologyService.isReady() ) {
searchResults.addAll( CharacteristicValueObject.characteristic2CharacteristicVO(
this.termsToCharacteristics( geneOntologyService.findTerm( queryString ) ) ) );
}
// Sort the results rather elaborately.
Collection<CharacteristicValueObject> sortedResults = this
.sort( previouslyUsedInSystem, searchResults, queryString );
if ( watch.getTime() > 1000 ) {
OntologyServiceImpl.log
.info( "Ontology term query for: " + givenQueryString + ": " + watch.getTime() + "ms" );
}
return sortedResults;
}
@Override
public Collection<OntologyTerm> getCategoryTerms() {
if ( !experimentalFactorOntologyService.isOntologyLoaded() ) {
OntologyServiceImpl.log.warn( "EFO is not loaded" );
}
/*
* Requires EFO, OBI and SO. If one of them isn't loaded, the terms are filled in with placeholders.
*/
if ( OntologyServiceImpl.categoryTerms == null || OntologyServiceImpl.categoryTerms.isEmpty() ) {
this.initializeCategoryTerms();
}
return OntologyServiceImpl.categoryTerms;
}
@Override
public CellLineOntologyService getCellLineOntologyService() {
return cellLineOntologyService;
}
@Override
public CellTypeOntologyService getCellTypeOntologyService() {
return cellTypeOntologyService;
}
@Override
public GemmaOntologyService getGemmaOntologyService() {
return gemmaOntologyService;
}
@Override
public HumanDevelopmentOntologyService getHumanDevelopmentOntologyService() {
return humanDevelopmentOntologyService;
}
@Override
public MouseDevelopmentOntologyService getMouseDevelopmentOntologyService() {
return mouseDevelopmentOntologyService;
}
@Override
public ChebiOntologyService getChebiOntologyService() {
return chebiOntologyService;
}
@Override
public DiseaseOntologyService getDiseaseOntologyService() {
return diseaseOntologyService;
}
@Override
public ExperimentalFactorOntologyService getExperimentalFactorOntologyService() {
return experimentalFactorOntologyService;
}
@Override
public HumanPhenotypeOntologyService getHumanPhenotypeOntologyService() {
return humanPhenotypeOntologyService;
}
@Override
public MammalianPhenotypeOntologyService getMammalianPhenotypeOntologyService() {
return mammalianPhenotypeOntologyService;
}
@Override
public ObiService getObiService() {
return obiService;
}
@Override
public UberonOntologyService getUberonService() {
return this.uberonOntologyService;
}
@Override
public OntologyResource getResource( String uri ) {
for ( AbstractOntologyService ontology : ontologyServices ) {
OntologyResource resource = ontology.getResource( uri );
if ( resource != null )
return resource;
}
return null;
}
@Override
public SequenceOntologyService getSequenceOntologyService() {
return this.sequenceOntologyService;
}
@Override
public OntologyTerm getTerm( String uri ) {
for ( AbstractOntologyService ontology : ontologyServices ) {
OntologyTerm term = ontology.getTerm( uri );
if ( term != null )
return term;
}
// TODO: doesn't include GO.
return null;
}
/**
* @return true if the Uri is an ObsoleteClass. This will only work if the ontology in question is loaded.
*/
@Override
public boolean isObsolete( String uri ) {
if ( uri == null )
return false;
OntologyTerm t = this.getTerm( uri );
return t != null && t.isTermObsolete();
}
@Override
public void reindexAllOntologies() {
for ( AbstractOntologyService serv : this.ontologyServices ) {
if ( serv.isOntologyLoaded() ) {
OntologyServiceImpl.log.info( "Reindexing: " + serv );
try {
serv.index( true );
} catch ( Exception e ) {
OntologyServiceImpl.log.error( "Failed to index " + serv + ": " + e.getMessage(), e );
}
} else {
if ( serv.isEnabled() )
OntologyServiceImpl.log
.info( "Not available for reindexing (not enabled or finished initialization): " + serv );
}
}
}
@Override
public void reinitializeAllOntologies() {
for ( AbstractOntologyService serv : this.ontologyServices ) {
serv.startInitializationThread( true, true );
}
}
@Override
public void removeBioMaterialStatement( Long characterId, BioMaterial bm ) {
Characteristic vc = characteristicService.load( characterId );
if ( vc == null )
throw new IllegalArgumentException( "No characteristic with id=" + characterId + " was foundF" );
bm.getCharacteristics().remove( vc );
characteristicService.remove( characterId );
}
@Override
public void saveBioMaterialStatement( Characteristic vc, BioMaterial bm ) {
OntologyServiceImpl.log.debug( "Vocab Characteristic: " + vc );
vc.setEvidenceCode( GOEvidenceCode.IC ); // manually added characteristic
Set<Characteristic> chars = new HashSet<>();
chars.add( vc );
Collection<Characteristic> current = bm.getCharacteristics();
if ( current == null )
current = new HashSet<>( chars );
else
current.addAll( chars );
for ( Characteristic characteristic : chars ) {
OntologyServiceImpl.log.info( "Adding characteristic to " + bm + " : " + characteristic );
}
bm.setCharacteristics( current );
bioMaterialService.update( bm );
}
@Override
public void addExpressionExperimentStatement( Characteristic vc, ExpressionExperiment ee ) {
if ( vc == null ) {
throw new IllegalArgumentException( "Null characteristic" );
}
if ( StringUtils.isBlank( vc.getCategory() ) ) {
throw new IllegalArgumentException( "Must provide a category" );
}
if ( StringUtils.isBlank( vc.getValue() ) ) {
throw new IllegalArgumentException( "Must provide a value" );
}
if ( vc.getEvidenceCode() == null ) {
vc.setEvidenceCode( GOEvidenceCode.IC ); // assume: manually added characteristic
}
if ( StringUtils.isNotBlank( vc.getValueUri() ) && this.isObsolete( vc.getValueUri() ) ) {
throw new IllegalArgumentException( vc + " is an obsolete term! Not saving." );
}
if ( ee == null )
throw new IllegalArgumentException( "Experiment cannot be null" );
OntologyServiceImpl.log
.info( "Adding characteristic '" + vc.getValue() + "' to " + ee.getShortName() + " (ID=" + ee.getId()
+ ") : " + vc );
ee.getCharacteristics().add( vc );
}
@Override
public void sort( List<CharacteristicValueObject> characteristics ) {
Collections.sort( characteristics, new CharacteristicComparator() );
}
/**
* Convert raw ontology resources into Characteristics.
*/
@Override
public Collection<Characteristic> termsToCharacteristics( final Collection<? extends OntologyResource> terms ) {
Collection<Characteristic> results = new HashSet<>();
if ( ( terms == null ) || ( terms.isEmpty() ) )
return results;
for ( OntologyResource term : terms ) {
if ( term == null )
continue;
Characteristic vc = this.termToCharacteristic( term );
if ( vc == null )
continue;
results.add( vc );
}
OntologyServiceImpl.log.debug( "returning " + results.size() + " terms after filter" );
return results;
}
@Override
public Map<String, CharacteristicValueObject> countObsoleteOccurrences( int start, int stop, int step ) {
Map<String, CharacteristicValueObject> vos = new HashMap<>();
int minId = start;
int maxId = step;
int nullCnt = 0;
int obsoleteCnt = 0;
// Loading all characteristics in steps
while ( maxId < stop ) {
OntologyServiceImpl.log.info( "Checking characteristics with IDs between " + minId + " and " + maxId );
List<Long> ids = new ArrayList<>( step );
for ( int i = minId; i < maxId + 1; i++ ) {
ids.add( ( long ) i );
}
minId = maxId + 1;
maxId += step;
Collection<Characteristic> chars = characteristicService.load( ids );
if ( chars == null || chars.isEmpty() ) {
OntologyServiceImpl.log.info( "No characteristics in the current ID range, moving on." );
continue;
}
OntologyServiceImpl.log.info( "Found " + chars.size()
+ " characteristics in the current ID range, checking for obsoletes." );
// Detect obsoletes
for ( Characteristic ch : chars ) {
if ( StringUtils.isBlank( ch.getValueUri() ) ) {
nullCnt++;
} else if ( this.isObsolete( ch.getValueUri() ) ) {
String key = this.foundValueKey( ch );
if ( !vos.containsKey( key ) ) {
vos.put( key, new CharacteristicValueObject( ch ) );
}
vos.get( key ).incrementOccurrenceCount();
obsoleteCnt++;
OntologyServiceImpl.log.info( "Found obsolete term: " + ch.getValue() + " / " + ch.getValueUri() );
}
}
ids.clear();
chars.clear();
}
OntologyServiceImpl.log.info( "Terms with empty uri: " + nullCnt );
OntologyServiceImpl.log.info( "Obsolete terms found: " + obsoleteCnt );
return vos;
}
private Characteristic termToCharacteristic( OntologyResource res ) {
if ( this.isObsolete( res.getUri() ) ) {
OntologyServiceImpl.log.warn( "Skipping an obsolete term: " + res.getLabel() + " / " + res.getUri() );
return null;
}
Characteristic vc = Characteristic.Factory.newInstance();
if ( res instanceof OntologyTerm ) {
OntologyTerm term = ( OntologyTerm ) res;
vc.setValue( term.getTerm() );
vc.setValueUri( term.getUri() );
vc.setDescription( term.getComment() );
} else if ( res instanceof OntologyIndividual ) {
OntologyIndividual indi = ( OntologyIndividual ) res;
vc.setValue( indi.getLabel() );
vc.setValueUri( indi.getUri() );
vc.setDescription( "Individual" );
} else {
OntologyServiceImpl.log.warn( "This is neither an OntologyTerm or an OntologyIndividual: " + res );
return null;
}
if ( vc.getValue() == null ) {
OntologyServiceImpl.log
.warn( "Skipping a characteristic with no value: " + res.getLabel() + " / " + res.getUri() );
return null;
}
return vc;
}
/**
* Given a collection of ontology terms converts them to a collection of Characteristics
*/
private Collection<Characteristic> convert( final Collection<OntologyResource> resources ) {
Collection<Characteristic> converted = new HashSet<>();
if ( ( resources == null ) || ( resources.isEmpty() ) )
return converted;
for ( OntologyResource res : resources ) {
Characteristic vc = Characteristic.Factory.newInstance();
// If there is no URI we don't want to send it back (ie useless)
if ( ( res.getUri() == null ) || StringUtils.isEmpty( res.getUri() ) )
continue;
if ( res instanceof OntologyTerm ) {
OntologyTerm term = ( OntologyTerm ) res;
vc.setValue( term.getTerm() );
vc.setValueUri( term.getUri() );
vc.setDescription( term.getComment() );
}
if ( res instanceof OntologyIndividual ) {
OntologyIndividual indi = ( OntologyIndividual ) res;
vc.setValue( indi.getLabel() );
vc.setValueUri( indi.getUri() );
vc.setDescription( "Individual" );
}
converted.add( vc );
}
return converted;
}
private void countOccurrences( String queryString, Map<String, CharacteristicValueObject> previouslyUsedInSystem ) {
StopWatch watch = new StopWatch();
watch.start();
Collection<Characteristic> foundChars = characteristicService.findByValue( queryString );
/*
* Want to flag in the web interface that these are already used by Gemma (also ignore capitalization; category
* is always ignored; remove duplicates.)
*/
for ( Characteristic characteristic : foundChars ) {
// count up number of usages; see bug 3897
String key = this.foundValueKey( characteristic );
if ( previouslyUsedInSystem.containsKey( key ) ) {
previouslyUsedInSystem.get( key ).incrementOccurrenceCount();
continue;
}
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log.debug( "saw " + key + " (" + key + ") for " + characteristic );
CharacteristicValueObject vo = new CharacteristicValueObject( characteristic );
vo.setCategory( null );
vo.setCategoryUri( null ); // to avoid us counting separately by category.
vo.setAlreadyPresentInDatabase( true );
vo.incrementOccurrenceCount();
previouslyUsedInSystem.put( key, vo );
}
if ( OntologyServiceImpl.log.isDebugEnabled() || ( watch.getTime() > 100
&& previouslyUsedInSystem.size() > 0 ) )
OntologyServiceImpl.log
.info( "found " + previouslyUsedInSystem.size() + " matching characteristics used in the database"
+ " in " + watch.getTime() + " ms " + " Filtered from initial set of " + foundChars
.size() );
}
/**
* given a collection of characteristics add them to the correct List
*/
private Collection<CharacteristicValueObject> findCharacteristicsFromOntology( String searchQuery,
boolean useNeuroCartaOntology,
Map<String, CharacteristicValueObject> characteristicFromDatabaseWithValueUri ) {
Collection<CharacteristicValueObject> characteristicsFromOntology = new HashSet<>();
// in neurocarta we don't need to search all Ontologies
Collection<AbstractOntologyService> ontologyServicesToUse = new HashSet<>();
if ( useNeuroCartaOntology ) {
ontologyServicesToUse.add( this.nifstdOntologyService );
ontologyServicesToUse.add( this.fmaOntologyService );
ontologyServicesToUse.add( this.obiService );
} else {
ontologyServicesToUse = this.ontologyServices;
}
// search all Ontology
for ( AbstractOntologyService ontologyService : ontologyServicesToUse ) {
Collection<OntologyTerm> ontologyTerms = ontologyService.findTerm( searchQuery );
for ( OntologyTerm ontologyTerm : ontologyTerms ) {
// if the ontology term wasnt already found in the database
if ( characteristicFromDatabaseWithValueUri.get( ontologyTerm.getUri() ) == null ) {
CharacteristicValueObject phenotype = new CharacteristicValueObject( -1L,
ontologyTerm.getLabel().toLowerCase(), ontologyTerm.getUri() );
characteristicsFromOntology.add( phenotype );
}
}
}
return characteristicsFromOntology;
}
private String foundValueKey( Characteristic c ) {
if ( StringUtils.isNotBlank( c.getValueUri() ) ) {
return c.getValueUri().toLowerCase();
}
return c.getValue().toLowerCase();
}
private String foundValueKey( CharacteristicValueObject c ) {
if ( c.getValueUri() != null && StringUtils.isNotBlank( c.getValueUri() ) ) {
return c.getValueUri().toLowerCase();
}
return c.getValue().toLowerCase();
}
/**
* Allow us to store gene information as a characteristic associated with our entities. This doesn't work so well
* for non-ncbi genes.
*/
private Characteristic gene2Characteristic( GeneValueObject g ) {
Characteristic vc = Characteristic.Factory.newInstance();
vc.setCategory( "gene" );
vc.setCategoryUri( "http://purl.org/commons/hcls/gene" );
vc.setValue( g.getOfficialSymbol() + " [" + g.getTaxonCommonName() + "]" + " " + g.getOfficialName() );
vc.setDescription( g.toString() );
if ( g.getNcbiId() != null ) {
vc.setValueUri( "http://purl.org/commons/record/ncbi_gene/" + g.getNcbiId() );
}
return vc;
}
private synchronized void initializeCategoryTerms() {
URL termUrl = OntologyServiceImpl.class.getResource( "/ubic/gemma/core/ontology/EFO.factor.categories.txt" );
OntologyServiceImpl.categoryTerms = new ConcurrentHashSet<>();
try (BufferedReader reader = new BufferedReader( new InputStreamReader( termUrl.openStream() ) )) {
String line;
boolean warned = false;
while ( ( line = reader.readLine() ) != null ) {
if ( line.startsWith( "#" ) || StringUtils.isEmpty( line ) )
continue;
String[] f = StringUtils.split( line, '\t' );
if ( f.length < 2 ) {
continue;
}
OntologyTerm t = this.getTerm( f[0] );
if ( t == null ) {
// this is not great. We might want to let it expire and redo it later if the ontology
// becomes
// available. Inference will not be available.
if ( !warned ) {
OntologyServiceImpl.log
.info( "Ontology needed is not loaded? Using light-weight placeholder for " + f[0]
+ " (further warnings hidden)" );
warned = true;
}
t = new OntologyTermSimple( f[0], f[1] );
}
OntologyServiceImpl.categoryTerms.add( t );
}
} catch ( IOException ioe ) {
OntologyServiceImpl.log
.error( "Error reading from term list '" + termUrl + "'; returning general term list", ioe );
OntologyServiceImpl.categoryTerms = null;
}
OntologyServiceImpl.categoryTerms = Collections.unmodifiableCollection( OntologyServiceImpl.categoryTerms );
}
/**
* given a collection of characteristics add them to the correct List
*/
private void putCharacteristicsIntoSpecificList( String searchQuery,
Collection<CharacteristicValueObject> characteristics,
Collection<CharacteristicValueObject> characteristicsWithExactMatch,
Collection<CharacteristicValueObject> characteristicsStartWithQuery,
Collection<CharacteristicValueObject> characteristicsSubstring,
Collection<CharacteristicValueObject> characteristicsNoRuleFound ) {
for ( CharacteristicValueObject cha : characteristics ) {
// Case 1, exact match
if ( cha.getValue().equalsIgnoreCase( searchQuery ) ) {
characteristicsWithExactMatch.add( cha );
}
// Case 2, starts with a substring of the word
else if ( cha.getValue().toLowerCase().startsWith( searchQuery.toLowerCase() ) ) {
characteristicsStartWithQuery.add( cha );
}
// Case 3, contains a substring of the word
else if ( cha.getValue().toLowerCase().contains( searchQuery.toLowerCase() ) ) {
characteristicsSubstring.add( cha );
} else {
characteristicsNoRuleFound.add( cha );
}
}
}
/**
* Look for genes, but only for certain category Uris (genotype, etc.)
*
* @param taxon okay if null, but then all matches returned.
* @param searchResults added to this
*/
private void searchForGenes( String queryString, Taxon taxon,
Collection<CharacteristicValueObject> searchResults ) {
SearchSettings ss = SearchSettings.Factory.newInstance();
ss.setQuery( queryString );
ss.noSearches();
ss.setTaxon( taxon );
ss.setSearchGenes( true );
Map<Class<?>, List<SearchResult>> geneResults = this.searchService.search( ss, false, false );
if ( geneResults.containsKey( Gene.class ) ) {
for ( SearchResult sr : geneResults.get( Gene.class ) ) {
GeneValueObject g = this.geneService.loadValueObjectById( sr.getResultId() );
if ( g == null ) {
throw new IllegalStateException(
"There is no gene with ID=" + sr.getResultId() + " (in response to search that yielded: " + sr + ")" );
}
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log.debug( "Search for " + queryString + " returned: " + g );
searchResults.add( new CharacteristicValueObject( this.gene2Characteristic( g ) ) );
}
}
}
/**
* @param alreadyUsedResults items already in the system; remove singleton free-text terms.
* @param otherResults other results
* @param searchTerm the query
*/
private Collection<CharacteristicValueObject> sort( Map<String, CharacteristicValueObject> alreadyUsedResults,
Collection<CharacteristicValueObject> otherResults, String searchTerm ) {
/*
* Organize the list into 3 parts. Want to get the exact match showing up on top
*/
List<CharacteristicValueObject> sortedResultsExact = new ArrayList<>();
List<CharacteristicValueObject> sortedResultsStartsWith = new ArrayList<>();
List<CharacteristicValueObject> sortedResultsBottom = new ArrayList<>();
Set<String> foundValues = new HashSet<>();
for ( String key : alreadyUsedResults.keySet() ) {
CharacteristicValueObject c = alreadyUsedResults.get( key );
if ( foundValues.contains( key ) )
continue;
foundValues.add( key );
// don't show singletons of free-text terms.
if ( c.getValueUri() == null && c.getNumTimesUsed() < 2 ) {
continue;
}
//Skip obsolete terms
if ( this.isObsolete( c.getValueUri() ) ) {
OntologyServiceImpl.log.warn( "Skipping an obsolete term: " + c.getValue() + " / " + c.getValueUri() );
continue;
}
this.addToAppropriateList( searchTerm, sortedResultsExact, sortedResultsStartsWith, sortedResultsBottom,
c );
}
for ( CharacteristicValueObject c : otherResults ) {
assert c.getValueUri() != null;
String key = this.foundValueKey( c );
if ( foundValues.contains( key ) )
continue;
foundValues.add( key );
this.addToAppropriateList( searchTerm, sortedResultsExact, sortedResultsStartsWith, sortedResultsBottom,
c );
}
this.sort( sortedResultsExact );
this.sort( sortedResultsStartsWith );
this.sort( sortedResultsBottom );
List<CharacteristicValueObject> sortedTerms = new ArrayList<>( foundValues.size() );
sortedTerms.addAll( sortedResultsExact );
sortedTerms.addAll( sortedResultsStartsWith );
sortedTerms.addAll( sortedResultsBottom );
return sortedTerms;
}
private void addToAppropriateList( String searchTerm, List<CharacteristicValueObject> sortedResultsExact,
List<CharacteristicValueObject> sortedResultsStartsWith,
List<CharacteristicValueObject> sortedResultsBottom, CharacteristicValueObject c ) {
if ( c.getValue().equalsIgnoreCase( searchTerm ) ) {
sortedResultsExact.add( c );
} else if ( c.getValue().toLowerCase().startsWith( searchTerm.toLowerCase() ) || c.getValueUri() != null ) {
sortedResultsStartsWith.add( c );
} else {
sortedResultsBottom.add( c );
}
}
/**
* Sorts Characteristics in our preferred ordering
*/
private class CharacteristicComparator implements Comparator<CharacteristicValueObject> {
@Override
public int compare( CharacteristicValueObject o1, CharacteristicValueObject o2 ) {
// sort by whether used or not, and then by URI; terms without URIs are listed later; break ties by length
if ( o1.getValueUri() != null ) {
if ( o2.getValueUri() != null ) {
// both have uri, break tie.
if ( o1.isAlreadyPresentInDatabase() ) {
if ( o2.isAlreadyPresentInDatabase() ) {
// both are used, break tie by who is used most.
if ( o1.getNumTimesUsed() > o2.getNumTimesUsed() ) {
return -1;
} else if ( o2.getNumTimesUsed() > o1.getNumTimesUsed() ) {
return 1;
}
// both are used same number of times, compare by length (shorter better, typically...)
if ( o1.getValue().length() < o2.getValue().length() ) {
return -1;
} else if ( o1.getValue().length() > o2.getValue().length() ) {
return 1;
}
// equal length, compare by lexig. value.
return o1.getValue().toLowerCase().compareTo( o2.getValue().toLowerCase() );
}
// o1 is used, o2 is not; o1 should be first.
return -1;
} else if ( o2.isAlreadyPresentInDatabase() ) {
// o2 is used and o1 is not; o2 should be first.
return 1;
}
}
// o1 has uri, o2 does not.
return -1;
} else if ( o2.getValueUri() != null ) {
// we know o1 does not have a uri, o2 goes first.
return 1;
}
// neither has URI. By definition these are in the database, so we just rank by length/text
if ( o1.getValue().length() < o2.getValue().length() ) {
return -1;
} else if ( o1.getValue().length() > o2.getValue().length() ) {
return 1;
}
// equal length, compare by lexig. value.
return o1.getValue().toLowerCase().compareTo( o2.getValue().toLowerCase() );
}
}
} | gemma-core/src/main/java/ubic/gemma/core/ontology/OntologyServiceImpl.java | /*
* The Gemma project
*
* Copyright (c) 2007 University of British Columbia
*
* 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 ubic.gemma.core.ontology;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.compass.core.util.concurrent.ConcurrentHashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.basecode.ontology.model.OntologyIndividual;
import ubic.basecode.ontology.model.OntologyResource;
import ubic.basecode.ontology.model.OntologyTerm;
import ubic.basecode.ontology.model.OntologyTermSimple;
import ubic.basecode.ontology.providers.*;
import ubic.basecode.ontology.search.OntologySearch;
import ubic.basecode.util.Configuration;
import ubic.gemma.core.genome.gene.service.GeneService;
import ubic.gemma.core.ontology.providers.GemmaOntologyService;
import ubic.gemma.core.ontology.providers.GeneOntologyService;
import ubic.gemma.core.search.SearchResult;
import ubic.gemma.core.search.SearchService;
import ubic.gemma.model.association.GOEvidenceCode;
import ubic.gemma.model.common.description.Characteristic;
import ubic.gemma.model.common.search.SearchSettings;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.gene.GeneValueObject;
import ubic.gemma.model.genome.gene.phenotype.valueObject.CharacteristicValueObject;
import ubic.gemma.persistence.service.common.description.CharacteristicService;
import ubic.gemma.persistence.service.expression.biomaterial.BioMaterialService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
/**
* Has a static method for finding out which ontologies are loaded into the system and a general purpose find method
* that delegates to the many ontology services. NOTE: Logging messages from this service are important for tracking
* changes to annotations.
*
* @author pavlidis
*/
@Service
public class OntologyServiceImpl implements OntologyService {
/**
* Throttle how many ontology terms we retrieve. We search the ontologies in a favored order, so we can stop when we
* find "enough stuff".
*/
private static final int MAX_TERMS_TO_FETCH = 200;
private static final Log log = LogFactory.getLog( OntologyServiceImpl.class.getName() );
private static Collection<OntologyTerm> categoryTerms = null;
private final CellLineOntologyService cellLineOntologyService = new CellLineOntologyService();
private final CellTypeOntologyService cellTypeOntologyService = new CellTypeOntologyService();
private final ChebiOntologyService chebiOntologyService = new ChebiOntologyService();
private final DiseaseOntologyService diseaseOntologyService = new DiseaseOntologyService();
private final ExperimentalFactorOntologyService experimentalFactorOntologyService = new ExperimentalFactorOntologyService();
@Deprecated
private final FMAOntologyService fmaOntologyService = new FMAOntologyService();
private final GemmaOntologyService gemmaOntologyService = new GemmaOntologyService();
private final HumanDevelopmentOntologyService humanDevelopmentOntologyService = new HumanDevelopmentOntologyService();
private final HumanPhenotypeOntologyService humanPhenotypeOntologyService = new HumanPhenotypeOntologyService();
private final MammalianPhenotypeOntologyService mammalianPhenotypeOntologyService = new MammalianPhenotypeOntologyService();
private final MouseDevelopmentOntologyService mouseDevelopmentOntologyService = new MouseDevelopmentOntologyService();
@Deprecated
private final NIFSTDOntologyService nifstdOntologyService = new NIFSTDOntologyService();
private final ObiService obiService = new ObiService();
private final Collection<AbstractOntologyService> ontologyServices = new ArrayList<>();
private final SequenceOntologyService sequenceOntologyService = new SequenceOntologyService();
private final UberonOntologyService uberonOntologyService = new UberonOntologyService();
private BioMaterialService bioMaterialService;
private CharacteristicService characteristicService;
private SearchService searchService;
private GeneOntologyService geneOntologyService;
private GeneService geneService;
@Autowired
public void setBioMaterialService( BioMaterialService bioMaterialService ) {
this.bioMaterialService = bioMaterialService;
}
@Autowired
public void setCharacteristicService( CharacteristicService characteristicService ) {
this.characteristicService = characteristicService;
}
@Autowired
public void setSearchService( SearchService searchService ) {
this.searchService = searchService;
}
@Autowired
public void setGeneOntologyService( GeneOntologyService geneOntologyService ) {
this.geneOntologyService = geneOntologyService;
}
@Autowired
public void setGeneService( GeneService geneService ) {
this.geneService = geneService;
}
@Override
public void afterPropertiesSet() {
this.ontologyServices.add( this.gemmaOntologyService );
this.ontologyServices.add( this.experimentalFactorOntologyService );
this.ontologyServices.add( this.obiService );
this.ontologyServices.add( this.nifstdOntologyService ); // DEPRECATED
this.ontologyServices.add( this.fmaOntologyService ); // DEPRECATED
this.ontologyServices.add( this.diseaseOntologyService );
this.ontologyServices.add( this.cellTypeOntologyService );
this.ontologyServices.add( this.chebiOntologyService );
this.ontologyServices.add( this.mammalianPhenotypeOntologyService );
this.ontologyServices.add( this.humanPhenotypeOntologyService );
this.ontologyServices.add( this.mouseDevelopmentOntologyService );
this.ontologyServices.add( this.humanDevelopmentOntologyService );
this.ontologyServices.add( this.sequenceOntologyService );
this.ontologyServices.add( this.cellLineOntologyService );
this.ontologyServices.add( this.uberonOntologyService );
/*
* If this load.ontologies is NOT configured, we go ahead (per-ontology config will be checked).
*/
String doLoad = Configuration.getString( "load.ontologies" );
if ( StringUtils.isBlank( doLoad ) || Configuration.getBoolean( "load.ontologies" ) ) {
for ( AbstractOntologyService serv : this.ontologyServices ) {
serv.startInitializationThread( false, false );
}
} else {
log.info( "Auto-loading of ontologies suppressed" );
}
}
@SuppressWarnings({ "unused", "WeakerAccess" }) // Possible external use
public void countOccurrences( Collection<CharacteristicValueObject> searchResults,
Map<String, CharacteristicValueObject> previouslyUsedInSystem ) {
StopWatch watch = new StopWatch();
watch.start();
Set<String> uris = new HashSet<>();
for ( CharacteristicValueObject cvo : searchResults ) {
uris.add( cvo.getValueUri() );
}
Collection<Characteristic> existingCharacteristicsUsingTheseTerms = characteristicService.findByUri( uris );
for ( Characteristic c : existingCharacteristicsUsingTheseTerms ) {
// count up number of usages; see bug 3897
String key = this.foundValueKey( c );
if ( previouslyUsedInSystem.containsKey( key ) ) {
previouslyUsedInSystem.get( key ).incrementOccurrenceCount();
continue;
}
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log.debug( "saw " + key + " (" + key + ")" );
CharacteristicValueObject vo = new CharacteristicValueObject( c );
vo.setCategory( null );
vo.setCategoryUri( null ); // to avoid us counting separately by category.
vo.setAlreadyPresentInDatabase( true );
vo.incrementOccurrenceCount();
previouslyUsedInSystem.put( key, vo );
}
if ( OntologyServiceImpl.log.isDebugEnabled() || ( watch.getTime() > 100
&& previouslyUsedInSystem.size() > 0 ) )
OntologyServiceImpl.log
.info( "found " + previouslyUsedInSystem.size() + " matching characteristics used in the database"
+ " in " + watch.getTime() + " ms " + " Filtered from initial set of "
+ existingCharacteristicsUsingTheseTerms.size() );
}
/**
* Using the ontology and values in the database, for a search searchQuery given by the client give an ordered list
* of possible choices
*/
@Override
public Collection<CharacteristicValueObject> findExperimentsCharacteristicTags( String searchQueryString,
boolean useNeuroCartaOntology ) {
String searchQuery = OntologySearch.stripInvalidCharacters( searchQueryString );
if ( searchQuery.length() < 3 ) {
return new HashSet<>();
}
// this will do like %search%
Collection<CharacteristicValueObject> characteristicsFromDatabase = CharacteristicValueObject
.characteristic2CharacteristicVO( this.characteristicService.findByValue( "%" + searchQuery ) );
Map<String, CharacteristicValueObject> characteristicFromDatabaseWithValueUri = new HashMap<>();
Collection<CharacteristicValueObject> characteristicFromDatabaseFreeText = new HashSet<>();
for ( CharacteristicValueObject characteristicInDatabase : characteristicsFromDatabase ) {
// flag to let know that it was found in the database
characteristicInDatabase.setAlreadyPresentInDatabase( true );
if ( characteristicInDatabase.getValueUri() != null && !characteristicInDatabase.getValueUri()
.equals( "" ) ) {
characteristicFromDatabaseWithValueUri
.put( characteristicInDatabase.getValueUri(), characteristicInDatabase );
} else {
// free txt, no value uri
characteristicFromDatabaseFreeText.add( characteristicInDatabase );
}
}
// search the ontology for the given searchTerm, but if already found in the database dont add it again
Collection<CharacteristicValueObject> characteristicsFromOntology = this
.findCharacteristicsFromOntology( searchQuery, useNeuroCartaOntology,
characteristicFromDatabaseWithValueUri );
// order to show the the term: 1-exactMatch, 2-startWith, 3-substring and 4- no rule
// order to show values for each List : 1-From database with Uri, 2- from Ontology, 3- from from database with
// no Uri
Collection<CharacteristicValueObject> characteristicsWithExactMatch = new ArrayList<>();
Collection<CharacteristicValueObject> characteristicsStartWithQuery = new ArrayList<>();
Collection<CharacteristicValueObject> characteristicsSubstring = new ArrayList<>();
Collection<CharacteristicValueObject> characteristicsNoRuleFound = new ArrayList<>();
// from the database with a uri
this.putCharacteristicsIntoSpecificList( searchQuery, characteristicFromDatabaseWithValueUri.values(),
characteristicsWithExactMatch, characteristicsStartWithQuery, characteristicsSubstring,
characteristicsNoRuleFound );
// from the ontology
this.putCharacteristicsIntoSpecificList( searchQuery, characteristicsFromOntology,
characteristicsWithExactMatch, characteristicsStartWithQuery, characteristicsSubstring,
characteristicsNoRuleFound );
// from the database with no uri
this.putCharacteristicsIntoSpecificList( searchQuery, characteristicFromDatabaseFreeText,
characteristicsWithExactMatch, characteristicsStartWithQuery, characteristicsSubstring,
characteristicsNoRuleFound );
List<CharacteristicValueObject> allCharacteristicsFound = new ArrayList<>();
allCharacteristicsFound.addAll( characteristicsWithExactMatch );
allCharacteristicsFound.addAll( characteristicsStartWithQuery );
allCharacteristicsFound.addAll( characteristicsSubstring );
allCharacteristicsFound.addAll( characteristicsNoRuleFound );
// limit the size of the returned phenotypes to 100 terms
if ( allCharacteristicsFound.size() > 100 ) {
return allCharacteristicsFound.subList( 0, 100 );
}
return allCharacteristicsFound;
}
@Override
public Collection<OntologyIndividual> findIndividuals( String givenSearch ) {
String query = OntologySearch.stripInvalidCharacters( givenSearch );
Collection<OntologyIndividual> results = new HashSet<>();
for ( AbstractOntologyService ontology : ontologyServices ) {
Collection<OntologyIndividual> found = ontology.findIndividuals( query );
if ( found != null )
results.addAll( found );
}
return results;
}
@Override
public Collection<Characteristic> findTermAsCharacteristic( String search ) {
String query = OntologySearch.stripInvalidCharacters( search );
Collection<Characteristic> results = new HashSet<>();
if ( StringUtils.isBlank( query ) ) {
return results;
}
for ( AbstractOntologyService ontology : ontologyServices ) {
Collection<OntologyTerm> found = ontology.findTerm( query );
if ( found != null )
results.addAll( this.convert( new HashSet<OntologyResource>( found ) ) );
}
return results;
}
@Override
public Collection<OntologyTerm> findTerms( String search ) {
Collection<OntologyTerm> results = new HashSet<>();
/*
* URI input: just retrieve the term.
*/
if ( search.startsWith( "http://" ) ) {
for ( AbstractOntologyService ontology : ontologyServices ) {
if ( ontology.isOntologyLoaded() ) {
OntologyTerm found = ontology.getTerm( search );
if ( found != null ) {
results.add( found );
}
}
}
return results;
}
/*
* Other queries:
*/
String query = OntologySearch.stripInvalidCharacters( search );
if ( StringUtils.isBlank( query ) ) {
return results;
}
for ( AbstractOntologyService ontology : ontologyServices ) {
if ( ontology.isOntologyLoaded() ) {
Collection<OntologyTerm> found = ontology.findTerm( query );
if ( found != null ) {
for ( OntologyTerm t : found ) {
if ( !t.isTermObsolete() ) {
results.add( t );
}
}
}
}
}
if ( geneOntologyService.isReady() )
results.addAll( geneOntologyService.findTerm( search ) );
return results;
}
@Override
public Collection<CharacteristicValueObject> findTermsInexact( String givenQueryString, Taxon taxon ) {
if ( StringUtils.isBlank( givenQueryString ) )
return null;
StopWatch watch = new StopWatch();
watch.start();
String queryString = OntologySearch.stripInvalidCharacters( givenQueryString );
if ( StringUtils.isBlank( queryString ) ) {
OntologyServiceImpl.log.warn( "The query was not valid (ended up being empty): " + givenQueryString );
return new HashSet<>();
}
if ( OntologyServiceImpl.log.isDebugEnabled() ) {
OntologyServiceImpl.log
.debug( "starting findExactTerm for " + queryString + ". Timing information begins from here" );
}
Collection<? extends OntologyResource> results = null;
Collection<CharacteristicValueObject> searchResults = new HashSet<>();
Map<String, CharacteristicValueObject> previouslyUsedInSystem = new HashMap<>();
this.countOccurrences( queryString, previouslyUsedInSystem );
this.searchForGenes( queryString, taxon, searchResults );
for ( AbstractOntologyService service : this.ontologyServices ) {
if ( !service.isOntologyLoaded() )
continue;
try {
results = service.findResources( queryString );
} catch ( Exception e ) {
OntologyServiceImpl.log.warn( e.getMessage() ); // parse errors, etc.
}
if ( results == null || results.isEmpty() )
continue;
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log
.debug( "found " + results.size() + " from " + service.getClass().getSimpleName() + " in "
+ watch.getTime() + " ms" );
searchResults.addAll( CharacteristicValueObject
.characteristic2CharacteristicVO( this.termsToCharacteristics( results ) ) );
if ( searchResults.size() > OntologyServiceImpl.MAX_TERMS_TO_FETCH ) {
break;
}
}
this.countOccurrences( searchResults, previouslyUsedInSystem );
// get GO terms, if we don't already have a lot of possibilities. (might have to adjust this)
if ( searchResults.size() < OntologyServiceImpl.MAX_TERMS_TO_FETCH && geneOntologyService.isReady() ) {
searchResults.addAll( CharacteristicValueObject.characteristic2CharacteristicVO(
this.termsToCharacteristics( geneOntologyService.findTerm( queryString ) ) ) );
}
// Sort the results rather elaborately.
Collection<CharacteristicValueObject> sortedResults = this
.sort( previouslyUsedInSystem, searchResults, queryString );
if ( watch.getTime() > 1000 ) {
OntologyServiceImpl.log
.info( "Ontology term query for: " + givenQueryString + ": " + watch.getTime() + "ms" );
}
return sortedResults;
}
@Override
public Collection<OntologyTerm> getCategoryTerms() {
if ( !experimentalFactorOntologyService.isOntologyLoaded() ) {
OntologyServiceImpl.log.warn( "EFO is not loaded" );
}
/*
* Requires EFO, OBI and SO. If one of them isn't loaded, the terms are filled in with placeholders.
*/
if ( OntologyServiceImpl.categoryTerms == null || OntologyServiceImpl.categoryTerms.isEmpty() ) {
this.initializeCategoryTerms();
}
return OntologyServiceImpl.categoryTerms;
}
@Override
public CellLineOntologyService getCellLineOntologyService() {
return cellLineOntologyService;
}
@Override
public CellTypeOntologyService getCellTypeOntologyService() {
return cellTypeOntologyService;
}
@Override
public GemmaOntologyService getGemmaOntologyService() {
return gemmaOntologyService;
}
@Override
public HumanDevelopmentOntologyService getHumanDevelopmentOntologyService() {
return humanDevelopmentOntologyService;
}
@Override
public MouseDevelopmentOntologyService getMouseDevelopmentOntologyService() {
return mouseDevelopmentOntologyService;
}
@Override
public ChebiOntologyService getChebiOntologyService() {
return chebiOntologyService;
}
@Override
public DiseaseOntologyService getDiseaseOntologyService() {
return diseaseOntologyService;
}
@Override
public ExperimentalFactorOntologyService getExperimentalFactorOntologyService() {
return experimentalFactorOntologyService;
}
@Override
public HumanPhenotypeOntologyService getHumanPhenotypeOntologyService() {
return humanPhenotypeOntologyService;
}
@Override
public MammalianPhenotypeOntologyService getMammalianPhenotypeOntologyService() {
return mammalianPhenotypeOntologyService;
}
@Override
public ObiService getObiService() {
return obiService;
}
@Override
public UberonOntologyService getUberonService() {
return this.uberonOntologyService;
}
@Override
public OntologyResource getResource( String uri ) {
for ( AbstractOntologyService ontology : ontologyServices ) {
OntologyResource resource = ontology.getResource( uri );
if ( resource != null )
return resource;
}
return null;
}
@Override
public SequenceOntologyService getSequenceOntologyService() {
return this.sequenceOntologyService;
}
@Override
public OntologyTerm getTerm( String uri ) {
for ( AbstractOntologyService ontology : ontologyServices ) {
OntologyTerm term = ontology.getTerm( uri );
if ( term != null )
return term;
}
// TODO: doesn't include GO.
return null;
}
/**
* @return true if the Uri is an ObsoleteClass. This will only work if the ontology in question is loaded.
*/
@Override
public boolean isObsolete( String uri ) {
if ( uri == null )
return false;
OntologyTerm t = this.getTerm( uri );
return t != null && t.isTermObsolete();
}
@Override
public void reindexAllOntologies() {
for ( AbstractOntologyService serv : this.ontologyServices ) {
if ( serv.isOntologyLoaded() ) {
OntologyServiceImpl.log.info( "Reindexing: " + serv );
try {
serv.index( true );
} catch ( Exception e ) {
OntologyServiceImpl.log.error( "Failed to index " + serv + ": " + e.getMessage(), e );
}
} else {
if ( serv.isEnabled() )
OntologyServiceImpl.log
.info( "Not available for reindexing (not enabled or finished initialization): " + serv );
}
}
}
@Override
public void reinitializeAllOntologies() {
for ( AbstractOntologyService serv : this.ontologyServices ) {
serv.startInitializationThread( true, true );
}
}
@Override
public void removeBioMaterialStatement( Long characterId, BioMaterial bm ) {
Characteristic vc = characteristicService.load( characterId );
if ( vc == null )
throw new IllegalArgumentException( "No characteristic with id=" + characterId + " was foundF" );
bm.getCharacteristics().remove( vc );
characteristicService.remove( characterId );
}
@Override
public void saveBioMaterialStatement( Characteristic vc, BioMaterial bm ) {
OntologyServiceImpl.log.debug( "Vocab Characteristic: " + vc );
vc.setEvidenceCode( GOEvidenceCode.IC ); // manually added characteristic
Set<Characteristic> chars = new HashSet<>();
chars.add( vc );
Collection<Characteristic> current = bm.getCharacteristics();
if ( current == null )
current = new HashSet<>( chars );
else
current.addAll( chars );
for ( Characteristic characteristic : chars ) {
OntologyServiceImpl.log.info( "Adding characteristic to " + bm + " : " + characteristic );
}
bm.setCharacteristics( current );
bioMaterialService.update( bm );
}
@Override
public void addExpressionExperimentStatement( Characteristic vc, ExpressionExperiment ee ) {
if ( vc == null ) {
throw new IllegalArgumentException( "Null characteristic" );
}
if ( StringUtils.isBlank( vc.getCategory() ) ) {
throw new IllegalArgumentException( "Must provide a category" );
}
if ( StringUtils.isBlank( vc.getValue() ) ) {
throw new IllegalArgumentException( "Must provide a value" );
}
if ( vc.getEvidenceCode() == null ) {
vc.setEvidenceCode( GOEvidenceCode.IC ); // assume: manually added characteristic
}
if ( StringUtils.isNotBlank( vc.getValueUri() ) && this.isObsolete( vc.getValueUri() ) ) {
throw new IllegalArgumentException( vc + " is an obsolete term! Not saving." );
}
if ( ee == null )
throw new IllegalArgumentException( "Experiment cannot be null" );
OntologyServiceImpl.log
.info( "Adding characteristic '" + vc.getValue() + "' to " + ee.getShortName() + " (ID=" + ee.getId()
+ ") : " + vc );
ee.getCharacteristics().add( vc );
}
@Override
public void sort( List<CharacteristicValueObject> characteristics ) {
Collections.sort( characteristics, new CharacteristicComparator() );
}
/**
* Convert raw ontology resources into Characteristics.
*/
@Override
public Collection<Characteristic> termsToCharacteristics( final Collection<? extends OntologyResource> terms ) {
Collection<Characteristic> results = new HashSet<>();
if ( ( terms == null ) || ( terms.isEmpty() ) )
return results;
for ( OntologyResource term : terms ) {
if ( term == null )
continue;
Characteristic vc = this.termToCharacteristic( term );
if ( vc == null )
continue;
results.add( vc );
}
OntologyServiceImpl.log.debug( "returning " + results.size() + " terms after filter" );
return results;
}
@Override
public Map<String, CharacteristicValueObject> countObsoleteOccurrences( int start, int stop, int step ) {
Map<String, CharacteristicValueObject> vos = new HashMap<>();
int minId = start;
int maxId = step;
int nullCnt = 0;
int obsoleteCnt = 0;
// Loading all characteristics in steps
while ( maxId < stop ) {
OntologyServiceImpl.log.info( "Checking characteristics with IDs between " + minId + " and " + maxId );
List<Long> ids = new ArrayList<>( step );
for ( int i = minId; i < maxId + 1; i++ ) {
ids.add( ( long ) i );
}
minId = maxId + 1;
maxId += step;
Collection<Characteristic> chars = characteristicService.load( ids );
if ( chars == null || chars.isEmpty() ) {
OntologyServiceImpl.log.info( "No characteristics in the current ID range, moving on." );
continue;
}
OntologyServiceImpl.log.info( "Found " + chars.size()
+ " characteristics in the current ID range, checking for obsoletes." );
// Detect obsoletes
for ( Characteristic ch : chars ) {
if ( StringUtils.isBlank( ch.getValueUri() ) ) {
nullCnt++;
} else if ( this.isObsolete( ch.getValueUri() ) ) {
String key = this.foundValueKey( ch );
if ( !vos.containsKey( key ) ) {
vos.put( key, new CharacteristicValueObject( ch ) );
}
vos.get( key ).incrementOccurrenceCount();
obsoleteCnt++;
OntologyServiceImpl.log.info( "Found obsolete term: " + ch.getValue() + " / " + ch.getValueUri() );
}
}
ids.clear();
chars.clear();
}
OntologyServiceImpl.log.info( "Terms with empty uri: " + nullCnt );
OntologyServiceImpl.log.info( "Obsolete terms found: " + obsoleteCnt );
return vos;
}
private Characteristic termToCharacteristic( OntologyResource res ) {
if ( this.isObsolete( res.getUri() ) ) {
OntologyServiceImpl.log.warn( "Skipping an obsolete term: " + res.getLabel() + " / " + res.getUri() );
return null;
}
Characteristic vc = Characteristic.Factory.newInstance();
if ( res instanceof OntologyTerm ) {
OntologyTerm term = ( OntologyTerm ) res;
vc.setValue( term.getTerm() );
vc.setValueUri( term.getUri() );
vc.setDescription( term.getComment() );
} else if ( res instanceof OntologyIndividual ) {
OntologyIndividual indi = ( OntologyIndividual ) res;
vc.setValue( indi.getLabel() );
vc.setValueUri( indi.getUri() );
vc.setDescription( "Individual" );
} else {
OntologyServiceImpl.log.warn( "This is neither an OntologyTerm or an OntologyIndividual: " + res );
return null;
}
if ( vc.getValue() == null ) {
OntologyServiceImpl.log
.warn( "Skipping a characteristic with no value: " + res.getLabel() + " / " + res.getUri() );
return null;
}
return vc;
}
/**
* Given a collection of ontology terms converts them to a collection of Characteristics
*/
private Collection<Characteristic> convert( final Collection<OntologyResource> resources ) {
Collection<Characteristic> converted = new HashSet<>();
if ( ( resources == null ) || ( resources.isEmpty() ) )
return converted;
for ( OntologyResource res : resources ) {
Characteristic vc = Characteristic.Factory.newInstance();
// If there is no URI we don't want to send it back (ie useless)
if ( ( res.getUri() == null ) || StringUtils.isEmpty( res.getUri() ) )
continue;
if ( res instanceof OntologyTerm ) {
OntologyTerm term = ( OntologyTerm ) res;
vc.setValue( term.getTerm() );
vc.setValueUri( term.getUri() );
vc.setDescription( term.getComment() );
}
if ( res instanceof OntologyIndividual ) {
OntologyIndividual indi = ( OntologyIndividual ) res;
vc.setValue( indi.getLabel() );
vc.setValueUri( indi.getUri() );
vc.setDescription( "Individual" );
}
converted.add( vc );
}
return converted;
}
private void countOccurrences( String queryString, Map<String, CharacteristicValueObject> previouslyUsedInSystem ) {
StopWatch watch = new StopWatch();
watch.start();
Collection<Characteristic> foundChars = characteristicService.findByValue( queryString );
/*
* Want to flag in the web interface that these are already used by Gemma (also ignore capitalization; category
* is always ignored; remove duplicates.)
*/
for ( Characteristic characteristic : foundChars ) {
// count up number of usages; see bug 3897
String key = this.foundValueKey( characteristic );
if ( previouslyUsedInSystem.containsKey( key ) ) {
previouslyUsedInSystem.get( key ).incrementOccurrenceCount();
continue;
}
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log.debug( "saw " + key + " (" + key + ") for " + characteristic );
CharacteristicValueObject vo = new CharacteristicValueObject( characteristic );
vo.setCategory( null );
vo.setCategoryUri( null ); // to avoid us counting separately by category.
vo.setAlreadyPresentInDatabase( true );
vo.incrementOccurrenceCount();
previouslyUsedInSystem.put( key, vo );
}
if ( OntologyServiceImpl.log.isDebugEnabled() || ( watch.getTime() > 100
&& previouslyUsedInSystem.size() > 0 ) )
OntologyServiceImpl.log
.info( "found " + previouslyUsedInSystem.size() + " matching characteristics used in the database"
+ " in " + watch.getTime() + " ms " + " Filtered from initial set of " + foundChars
.size() );
}
/**
* given a collection of characteristics add them to the correct List
*/
private Collection<CharacteristicValueObject> findCharacteristicsFromOntology( String searchQuery,
boolean useNeuroCartaOntology,
Map<String, CharacteristicValueObject> characteristicFromDatabaseWithValueUri ) {
Collection<CharacteristicValueObject> characteristicsFromOntology = new HashSet<>();
// in neurocarta we don't need to search all Ontologies
Collection<AbstractOntologyService> ontologyServicesToUse = new HashSet<>();
if ( useNeuroCartaOntology ) {
ontologyServicesToUse.add( this.nifstdOntologyService );
ontologyServicesToUse.add( this.fmaOntologyService );
ontologyServicesToUse.add( this.obiService );
} else {
ontologyServicesToUse = this.ontologyServices;
}
// search all Ontology
for ( AbstractOntologyService ontologyService : ontologyServicesToUse ) {
Collection<OntologyTerm> ontologyTerms = ontologyService.findTerm( searchQuery );
for ( OntologyTerm ontologyTerm : ontologyTerms ) {
// if the ontology term wasnt already found in the database
if ( characteristicFromDatabaseWithValueUri.get( ontologyTerm.getUri() ) == null ) {
CharacteristicValueObject phenotype = new CharacteristicValueObject( -1L,
ontologyTerm.getLabel().toLowerCase(), ontologyTerm.getUri() );
characteristicsFromOntology.add( phenotype );
}
}
}
return characteristicsFromOntology;
}
private String foundValueKey( Characteristic c ) {
if ( StringUtils.isNotBlank( c.getValueUri() ) ) {
return c.getValueUri().toLowerCase();
}
return c.getValue().toLowerCase();
}
private String foundValueKey( CharacteristicValueObject c ) {
if ( c.getValueUri() != null && StringUtils.isNotBlank( c.getValueUri() ) ) {
return c.getValueUri().toLowerCase();
}
return c.getValue().toLowerCase();
}
/**
* Allow us to store gene information as a characteristic associated with our entities. This doesn't work so well
* for non-ncbi genes.
*/
private Characteristic gene2Characteristic( GeneValueObject g ) {
Characteristic vc = Characteristic.Factory.newInstance();
vc.setCategory( "gene" );
vc.setCategoryUri( "http://purl.org/commons/hcls/gene" );
vc.setValue( g.getOfficialSymbol() + " [" + g.getTaxonCommonName() + "]" + " " + g.getOfficialName() );
vc.setDescription( g.toString() );
if ( g.getNcbiId() != null ) {
vc.setValueUri( "http://purl.org/commons/record/ncbi_gene/" + g.getNcbiId() );
}
return vc;
}
private synchronized void initializeCategoryTerms() {
URL termUrl = OntologyServiceImpl.class.getResource( "/ubic/gemma/core/ontology/EFO.factor.categories.txt" );
OntologyServiceImpl.categoryTerms = new ConcurrentHashSet<>();
try (BufferedReader reader = new BufferedReader( new InputStreamReader( termUrl.openStream() ) )) {
String line;
boolean warned = false;
while ( ( line = reader.readLine() ) != null ) {
if ( line.startsWith( "#" ) || StringUtils.isEmpty( line ) )
continue;
String[] f = StringUtils.split( line, '\t' );
if ( f.length < 2 ) {
continue;
}
OntologyTerm t = this.getTerm( f[0] );
if ( t == null ) {
// this is not great. We might want to let it expire and redo it later if the ontology
// becomes
// available. Inference will not be available.
if ( !warned ) {
OntologyServiceImpl.log
.info( "Ontology needed is not loaded? Using light-weight placeholder for " + f[0]
+ " (further warnings hidden)" );
warned = true;
}
t = new OntologyTermSimple( f[0], f[1] );
}
OntologyServiceImpl.categoryTerms.add( t );
}
} catch ( IOException ioe ) {
OntologyServiceImpl.log
.error( "Error reading from term list '" + termUrl + "'; returning general term list", ioe );
OntologyServiceImpl.categoryTerms = null;
}
OntologyServiceImpl.categoryTerms = Collections.unmodifiableCollection( OntologyServiceImpl.categoryTerms );
}
/**
* given a collection of characteristics add them to the correct List
*/
private void putCharacteristicsIntoSpecificList( String searchQuery,
Collection<CharacteristicValueObject> characteristics,
Collection<CharacteristicValueObject> characteristicsWithExactMatch,
Collection<CharacteristicValueObject> characteristicsStartWithQuery,
Collection<CharacteristicValueObject> characteristicsSubstring,
Collection<CharacteristicValueObject> characteristicsNoRuleFound ) {
for ( CharacteristicValueObject cha : characteristics ) {
// Case 1, exact match
if ( cha.getValue().equalsIgnoreCase( searchQuery ) ) {
characteristicsWithExactMatch.add( cha );
}
// Case 2, starts with a substring of the word
else if ( cha.getValue().toLowerCase().startsWith( searchQuery.toLowerCase() ) ) {
characteristicsStartWithQuery.add( cha );
}
// Case 3, contains a substring of the word
else if ( cha.getValue().toLowerCase().contains( searchQuery.toLowerCase() ) ) {
characteristicsSubstring.add( cha );
} else {
characteristicsNoRuleFound.add( cha );
}
}
}
/**
* Look for genes, but only for certain category Uris (genotype, etc.)
*
* @param taxon okay if null, but then all matches returned.
* @param searchResults added to this
*/
private void searchForGenes( String queryString, Taxon taxon,
Collection<CharacteristicValueObject> searchResults ) {
SearchSettings ss = SearchSettings.Factory.newInstance();
ss.setQuery( queryString );
ss.noSearches();
ss.setTaxon( taxon );
ss.setSearchGenes( true );
Map<Class<?>, List<SearchResult>> geneResults = this.searchService.search( ss, false, false );
if ( geneResults.containsKey( Gene.class ) ) {
for ( SearchResult sr : geneResults.get( Gene.class ) ) {
GeneValueObject g = this.geneService.loadValueObjectById( sr.getResultId() );
if ( OntologyServiceImpl.log.isDebugEnabled() )
OntologyServiceImpl.log.debug( "Search for " + queryString + " returned: " + g );
searchResults.add( new CharacteristicValueObject( this.gene2Characteristic( g ) ) );
}
}
}
/**
* @param alreadyUsedResults items already in the system; remove singleton free-text terms.
* @param otherResults other results
* @param searchTerm the query
*/
private Collection<CharacteristicValueObject> sort( Map<String, CharacteristicValueObject> alreadyUsedResults,
Collection<CharacteristicValueObject> otherResults, String searchTerm ) {
/*
* Organize the list into 3 parts. Want to get the exact match showing up on top
*/
List<CharacteristicValueObject> sortedResultsExact = new ArrayList<>();
List<CharacteristicValueObject> sortedResultsStartsWith = new ArrayList<>();
List<CharacteristicValueObject> sortedResultsBottom = new ArrayList<>();
Set<String> foundValues = new HashSet<>();
for ( String key : alreadyUsedResults.keySet() ) {
CharacteristicValueObject c = alreadyUsedResults.get( key );
if ( foundValues.contains( key ) )
continue;
foundValues.add( key );
// don't show singletons of free-text terms.
if ( c.getValueUri() == null && c.getNumTimesUsed() < 2 ) {
continue;
}
//Skip obsolete terms
if ( this.isObsolete( c.getValueUri() ) ) {
OntologyServiceImpl.log.warn( "Skipping an obsolete term: " + c.getValue() + " / " + c.getValueUri() );
continue;
}
this.addToAppropriateList( searchTerm, sortedResultsExact, sortedResultsStartsWith, sortedResultsBottom,
c );
}
for ( CharacteristicValueObject c : otherResults ) {
assert c.getValueUri() != null;
String key = this.foundValueKey( c );
if ( foundValues.contains( key ) )
continue;
foundValues.add( key );
this.addToAppropriateList( searchTerm, sortedResultsExact, sortedResultsStartsWith, sortedResultsBottom,
c );
}
this.sort( sortedResultsExact );
this.sort( sortedResultsStartsWith );
this.sort( sortedResultsBottom );
List<CharacteristicValueObject> sortedTerms = new ArrayList<>( foundValues.size() );
sortedTerms.addAll( sortedResultsExact );
sortedTerms.addAll( sortedResultsStartsWith );
sortedTerms.addAll( sortedResultsBottom );
return sortedTerms;
}
private void addToAppropriateList( String searchTerm, List<CharacteristicValueObject> sortedResultsExact,
List<CharacteristicValueObject> sortedResultsStartsWith,
List<CharacteristicValueObject> sortedResultsBottom, CharacteristicValueObject c ) {
if ( c.getValue().equalsIgnoreCase( searchTerm ) ) {
sortedResultsExact.add( c );
} else if ( c.getValue().toLowerCase().startsWith( searchTerm.toLowerCase() ) || c.getValueUri() != null ) {
sortedResultsStartsWith.add( c );
} else {
sortedResultsBottom.add( c );
}
}
/**
* Sorts Characteristics in our preferred ordering
*/
private class CharacteristicComparator implements Comparator<CharacteristicValueObject> {
@Override
public int compare( CharacteristicValueObject o1, CharacteristicValueObject o2 ) {
// sort by whether used or not, and then by URI; terms without URIs are listed later; break ties by length
if ( o1.getValueUri() != null ) {
if ( o2.getValueUri() != null ) {
// both have uri, break tie.
if ( o1.isAlreadyPresentInDatabase() ) {
if ( o2.isAlreadyPresentInDatabase() ) {
// both are used, break tie by who is used most.
if ( o1.getNumTimesUsed() > o2.getNumTimesUsed() ) {
return -1;
} else if ( o2.getNumTimesUsed() > o1.getNumTimesUsed() ) {
return 1;
}
// both are used same number of times, compare by length (shorter better, typically...)
if ( o1.getValue().length() < o2.getValue().length() ) {
return -1;
} else if ( o1.getValue().length() > o2.getValue().length() ) {
return 1;
}
// equal length, compare by lexig. value.
return o1.getValue().toLowerCase().compareTo( o2.getValue().toLowerCase() );
}
// o1 is used, o2 is not; o1 should be first.
return -1;
} else if ( o2.isAlreadyPresentInDatabase() ) {
// o2 is used and o1 is not; o2 should be first.
return 1;
}
}
// o1 has uri, o2 does not.
return -1;
} else if ( o2.getValueUri() != null ) {
// we know o1 does not have a uri, o2 goes first.
return 1;
}
// neither has URI. By definition these are in the database, so we just rank by length/text
if ( o1.getValue().length() < o2.getValue().length() ) {
return -1;
} else if ( o1.getValue().length() > o2.getValue().length() ) {
return 1;
}
// equal length, compare by lexig. value.
return o1.getValue().toLowerCase().compareTo( o2.getValue().toLowerCase() );
}
}
} | debugging: unclear what is going on with server-side NPE (cannot reproduce locally)
| gemma-core/src/main/java/ubic/gemma/core/ontology/OntologyServiceImpl.java | debugging: unclear what is going on with server-side NPE (cannot reproduce locally) | <ide><path>emma-core/src/main/java/ubic/gemma/core/ontology/OntologyServiceImpl.java
<ide>
<ide> GeneValueObject g = this.geneService.loadValueObjectById( sr.getResultId() );
<ide>
<add> if ( g == null ) {
<add> throw new IllegalStateException(
<add> "There is no gene with ID=" + sr.getResultId() + " (in response to search that yielded: " + sr + ")" );
<add> }
<add>
<ide> if ( OntologyServiceImpl.log.isDebugEnabled() )
<ide> OntologyServiceImpl.log.debug( "Search for " + queryString + " returned: " + g );
<ide> searchResults.add( new CharacteristicValueObject( this.gene2Characteristic( g ) ) ); |
|
Java | apache-2.0 | 14162dc318cf941a2c59e4442d5cd32cb9f9a080 | 0 | benjymous/MWM-for-Android |
/*****************************************************************************
* Copyright (c) 2011 Meta Watch Ltd. *
* www.MetaWatch.org *
* *
=============================================================================
* *
* 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. *
* *
*****************************************************************************/
/*****************************************************************************
* Idle.java *
* Idle *
* Idle watch mode *
* *
* *
*****************************************************************************/
package org.metawatch.manager;
import org.metawatch.manager.MetaWatchService.Preferences;
import org.metawatch.manager.Monitors.LocationData;
import org.metawatch.manager.Monitors.WeatherData;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
public class Idle {
public static byte[] overridenButtons = null;
static void drawWrappedText(String text, Canvas canvas, int x, int y, int width, TextPaint paint) {
canvas.save();
StaticLayout layout = new StaticLayout(text, paint, width, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
canvas.translate(x, y); //position the text
layout.draw(canvas);
canvas.restore();
}
static void drawOutlinedText(String text, Canvas canvas, int x, int y, TextPaint col, TextPaint outline) {
canvas.drawText(text, x+1, y, outline);
canvas.drawText(text, x-1, y, outline);
canvas.drawText(text, x, y+1, outline);
canvas.drawText(text, x, y-1, outline);
canvas.drawText(text, x, y, col);
}
static void drawWrappedOutlinedText(String text, Canvas canvas, int x, int y, int width, TextPaint col, TextPaint outline) {
drawWrappedText(text, canvas, x-1, y, width, outline);
drawWrappedText(text, canvas, x+1, y, width, outline);
drawWrappedText(text, canvas, x, y-1, width, outline);
drawWrappedText(text, canvas, x, y+1, width, outline);
drawWrappedText(text, canvas, x, y, width, col);
}
static Bitmap createLcdIdle(Context context) {
Bitmap bitmap = Bitmap.createBitmap(96, 96, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
TextPaint paintSmall = new TextPaint();
paintSmall.setColor(Color.BLACK);
paintSmall.setTextSize(FontCache.instance(context).Small.size);
paintSmall.setTypeface(FontCache.instance(context).Small.face);
TextPaint paintSmallOutline = new TextPaint();
paintSmallOutline.setColor(Color.WHITE);
paintSmallOutline.setTextSize(FontCache.instance(context).Small.size);
paintSmallOutline.setTypeface(FontCache.instance(context).Small.face);
TextPaint paintLarge = new TextPaint();
paintLarge.setColor(Color.BLACK);
paintLarge.setTextSize(FontCache.instance(context).Large.size);
paintLarge.setTypeface(FontCache.instance(context).Large.face);
canvas.drawColor(Color.WHITE);
canvas = drawLine(canvas, 32);
if(!Preferences.disableWeather) {
if (WeatherData.received) {
//WeatherData.icon = "weather_sunny.bmp";
//WeatherData.locationName = "a really long place name";
//WeatherData.condition = "cloudy with a chance of meatballs";
// icon
Bitmap image = Utils.loadBitmapFromAssets(context, WeatherData.icon);
canvas.drawBitmap(image, 36, 37, null);
// condition
drawWrappedOutlinedText(WeatherData.condition, canvas, 1, 35, 60, paintSmall, paintSmallOutline);
// temperatures
if (WeatherData.celsius) {
paintLarge.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.temp, 82, 46, paintLarge);
//RM: since the degree symbol draws wrong...
canvas.drawText("O", 82, 40, paintSmall);
canvas.drawText("C", 95, 46, paintLarge);
}
else {
paintLarge.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.temp, 83, 46, paintLarge);
//RM: since the degree symbol draws wrong...
canvas.drawText("O", 83, 40, paintSmall);
canvas.drawText("F", 95, 46, paintLarge);
}
paintLarge.setTextAlign(Paint.Align.LEFT);
canvas.drawText("High", 64, 54, paintSmall);
canvas.drawText("Low", 64, 62, paintSmall);
paintSmall.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.tempHigh, 95, 54, paintSmall);
canvas.drawText(WeatherData.tempLow, 95, 62, paintSmall);
paintSmall.setTextAlign(Paint.Align.LEFT);
drawOutlinedText((String) TextUtils.ellipsize(WeatherData.locationName, paintSmall, 63, TruncateAt.END), canvas, 1, 62, paintSmall, paintSmallOutline);
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
if (Preferences.weatherGeolocation) {
if( !LocationData.received ) {
canvas.drawText("Awaiting location", 48, 50, paintSmall);
}
else {
canvas.drawText("Awaiting weather", 48, 50, paintSmall);
}
}
else {
canvas.drawText("No data", 48, 50, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
}
// Debug current time
//String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
//String currentTimeString = new SimpleDateFormat("HH:mm").format(new Date());
//canvas.drawText(currentTimeString, 0, 56, paintSmall);
canvas = drawLine(canvas, 64);
}
// icons row
//Bitmap imageI = Utils.loadBitmapFromAssets(context, "idle_icons_row.bmp");
//canvas.drawBitmap(imageI, 0, 66, null);
int rows = 3;
/*
if (Utils.isGmailAccessSupported(context))
rows = 3;
else
rows = 2;
*/
int yPos = !Preferences.disableWeather ? 67 : 36;
// icons
for (int i = 0; i < rows; i++) {
int slotSpace = 96/rows;
int slotX = slotSpace/2-12;
int iconX = slotSpace*i + slotX;
switch (i) {
case 0:
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "idle_call.bmp"), iconX, yPos, null);
break;
case 1:
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "idle_sms.bmp"), iconX, yPos, null);
break;
case 2:
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "idle_gmail.bmp"), iconX, yPos, null);
break;
}
}
// unread counters
for (int i = 0; i < rows; i++) {
String count = "";
switch (i) {
case 0:
count = Integer.toString(Utils.getMissedCallsCount(context));
break;
case 1:
count = Integer.toString(Utils.getUnreadSmsCount(context));
break;
case 2:
if(Preferences.showK9Unread) {
Log.d(MetaWatch.TAG, "Idle: About to draw k9 count.");
count = Integer.toString(Utils.getUnreadK9Count(context));
Log.d(MetaWatch.TAG, "Idle: k9 count is " + count);
}
else {
Log.d(MetaWatch.TAG, "Idle: About to draw Gmail count.");
if (Utils.isGmailAccessSupported(context))
count = Integer.toString(Utils.getUnreadGmailCount(context, Utils.getGoogleAccountName(context), "^i"));
else
count = Integer.toString(Monitors.getGmailUnreadCount());
Log.d(MetaWatch.TAG, "Idle: Gmail count is " + count);
}
break;
}
int slotSpace = 96/rows;
int slotX = (int) (slotSpace/2-paintSmall.measureText(count)/2)+1;
int countX = slotSpace*i + slotX;
canvas.drawText(count, countX, !Preferences.disableWeather ? 92 : 62, paintSmall);
}
if(Preferences.disableWeather) {
canvas = drawLine(canvas, 64);
//Add more icons here in future.
}
/*
FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Log.d("ow", "bmp ok");
*/
return bitmap;
}
public static Canvas drawLine(Canvas canvas, int y) {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
int left = 3;
for (int i = 0+left; i < 96-left; i += 3)
canvas.drawLine(i, y, i+2, y, paint);
return canvas;
}
public static synchronized void sendLcdIdle(Context context) {
Bitmap bitmap = createLcdIdle(context);
//Protocol.loadTemplate(0);
Protocol.sendLcdBitmap(bitmap, MetaWatchService.WatchBuffers.IDLE);
//Protocol.activateBuffer();
Protocol.updateDisplay(0);
}
public static boolean toIdle(Context context) {
// check for parent modes
MetaWatchService.WatchModes.IDLE = true;
MetaWatchService.watchState = MetaWatchService.WatchStates.IDLE;
if (MetaWatchService.watchType == MetaWatchService.WatchType.DIGITAL) {
sendLcdIdle(context);
//Protocol.updateDisplay(0);
}
return true;
}
public static void updateLcdIdle(Context context) {
if (MetaWatchService.watchState == MetaWatchService.WatchStates.IDLE
&& MetaWatchService.watchType == MetaWatchService.WatchType.DIGITAL)
sendLcdIdle(context);
}
public static boolean isIdleButtonOverriden(byte button) {
if (overridenButtons != null)
for (int i = 0; i < overridenButtons.length; i++)
if (overridenButtons[i] == button)
return true;
return false;
}
}
| src/org/metawatch/manager/Idle.java |
/*****************************************************************************
* Copyright (c) 2011 Meta Watch Ltd. *
* www.MetaWatch.org *
* *
=============================================================================
* *
* 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. *
* *
*****************************************************************************/
/*****************************************************************************
* Idle.java *
* Idle *
* Idle watch mode *
* *
* *
*****************************************************************************/
package org.metawatch.manager;
import org.metawatch.manager.MetaWatchService.Preferences;
import org.metawatch.manager.Monitors.LocationData;
import org.metawatch.manager.Monitors.WeatherData;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
public class Idle {
public static byte[] overridenButtons = null;
static void drawWrappedText(String text, Canvas canvas, int x, int y, int width, TextPaint paint) {
canvas.save();
StaticLayout layout = new StaticLayout(text, paint, width, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
canvas.translate(x, y); //position the text
layout.draw(canvas);
canvas.restore();
}
static void drawOutlinedText(String text, Canvas canvas, int x, int y, TextPaint col, TextPaint outline) {
canvas.drawText(text, x+1, y, outline);
canvas.drawText(text, x-1, y, outline);
canvas.drawText(text, x, y+1, outline);
canvas.drawText(text, x, y-1, outline);
canvas.drawText(text, x, y, col);
}
static void drawWrappedOutlinedText(String text, Canvas canvas, int x, int y, int width, TextPaint col, TextPaint outline) {
drawWrappedText(text, canvas, x-1, y, width, outline);
drawWrappedText(text, canvas, x+1, y, width, outline);
drawWrappedText(text, canvas, x, y-1, width, outline);
drawWrappedText(text, canvas, x, y+1, width, outline);
drawWrappedText(text, canvas, x, y, width, col);
}
static Bitmap createLcdIdle(Context context) {
Bitmap bitmap = Bitmap.createBitmap(96, 96, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
TextPaint paintSmall = new TextPaint();
paintSmall.setColor(Color.BLACK);
paintSmall.setTextSize(FontCache.instance(context).Small.size);
paintSmall.setTypeface(FontCache.instance(context).Small.face);
TextPaint paintSmallOutline = new TextPaint();
paintSmallOutline.setColor(Color.WHITE);
paintSmallOutline.setTextSize(FontCache.instance(context).Small.size);
paintSmallOutline.setTypeface(FontCache.instance(context).Small.face);
TextPaint paintLarge = new TextPaint();
paintLarge.setColor(Color.BLACK);
paintLarge.setTextSize(FontCache.instance(context).Large.size);
paintLarge.setTypeface(FontCache.instance(context).Large.face);
canvas.drawColor(Color.WHITE);
canvas = drawLine(canvas, 32);
if(!Preferences.disableWeather) {
if (WeatherData.received) {
//WeatherData.icon = "weather_sunny.bmp";
//WeatherData.locationName = "a really long place name";
//WeatherData.condition = "cloudy with a chance of meatballs";
// icon
Bitmap image = Utils.loadBitmapFromAssets(context, WeatherData.icon);
canvas.drawBitmap(image, 36, 37, null);
// condition
drawWrappedOutlinedText(WeatherData.condition, canvas, 1, 35, 60, paintSmall, paintSmallOutline);
// temperatures
if (WeatherData.celsius) {
paintLarge.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.temp, 82, 46, paintLarge);
//RM: since the degree symbol draws wrong...
canvas.drawText("O", 82, 40, paintSmall);
canvas.drawText("C", 95, 46, paintLarge);
}
else {
paintLarge.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.temp, 83, 46, paintLarge);
//RM: since the degree symbol draws wrong...
canvas.drawText("O", 83, 40, paintSmall);
canvas.drawText("F", 95, 46, paintLarge);
}
paintLarge.setTextAlign(Paint.Align.LEFT);
canvas.drawText("High", 64, 54, paintSmall);
canvas.drawText("Low", 64, 62, paintSmall);
paintSmall.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(WeatherData.tempHigh, 95, 54, paintSmall);
canvas.drawText(WeatherData.tempLow, 95, 62, paintSmall);
paintSmall.setTextAlign(Paint.Align.LEFT);
drawOutlinedText((String) TextUtils.ellipsize(WeatherData.locationName, paintSmall, 63, TruncateAt.END), canvas, 1, 62, paintSmall, paintSmallOutline);
} else {
paintSmall.setTextAlign(Paint.Align.CENTER);
if (Preferences.weatherGeolocation) {
if( !LocationData.received ) {
canvas.drawText("Awaiting location", 48, 50, paintSmall);
}
else {
canvas.drawText("Awaiting weather", 48, 50, paintSmall);
}
}
else {
canvas.drawText("No data", 48, 50, paintSmall);
}
paintSmall.setTextAlign(Paint.Align.LEFT);
}
// Debug current time
//String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
//String currentTimeString = new SimpleDateFormat("HH:mm").format(new Date());
//canvas.drawText(currentTimeString, 0, 56, paintSmall);
canvas = drawLine(canvas, 64);
}
// icons row
//Bitmap imageI = Utils.loadBitmapFromAssets(context, "idle_icons_row.bmp");
//canvas.drawBitmap(imageI, 0, 66, null);
int rows = 3;
/*
if (Utils.isGmailAccessSupported(context))
rows = 3;
else
rows = 2;
*/
int yPos = !Preferences.disableWeather ? 67 : 36;
// icons
for (int i = 0; i < rows; i++) {
int slotSpace = 96/rows;
int slotX = slotSpace/2-12;
int iconX = slotSpace*i + slotX;
switch (i) {
case 0:
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "idle_call.bmp"), iconX, yPos, null);
break;
case 1:
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "idle_sms.bmp"), iconX, yPos, null);
break;
case 2:
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "idle_gmail.bmp"), iconX, yPos, null);
break;
}
}
// unread counters
for (int i = 0; i < rows; i++) {
String count = "";
switch (i) {
case 0:
count = Integer.toString(Utils.getMissedCallsCount(context));
break;
case 1:
count = Integer.toString(Utils.getUnreadSmsCount(context));
break;
case 2:
if(Preferences.showK9Unread) {
Log.d(MetaWatch.TAG, "Idle: About to draw k9 count.");
count = Integer.toString(Utils.getUnreadK9Count(context));
Log.d(MetaWatch.TAG, "Idle: k9 count is " + count);
}
else {
Log.d(MetaWatch.TAG, "Idle: About to draw Gmail count.");
if (Utils.isGmailAccessSupported(context))
count = Integer.toString(Utils.getUnreadGmailCount(context, Utils.getGoogleAccountName(context), "^i"));
else
count = Integer.toString(Monitors.getGmailUnreadCount());
Log.d(MetaWatch.TAG, "Idle: Gmail count is " + count);
}
break;
}
int slotSpace = 96/rows;
int slotX = (int) (slotSpace/2-paintSmall.measureText(count)/2);
int countX = slotSpace*i + slotX;
canvas.drawText(count, countX, !Preferences.disableWeather ? 92 : 62, paintSmall);
}
if(Preferences.disableWeather) {
canvas = drawLine(canvas, 64);
//Add more icons here in future.
}
/*
FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Log.d("ow", "bmp ok");
*/
return bitmap;
}
public static Canvas drawLine(Canvas canvas, int y) {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
int left = 3;
for (int i = 0+left; i < 96-left; i += 3)
canvas.drawLine(i, y, i+2, y, paint);
return canvas;
}
public static synchronized void sendLcdIdle(Context context) {
Bitmap bitmap = createLcdIdle(context);
//Protocol.loadTemplate(0);
Protocol.sendLcdBitmap(bitmap, MetaWatchService.WatchBuffers.IDLE);
//Protocol.activateBuffer();
Protocol.updateDisplay(0);
}
public static boolean toIdle(Context context) {
// check for parent modes
MetaWatchService.WatchModes.IDLE = true;
MetaWatchService.watchState = MetaWatchService.WatchStates.IDLE;
if (MetaWatchService.watchType == MetaWatchService.WatchType.DIGITAL) {
sendLcdIdle(context);
//Protocol.updateDisplay(0);
}
return true;
}
public static void updateLcdIdle(Context context) {
if (MetaWatchService.watchState == MetaWatchService.WatchStates.IDLE
&& MetaWatchService.watchType == MetaWatchService.WatchType.DIGITAL)
sendLcdIdle(context);
}
public static boolean isIdleButtonOverriden(byte button) {
if (overridenButtons != null)
for (int i = 0; i < overridenButtons.length; i++)
if (overridenButtons[i] == button)
return true;
return false;
}
}
| fixed centreing on unread count text
| src/org/metawatch/manager/Idle.java | fixed centreing on unread count text | <ide><path>rc/org/metawatch/manager/Idle.java
<ide> String count = "";
<ide> switch (i) {
<ide> case 0:
<del> count = Integer.toString(Utils.getMissedCallsCount(context));
<add> count = Integer.toString(Utils.getMissedCallsCount(context));
<ide> break;
<ide> case 1:
<ide> count = Integer.toString(Utils.getUnreadSmsCount(context));
<ide> }
<ide> break;
<ide> }
<del>
<add>
<ide> int slotSpace = 96/rows;
<del> int slotX = (int) (slotSpace/2-paintSmall.measureText(count)/2);
<add> int slotX = (int) (slotSpace/2-paintSmall.measureText(count)/2)+1;
<ide> int countX = slotSpace*i + slotX;
<ide>
<ide> canvas.drawText(count, countX, !Preferences.disableWeather ? 92 : 62, paintSmall); |
|
Java | apache-2.0 | 1e85f0244a9910839182da853059990f8961df69 | 0 | tylerFowler/cloudapp-mp2,tylerFowler/cloudapp-mp2,tylerFowler/cloudapp-mp2 | import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.IOException;
import java.lang.Integer;
import java.util.StringTokenizer;
import java.util.TreeSet;
// >>> Don't Change
public class TopPopularLinks extends Configured implements Tool {
public static final Log LOG = LogFactory.getLog(TopPopularLinks.class);
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TopPopularLinks(), args);
System.exit(res);
}
public static class IntArrayWritable extends ArrayWritable {
public IntArrayWritable() {
super(IntWritable.class);
}
public IntArrayWritable(Integer[] numbers) {
super(IntWritable.class);
IntWritable[] ints = new IntWritable[numbers.length];
for (int i = 0; i < numbers.length; i++) {
ints[i] = new IntWritable(numbers[i]);
}
set(ints);
}
}
// <<< Don't Change
@Override
public int run(String[] args) throws Exception {
Configuration conf = this.getConf();
FileSystem fs = FileSystem.get(conf);
Path tmpPath = new Path("/mp2/tmp");
fs.delete(tmpPath, true);
// Link Count Job Configuration
Job linkJob = Job.getInstance(conf, "Top Popular Links");
linkJob.setOutputKeyClass(IntWritable.class);
linkJob.setOutputValueClass(IntWritable.class);
linkJob.setMapperClass(LinkCountMap.class);
linkJob.setReducerClass(LinkCountReduce.class);
FileInputFormat.setInputPaths(linkJob, new Path(args[0]));
FileOutputFormat.setOutputPath(linkJob, tmpPath);
linkJob.setJarByClass(TopPopularLinks.class);
linkJob.waitForCompletion(true);
// Top Link Job Configuration
Job topLinksJob = Job.getInstance(conf, "Top Popular Links");
topLinksJob.setOutputKeyClass(IntWritable.class);
topLinksJob.setOutputValueClass(IntWritable.class);
topLinksJob.setMapOutputKeyClass(NullWritable.class);
topLinksJob.setMapOutputValueClass(IntArrayWritable.class);
topLinksJob.setMapperClass(TopLinksMap.class);
topLinksJob.setReducerClass(TopLinksReduce.class);
topLinksJob.setNumReduceTasks(1);
FileInputFormat.setInputPaths(topLinksJob, tmpPath);
FileOutputFormat.setOutputPath(topLinksJob, new Path(args[1]));
topLinksJob.setInputFormatClass(KeyValueTextInputFormat.class);
topLinksJob.setOutputFormatClass(TextOutputFormat.class);
topLinksJob.setJarByClass(TopPopularLinks.class);
return topLinksJob.waitForCompletion(true) ? 0 : 1;
}
public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> {
@Override
public void map(Object key, Text line, Context ctxt) throws IOException, InterruptedException {
String[] input = line.toString().split(":");
Integer pageId = Integer.parseInt(input[0].replace(':', ' ').trim());
String[] pageLinks = input[1].split(" ");
// Flip the format upside down so that each *linked to*
// page has a corresponding page that *links* to it.
// This method completely excludes orphaned links but since
// this is a popularity contest we don't care, and even better,
// it makes the reducer dataset smaller
for (String linkIdStr : pageLinks) {
if (linkIdStr.trim().isEmpty()) continue;
Integer linkId = Integer.parseInt(linkIdStr.trim());
ctxt.write(new IntWritable(linkId), new IntWritable(1));
}
}
}
public static class LinkCountReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
// we simply need to aggregate the number of counts
// this is more of a map than a reduce.. the mapper already reduced
// by excluding orphaned pages
@Override
public void reduce(IntWritable key, Iterable<IntWritable> values, Context ctxt) throws IOException, InterruptedException {
Integer linkBackCount = 0;
for (IntWritable linkId : values) {
linkBackCount += linkId.get();
}
ctxt.write(key, new IntWritable(linkBackCount));
}
}
public static class TopLinksMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> {
Integer N;
private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void map(Text key, Text value, Context ctxt) throws IOException, InterruptedException {
Integer pageId = Integer.parseInt(key.toString());
Integer count = Integer.parseInt(value.toString());
rankMap.add(new Pair<Integer, Integer>(pageId, count));
if (rankMap.size() > this.N) {
rankMap.remove(rankMap.first());
}
}
@Override
protected void cleanup(Context ctxt) throws IOException, InterruptedException {
for (Pair<Integer, Integer> itm : rankMap) {
Integer[] entry = { itm.first, itm.second };
IntArrayWritable entryArr = new IntArrayWritable(entry);
ctxt.write(NullWritable.get(), entryArr);
}
}
}
public static class TopLinksReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> {
Integer N;
private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void reduce(NullWritable key, Iterable<IntArrayWritable> values, Context ctxt) throws IOException, InterruptedException {
for (IntArrayWritable val : values) {
IntWritable[] rankEntry = (IntWritable[]) val.toArray();
Integer pageId = rankEntry[0].get();
Integer linkBackCount = rankEntry[1].get();
rankMap.add(new Pair<Integer, Integer>(pageId, linkBackCount));
if (rankMap.size() > this.N) {
rankMap.remove(rankMap.first());
}
}
for (Pair<Integer, Integer> rankEntry : rankMap) {
IntWritable pageId = new IntWritable(rankEntry.first);
IntWritable count = new IntWritable(rankEntry.second);
ctxt.write(pageId, count);
}
}
}
}
// >>> Don't Change
class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
// <<< Don't Change
| TopPopularLinks.java | import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.IOException;
import java.lang.Integer;
import java.util.StringTokenizer;
import java.util.TreeSet;
// >>> Don't Change
public class TopPopularLinks extends Configured implements Tool {
public static final Log LOG = LogFactory.getLog(TopPopularLinks.class);
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TopPopularLinks(), args);
System.exit(res);
}
public static class IntArrayWritable extends ArrayWritable {
public IntArrayWritable() {
super(IntWritable.class);
}
public IntArrayWritable(Integer[] numbers) {
super(IntWritable.class);
IntWritable[] ints = new IntWritable[numbers.length];
for (int i = 0; i < numbers.length; i++) {
ints[i] = new IntWritable(numbers[i]);
}
set(ints);
}
}
// <<< Don't Change
@Override
public int run(String[] args) throws Exception {
Configuration conf = this.getConf();
FileSystem fs = FileSystem.get(conf);
Path tmpPath = new Path("/mp2/tmp");
fs.delete(tmpPath, true);
// Link Count Job Configuration
Job linkJob = Job.getInstance(conf, "Top Popular Links");
linkJob.setOutputKeyClass(IntWritable.class);
linkJob.setOutputValueClass(IntWritable.class);
linkJob.setMapperClass(LinkCountMap.class);
linkJob.setReducerClass(LinkCountReduce.class);
FileInputFormat.setInputPaths(linkJob, new Path(args[0]));
FileOutputFormat.setOutputPath(linkJob, tmpPath);
linkJob.setJarByClass(TopPopularLinks.class);
linkJob.waitForCompletion(true);
// Top Link Job Configuration
Job topLinksJob = Job.getInstance(conf, "Top Popular Links");
topLinksJob.setOutputKeyClass(IntWritable.class);
topLinksJob.setOutputValueClass(IntWritable.class);
topLinksJob.setMapOutputKeyClass(NullWritable.class);
topLinksJob.setMapOutputValueClass(IntArrayWritable.class);
topLinksJob.setMapperClass(TopLinksMap.class);
topLinksJob.setReducerClass(TopLinksReduce.class);
topLinksJob.setNumReduceTasks(1);
FileInputFormat.setInputPaths(topLinksJob, tmpPath);
FileOutputFormat.setOutputPath(topLinksJob, new Path(args[1]));
topLinksJob.setInputFormatClass(KeyValueTextInputFormat.class);
topLinksJob.setOutputFormatClass(TextOutputFormat.class);
topLinksJob.setJarByClass(TopPopularLinks.class);
return topLinksJob.waitForCompletion(true) ? 0 : 1;
}
public static class LinkCountMap extends Mapper<Object, Text, IntWritable, IntWritable> {
@Override
public void map(Object key, Text line, Context ctxt) throws IOException, InterruptedException {
String[] input = line.toString().split(":");
Integer pageId = Integer.parseInt(input[0].replace(':', ' ').trim());
String[] pageLinks = input[1].split(" ");
// Flip the format upside down so that each *linked to*
// page has a corresponding page that *links* to it.
// This method completely excludes orphaned links but since
// this is a popularity contest we don't care, and even better,
// it makes the reducer dataset smaller
for (String linkIdStr : pageLinks) {
if (linkIdStr.trim().isEmpty()) continue;
Integer linkId = Integer.parseInt(linkIdStr.trim());
ctxt.write(new IntWritable(linkId), new IntWritable(1));
}
}
}
public static class LinkCountReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
// we simply need to aggregate the number of counts
// this is more of a map than a reduce.. the mapper already reduced
// by excluding orphaned pages
@Override
public void reduce(IntWritable key, Iterable<IntWritable> values, Context ctxt) throws IOException, InterruptedException {
Integer linkBackCount = values.get();
// for (IntWritable linkId : values) {
// linkBackCount += linkId.get();
// }
ctxt.write(key, new IntWritable(linkBackCount));
}
}
public static class TopLinksMap extends Mapper<Text, Text, NullWritable, IntArrayWritable> {
Integer N;
private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void map(Text key, Text value, Context ctxt) throws IOException, InterruptedException {
Integer pageId = Integer.parseInt(key.toString());
Integer count = Integer.parseInt(value.toString());
rankMap.add(new Pair<Integer, Integer>(pageId, count));
if (rankMap.size() > this.N) {
rankMap.remove(rankMap.first());
}
}
@Override
protected void cleanup(Context ctxt) throws IOException, InterruptedException {
for (Pair<Integer, Integer> itm : rankMap) {
Integer[] entry = { itm.first, itm.second };
IntArrayWritable entryArr = new IntArrayWritable(entry);
ctxt.write(NullWritable.get(), entryArr);
}
}
}
public static class TopLinksReduce extends Reducer<NullWritable, IntArrayWritable, IntWritable, IntWritable> {
Integer N;
private TreeSet<Pair<Integer, Integer>> rankMap = new TreeSet<Pair<Integer, Integer>>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void reduce(NullWritable key, Iterable<IntArrayWritable> values, Context ctxt) throws IOException, InterruptedException {
for (IntArrayWritable val : values) {
IntWritable[] rankEntry = (IntWritable[]) val.toArray();
Integer pageId = rankEntry[0].get();
Integer linkBackCount = rankEntry[1].get();
rankMap.add(new Pair<Integer, Integer>(pageId, linkBackCount));
if (rankMap.size() > this.N) {
rankMap.remove(rankMap.first());
}
}
for (Pair<Integer, Integer> rankEntry : rankMap) {
IntWritable pageId = new IntWritable(rankEntry.first);
IntWritable count = new IntWritable(rankEntry.second);
ctxt.write(pageId, count);
}
}
}
}
// >>> Don't Change
class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
// <<< Don't Change
| o;iefjawf
| TopPopularLinks.java | o;iefjawf | <ide><path>opPopularLinks.java
<ide>
<ide> @Override
<ide> public void reduce(IntWritable key, Iterable<IntWritable> values, Context ctxt) throws IOException, InterruptedException {
<del> Integer linkBackCount = values.get();
<del> // for (IntWritable linkId : values) {
<del> // linkBackCount += linkId.get();
<del> // }
<add> Integer linkBackCount = 0;
<add> for (IntWritable linkId : values) {
<add> linkBackCount += linkId.get();
<add> }
<ide>
<ide> ctxt.write(key, new IntWritable(linkBackCount));
<ide> } |
|
JavaScript | mit | f2b9c683bc4689d0a3271e4004d3bae8fe8d5747 | 0 | maovt/p3_api,aswarren/p3_api,maovt/p3_api,maovt/p3_api,aswarren/p3_api,maovt/p3_api,PATRIC3/p3_api,maovt/p3_api,maovt/p3_api,PATRIC3/p3_api | var express = require('express');
var router = express.Router({strict:true,mergeParams:true});
var defer = require("promised-io/promise").defer;
var when = require("promised-io/promise").when;
var config = require("../config");
var bodyParser = require("body-parser");
var rql = require("solrjs/rql");
var debug = require('debug')('p3api-server:JBrowse');
var SolrQueryParser = require("../middleware/SolrQueryParser");
var RQLQueryParser = require("../middleware/RQLQueryParser");
var DecorateQuery = require("../middleware/DecorateQuery");
var PublicDataTypes = require("../middleware/PublicDataTypes");
var authMiddleware = require("../middleware/auth");
var APIMethodHandler = require("../middleware/APIMethodHandler");
var httpParams = require("../middleware/http-params");
var Limiter = require("../middleware/Limiter");
// router.use(httpParams);
// router.use(authMiddleware);
var apiRoot = config.get("jbrowseAPIRoot");
function generateRefSeqs(req,res,next){
return '[{"sid":"1094551.3","seqChunkSize":78236,"start":0,"seqDir":"","name":"AIME01000001","length":78236,"end":78236,"accn":"AIME01000001"},{"sid":"1094551.3","seqChunkSize":136015,"start":0,"seqDir":"","name":"AIME01000002","length":136015,"end":136015,"accn":"AIME01000002"},{"sid":"1094551.3","seqChunkSize":400537,"start":0,"seqDir":"","name":"AIME01000003","length":400537,"end":400537,"accn":"AIME01000003"},{"sid":"1094551.3","seqChunkSize":559503,"start":0,"seqDir":"","name":"AIME01000004","length":559503,"end":559503,"accn":"AIME01000004"},{"sid":"1094551.3","seqChunkSize":6253,"start":0,"seqDir":"","name":"AIME01000005","length":6253,"end":6253,"accn":"AIME01000005"},{"sid":"1094551.3","seqChunkSize":368863,"start":0,"seqDir":"","name":"AIME01000006","length":368863,"end":368863,"accn":"AIME01000006"},{"sid":"1094551.3","seqChunkSize":2535,"start":0,"seqDir":"","name":"AIME01000007","length":2535,"end":2535,"accn":"AIME01000007"},{"sid":"1094551.3","seqChunkSize":5334,"start":0,"seqDir":"","name":"AIME01000008","length":5334,"end":5334,"accn":"AIME01000008"},{"sid":"1094551.3","seqChunkSize":6500,"start":0,"seqDir":"","name":"AIME01000009","length":6500,"end":6500,"accn":"AIME01000009"},{"sid":"1094551.3","seqChunkSize":3562,"start":0,"seqDir":"","name":"AIME01000010","length":3562,"end":3562,"accn":"AIME01000010"},{"sid":"1094551.3","seqChunkSize":12776,"start":0,"seqDir":"","name":"AIME01000011","length":12776,"end":12776,"accn":"AIME01000011"},{"sid":"1094551.3","seqChunkSize":8474,"start":0,"seqDir":"","name":"AIME01000012","length":8474,"end":8474,"accn":"AIME01000012"},{"sid":"1094551.3","seqChunkSize":3218,"start":0,"seqDir":"","name":"AIME01000013","length":3218,"end":3218,"accn":"AIME01000013"},{"sid":"1094551.3","seqChunkSize":1065,"start":0,"seqDir":"","name":"AIME01000014","length":1065,"end":1065,"accn":"AIME01000014"},{"sid":"1094551.3","seqChunkSize":3412,"start":0,"seqDir":"","name":"AIME01000015","length":3412,"end":3412,"accn":"AIME01000015"},{"sid":"1094551.3","seqChunkSize":2868,"start":0,"seqDir":"","name":"AIME01000016","length":2868,"end":2868,"accn":"AIME01000016"},{"sid":"1094551.3","seqChunkSize":3686,"start":0,"seqDir":"","name":"AIME01000017","length":3686,"end":3686,"accn":"AIME01000017"},{"sid":"1094551.3","seqChunkSize":1858,"start":0,"seqDir":"","name":"AIME01000018","length":1858,"end":1858,"accn":"AIME01000018"},{"sid":"1094551.3","seqChunkSize":3144,"start":0,"seqDir":"","name":"AIME01000019","length":3144,"end":3144,"accn":"AIME01000019"},{"sid":"1094551.3","seqChunkSize":1499,"start":0,"seqDir":"","name":"AIME01000020","length":1499,"end":1499,"accn":"AIME01000020"},{"sid":"1094551.3","seqChunkSize":36781,"start":0,"seqDir":"","name":"AIME01000021","length":36781,"end":36781,"accn":"AIME01000021"}]'
}
function generateTrackList(req,res,next){
console.log("Generate Track List: ", req.params.id);
return JSON.stringify({
"tracks": [
{
"type": "SequenceTrack",
"storeClass": "JBrowse/Store/SeqFeature/REST",
"baseUrl": apiRoot + "/genome/" + req.params.id,
// "urlTemplate": apiRoot + "/sequence/{refseq}",
"key": "Reference sequence",
"label": "DNA",
"chunkSize": 20000,
"maxExportSpan": 10000000,
"region_stats": true
}
,{
"type": "JBrowse/View/Track/HTMLFeatures",
// "urlTemplate": apiRoot + "/genome/" +req.params.id + "/{refseq}?annotation=PATRIC",
// "storeClass": "JBrowse/Store/SeqFeature/NCList",
"storeClass": "JBrowse/Store/SeqFeature/REST",
"baseUrl": apiRoot + "/genome/" + req.params.id,
"key": "PATRIC Annotation",
"label": "PATRICGenes",
"query": {
annotation: "PATRIC"
},
"style": {
"label": "function( feature ) { console.log('RETURN PATRIC_ID: ', feature.get('patric_id'),feature); return feature.get('patric_id'); }"
},
"hooks": {
"modify": "function(track, feature, div) { div.style.padding='4px'; div.style.backgroundColor = ['#17487d','#5190d5','#c7daf1'][feature.get('phase')];}"
},
"tooltip": "<div style='line-height:1.7em'><b>{patric_id}</b> | {refseq_locus_tag} | {alt_locus_Tag} | {gene}<br>{product}<br>{type}: {start_str} .. {end} ({strand_str})<br> <i>Click for detail information</i></div>",
"metadata": {
"Description": "PATRIC annotated genes"
},
"maxExportFeatures": 10000,
"maxExportSpan": 10000000,
"region_stats": true
}
, {
"type": "FeatureTrack",
// "urlTemplate": apiRoot + "/genome/" +req.params.id + "/{refseq}?annotation=RefSeq",
// "storeClass": "JBrowse/Store/SeqFeature/NCList",
"storeClass": "JBrowse/Store/SeqFeature/REST",
"baseUrl": apiRoot + "/genome/" + req.params.id,
"query": {
annotation: "RefSeq"
},
"key": "RefSeq Annotation",
"label": "RefSeqGenes",
"style": {
"className": "feature3",
"label": "function( feature ) { return feature.refseq_locus_tag; }"
},
"hooks": {
"modify": "function(track, feature, div) { div.style.backgroundColor = ['#4c5e22','#9ab957','#c4d59b'][feature.get('phase')];}"
},
"tooltip": "<div style='line-height:1.7em'><b>{refseq_locus_tag}</b> | {gene}<br>{product}<br>{type}: {start_str} .. {end} ({strand_str})<br> <i>Click for detail information</i></div>",
"metadata": {
"Description": "RefSeq annotated genes"
},
"maxExportFeatures": 10000,
"maxExportSpan": 10000000,
"region_stats": true
}
],
"formatVersion": 1
})
}
router.use(httpParams);
router.use(authMiddleware);
router.use(PublicDataTypes);
router.get("/genome/:id/trackList", [
function(req,res,next){
res.write(generateTrackList(req,res,next));
res.end();
}
])
router.get("/genome/:id/tracks", [
function(req,res,next){
res.write("[]");
res.end();
}
])
router.get("/genome/:id/stats/global",[
function(req,res,next){
res.write('{}');
res.end();
}
])
router.get("/genome/:id/stats/region/:feature_id",[
function(req,res,next){
res.end();
}
])
router.get("/genome/:id/stats/regionFeatureDensities/:feature_id",[
function(req,res,next){
res.end();
}
])
router.get("/genome/:id/features/:feature_id",[
function(req,res,next){
console.log("req.params: ", req.params, "req.query: ", req.query);
var start = req.query.start || req.params.start;
var end = req.query.end || req.params.end;
var annotation = req.query.annotation || req.params.annotation || "PATRIC"
req.call_collection = "genome_feature";
req.call_method = "query";
var st = "and(gt(start,"+start+"),lt(start,"+end+"))"
var en = "and(gt(end,"+start+"),lt(end,"+end+"))"
req.call_params = ["and(eq(genome_id," + req.params.id + "),eq(accession," +req.params.feature_id + "),eq(annotation," + annotation + "),or(" +st+"," + en + "),ne(feature_type,source))"];
req.queryType = "rql";
console.log("CALL_PARAMS: ", req.call_params);
next();
},
RQLQueryParser,
DecorateQuery,
Limiter,
APIMethodHandler,
function(req,res,next){
console.log("res.results: ", res.results)
if (res.results && res.results.response && res.results.response.docs){
var features = res.results.response.docs.map(function(d){
d.seq= d.na_sequence;
d.type=d.feature_type;
d.name=d.accession;
d.uniqueID=d.feature_id;
d.strand=(d.strand=="+")?1:-1;
d.phase=(d.feature_type=="CDS")?0:((d.feature_type=="RNA")?1:2);
return d;
})
console.log("FEATURES: ", features)
res.json({features: features});
res.end();
}
}
])
router.get("/genome/:id/refseqs", [
function(req,res,next){
req.call_collection = "genome_sequence";
req.call_method = "query";
req.call_params = ["&eq(genome_id," + req.params.id + ")&select(topology,gi,accession,length,sequence_id,gc_content,owner,sequence_type,taxon_id,public,genome_id,genome_name,date_inserted,date_modified)&sort(+accession)"];
req.queryType = "rql";
next();
},
RQLQueryParser,
DecorateQuery,
Limiter,
APIMethodHandler,
function(req,res,next){
console.log("Res.results: ", res.results);
if (res.results && res.results.response && res.results.response.docs){
var refseqs = res.results.response.docs.map(function(d){
return {
length: d.length,
name: d.accession,
accn: d.accession,
sid: d.genome_id,
start: 0,
end: d.length,
seqDir: "",
seqChunkSize: d.length
}
})
res.json(refseqs);
res.end();
}
}
])
module.exports = router;
| routes/JBrowse.js | var express = require('express');
var router = express.Router({strict:true,mergeParams:true});
var defer = require("promised-io/promise").defer;
var when = require("promised-io/promise").when;
var config = require("../config");
var bodyParser = require("body-parser");
var rql = require("solrjs/rql");
var debug = require('debug')('p3api-server:JBrowse');
var SolrQueryParser = require("../middleware/SolrQueryParser");
var RQLQueryParser = require("../middleware/RQLQueryParser");
var DecorateQuery = require("../middleware/DecorateQuery");
var PublicDataTypes = require("../middleware/PublicDataTypes");
var authMiddleware = require("../middleware/auth");
var APIMethodHandler = require("../middleware/APIMethodHandler");
var httpParams = require("../middleware/http-params");
var Limiter = require("../middleware/Limiter");
// router.use(httpParams);
// router.use(authMiddleware);
var apiRoot = config.get("jbrowseAPIRoot");
function generateRefSeqs(req,res,next){
return '[{"sid":"1094551.3","seqChunkSize":78236,"start":0,"seqDir":"","name":"AIME01000001","length":78236,"end":78236,"accn":"AIME01000001"},{"sid":"1094551.3","seqChunkSize":136015,"start":0,"seqDir":"","name":"AIME01000002","length":136015,"end":136015,"accn":"AIME01000002"},{"sid":"1094551.3","seqChunkSize":400537,"start":0,"seqDir":"","name":"AIME01000003","length":400537,"end":400537,"accn":"AIME01000003"},{"sid":"1094551.3","seqChunkSize":559503,"start":0,"seqDir":"","name":"AIME01000004","length":559503,"end":559503,"accn":"AIME01000004"},{"sid":"1094551.3","seqChunkSize":6253,"start":0,"seqDir":"","name":"AIME01000005","length":6253,"end":6253,"accn":"AIME01000005"},{"sid":"1094551.3","seqChunkSize":368863,"start":0,"seqDir":"","name":"AIME01000006","length":368863,"end":368863,"accn":"AIME01000006"},{"sid":"1094551.3","seqChunkSize":2535,"start":0,"seqDir":"","name":"AIME01000007","length":2535,"end":2535,"accn":"AIME01000007"},{"sid":"1094551.3","seqChunkSize":5334,"start":0,"seqDir":"","name":"AIME01000008","length":5334,"end":5334,"accn":"AIME01000008"},{"sid":"1094551.3","seqChunkSize":6500,"start":0,"seqDir":"","name":"AIME01000009","length":6500,"end":6500,"accn":"AIME01000009"},{"sid":"1094551.3","seqChunkSize":3562,"start":0,"seqDir":"","name":"AIME01000010","length":3562,"end":3562,"accn":"AIME01000010"},{"sid":"1094551.3","seqChunkSize":12776,"start":0,"seqDir":"","name":"AIME01000011","length":12776,"end":12776,"accn":"AIME01000011"},{"sid":"1094551.3","seqChunkSize":8474,"start":0,"seqDir":"","name":"AIME01000012","length":8474,"end":8474,"accn":"AIME01000012"},{"sid":"1094551.3","seqChunkSize":3218,"start":0,"seqDir":"","name":"AIME01000013","length":3218,"end":3218,"accn":"AIME01000013"},{"sid":"1094551.3","seqChunkSize":1065,"start":0,"seqDir":"","name":"AIME01000014","length":1065,"end":1065,"accn":"AIME01000014"},{"sid":"1094551.3","seqChunkSize":3412,"start":0,"seqDir":"","name":"AIME01000015","length":3412,"end":3412,"accn":"AIME01000015"},{"sid":"1094551.3","seqChunkSize":2868,"start":0,"seqDir":"","name":"AIME01000016","length":2868,"end":2868,"accn":"AIME01000016"},{"sid":"1094551.3","seqChunkSize":3686,"start":0,"seqDir":"","name":"AIME01000017","length":3686,"end":3686,"accn":"AIME01000017"},{"sid":"1094551.3","seqChunkSize":1858,"start":0,"seqDir":"","name":"AIME01000018","length":1858,"end":1858,"accn":"AIME01000018"},{"sid":"1094551.3","seqChunkSize":3144,"start":0,"seqDir":"","name":"AIME01000019","length":3144,"end":3144,"accn":"AIME01000019"},{"sid":"1094551.3","seqChunkSize":1499,"start":0,"seqDir":"","name":"AIME01000020","length":1499,"end":1499,"accn":"AIME01000020"},{"sid":"1094551.3","seqChunkSize":36781,"start":0,"seqDir":"","name":"AIME01000021","length":36781,"end":36781,"accn":"AIME01000021"}]'
}
function generateTrackList(req,res,next){
console.log("Generate Track List: ", req.params.id);
return JSON.stringify({
"tracks": [
{
"type": "SequenceTrack",
"storeClass": "JBrowse/Store/SeqFeature/REST",
"baseUrl": apiRoot + "/genome/" + req.params.id,
// "urlTemplate": apiRoot + "/sequence/{refseq}",
"key": "Reference sequence",
"label": "DNA",
"chunkSize": 20000,
"maxExportSpan": 10000000,
"region_stats": true
}
,{
"type": "JBrowse/View/Track/HTMLFeatures",
// "urlTemplate": apiRoot + "/genome/" +req.params.id + "/{refseq}?annotation=PATRIC",
// "storeClass": "JBrowse/Store/SeqFeature/NCList",
"storeClass": "JBrowse/Store/SeqFeature/REST",
"baseUrl": apiRoot + "/genome/" + req.params.id,
"key": "PATRIC Annotation",
"label": "PATRICGenes",
"query": {
annotation: "PATRIC"
},
"style": {
"label": "function( feature ) { console.log('RETURN PATRIC_ID: ', feature.get('patric_id'),feature); return feature.get('patric_id'); }"
},
"hooks": {
"modify": "function(track, feature, div) { div.style.padding='4px'; div.style.backgroundColor = ['#17487d','#5190d5','#c7daf1'][feature.get('phase')];}"
},
"tooltip": "<div style='line-height:1.7em'><b>{patric_id}</b> | {refseq_locus_tag} | {alt_locus_Tag} | {gene}<br>{product}<br>{type}: {start_str} .. {end} ({strand_str})<br> <i>Click for detail information</i></div>",
"metadata": {
"Description": "PATRIC annotated genes"
},
"maxExportFeatures": 10000,
"maxExportSpan": 10000000,
"region_stats": true
}
, {
"type": "FeatureTrack",
// "urlTemplate": apiRoot + "/genome/" +req.params.id + "/{refseq}?annotation=RefSeq",
// "storeClass": "JBrowse/Store/SeqFeature/NCList",
"storeClass": "JBrowse/Store/SeqFeature/REST",
"baseUrl": apiRoot + "/genome/" + req.params.id,
"query": {
annotation: "RefSeq"
},
"key": "RefSeq Annotation",
"label": "RefSeqGenes",
"style": {
"className": "feature3",
"label": "function( feature ) { return feature.refseq_locus_tag; }"
},
"hooks": {
"modify": "function(track, feature, div) { div.style.backgroundColor = ['#4c5e22','#9ab957','#c4d59b'][feature.get('phase')];}"
},
"tooltip": "<div style='line-height:1.7em'><b>{refseq_locus_tag}</b> | {gene}<br>{product}<br>{type}: {start_str} .. {end} ({strand_str})<br> <i>Click for detail information</i></div>",
"metadata": {
"Description": "RefSeq annotated genes"
},
"maxExportFeatures": 10000,
"maxExportSpan": 10000000,
"region_stats": true
}
],
"formatVersion": 1
})
}
router.use(httpParams);
router.use(authMiddleware);
router.use(PublicDataTypes);
router.get("/genome/:id/trackList", [
function(req,res,next){
res.write(generateTrackList(req,res,next));
res.end();
}
])
router.get("/genome/:id/tracks", [
function(req,res,next){
res.write("[]");
res.end();
}
])
router.get("/genome/:id/stats/global",[
function(req,res,next){
res.write('{}');
res.end();
}
])
router.get("/genome/:id/stats/region/:feature_id",[
function(req,res,next){
res.end();
}
])
router.get("/genome/:id/stats/regionFeatureDensities/:feature_id",[
function(req,res,next){
res.end();
}
])
router.get("/genome/:id/features/:feature_id",[
function(req,res,next){
console.log("req.params: ", req.params, "req.query: ", req.query);
var start = req.query.start || req.params.start;
var end = req.query.end || req.params.end;
var annotation = req.query.annotation || req.params.annotation || "PATRIC"
req.call_collection = "genome_feature";
req.call_method = "query";
var st = "and(lt(start,"+start+"),gt(end,"+start+"))"
var en = "and(lt(start,"+end+"),gt(end,"+end+"))"
req.call_params = ["and(eq(genome_id," + req.params.id + "),eq(accession," +req.params.feature_id + "),eq(annotation," + annotation + "),or(" +st+"," + en + "))"];
req.queryType = "rql";
console.log("CALL_PARAMS: ", req.call_params);
next();
},
RQLQueryParser,
DecorateQuery,
Limiter,
APIMethodHandler,
function(req,res,next){
console.log("res.results: ", res.results)
if (res.results && res.results.response && res.results.response.docs){
var features = res.results.response.docs.map(function(d){
d.seq= d.na_sequence;
d.type=d.feature_type;
d.name=d.accession;
d.uniqueID=d.feature_id;
d.strand=(d.strand=="+")?1:-1;
d.phase=(d.feature_type=="CDS")?0:((d.feature_type=="RNA")?1:2);
return d;
})
console.log("FEATURES: ", features)
res.json({features: features});
res.end();
}
}
])
router.get("/genome/:id/refseqs", [
function(req,res,next){
req.call_collection = "genome_sequence";
req.call_method = "query";
req.call_params = ["&eq(genome_id," + req.params.id + ")&select(topology,gi,accession,length,sequence_id,gc_content,owner,sequence_type,taxon_id,public,genome_id,genome_name,date_inserted,date_modified)&sort(+accession)"];
req.queryType = "rql";
next();
},
RQLQueryParser,
DecorateQuery,
Limiter,
APIMethodHandler,
function(req,res,next){
console.log("Res.results: ", res.results);
if (res.results && res.results.response && res.results.response.docs){
var refseqs = res.results.response.docs.map(function(d){
return {
length: d.length,
name: d.accession,
accn: d.accession,
sid: d.genome_id,
start: 0,
end: d.length,
seqDir: "",
seqChunkSize: d.length
}
})
res.json(refseqs);
res.end();
}
}
])
module.exports = router;
| fix query for features
| routes/JBrowse.js | fix query for features | <ide><path>outes/JBrowse.js
<ide> var annotation = req.query.annotation || req.params.annotation || "PATRIC"
<ide> req.call_collection = "genome_feature";
<ide> req.call_method = "query";
<del> var st = "and(lt(start,"+start+"),gt(end,"+start+"))"
<del> var en = "and(lt(start,"+end+"),gt(end,"+end+"))"
<del> req.call_params = ["and(eq(genome_id," + req.params.id + "),eq(accession," +req.params.feature_id + "),eq(annotation," + annotation + "),or(" +st+"," + en + "))"];
<add> var st = "and(gt(start,"+start+"),lt(start,"+end+"))"
<add> var en = "and(gt(end,"+start+"),lt(end,"+end+"))"
<add> req.call_params = ["and(eq(genome_id," + req.params.id + "),eq(accession," +req.params.feature_id + "),eq(annotation," + annotation + "),or(" +st+"," + en + "),ne(feature_type,source))"];
<ide> req.queryType = "rql";
<ide> console.log("CALL_PARAMS: ", req.call_params);
<ide> next(); |
|
Java | mit | d53ee845ce7c3b3d5c2b0a5c816a6098ed942683 | 0 | sikuli/sikuli-slides,sikuli/sikuli-slides,sikuli/sikuli-slides | /**
Khalid
*/
package org.sikuli.slides.shapes;
import org.sikuli.slides.core.SlideComponent;
import org.sikuli.slides.sikuli.SlideAction;
import org.sikuli.slides.utils.Constants.DesktopEvent;
public class SlideShape {
private String id;
private String name;
private String type;
private int offx;
private int offy;
private int cx;
private int cy;
private int width;
private int height;
private String text;
private int order;
private int textSize;
private String backgroundColor;
public SlideShape(String id, String name, int order, String type,
int offx, int offy, int cx, int cy, String backgroundColor){
this.id=id;
this.name=name;
this.order=order;
this.type=type;
this.offx=offx;
this.offy=offy;
this.cx=cx;
this.cy=cy;
this.backgroundColor=backgroundColor;
}
/**
*
* @return shape id
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* returns the shape type or the geometry of the shape. In Office Open XML
* , the pre-defined shape type is specified with an attribute "prst"
* on the <a:prstGeom> element in each slide file.
* @return the geometry or form of a shape
*/
public String getType() {
return type;
}
/**
* sets the geometry or form of a shape.
* @param type the pre-defined shape type
*/
public void setType(String type) {
this.type = type;
}
public int getOffx() {
return offx;
}
public void setOffx(int offx) {
this.offx = offx;
}
public int getOffy() {
return offy;
}
public void setOffy(int offy) {
this.offy = offy;
}
public int getCx() {
return cx;
}
public void setCx(int cx) {
this.cx = cx;
}
public int getCy() {
return cy;
}
public void setCy(int cy) {
this.cy = cy;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public int getTextSize() {
return textSize;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
public void doSikuliAction(SlideComponent slideComponent,DesktopEvent desktopEvent){
SlideAction slideAction=new SlideAction(slideComponent);
slideAction.doSlideAction(desktopEvent);
}
@Override
public String toString(){
return "id="+id+" name="+name+
"\n offx="+offx+"\n offy="+offy+"\n cx="+cx+"\n cy="+cy
+"\n"+"width="+width+"\n"+"height="+height
+"\n"+"text: "+text+"\n order="+order+"\n"+
"background color= "+backgroundColor+
"font size="+textSize;
}
}
| src/main/java/org/sikuli/slides/shapes/SlideShape.java | /**
Khalid
*/
package org.sikuli.slides.shapes;
import org.sikuli.slides.core.SlideComponent;
import org.sikuli.slides.sikuli.SlideAction;
import org.sikuli.slides.utils.Constants.DesktopEvent;
public class SlideShape {
private String id;
private String name;
private String type;
private int offx;
private int offy;
private int cx;
private int cy;
private int width;
private int height;
private String text;
private int order;
private int textSize;
private String backgroundColor;
public SlideShape(String id, String name, int order, String type,
int offx, int offy, int cx, int cy, String backgroundColor){
this.id=id;
this.name=name;
this.order=order;
this.type=type;
this.offx=offx;
this.offy=offy;
this.cx=cx;
this.cy=cy;
this.backgroundColor=backgroundColor;
}
/**
*
* @return shape id
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* returns the shape type or the geometry of the shape. In Office Open XML
* , the pre-defined shape type is specified with an attribute "prst"
* on the <a:prstGeom> element in each slide file.
* @return the geometry or form of a shape
*/
public String getType() {
return type;
}
/**
* sets the geometry or form of a shape.
* @param type the pre-defined shape type
*/
public void setType(String type) {
this.type = type;
}
public int getOffx() {
return offx;
}
public void setOffx(int offx) {
this.offx = offx;
}
public int getOffy() {
return offy;
}
public void setOffy(int offy) {
this.offy = offy;
}
public int getCx() {
return cx;
}
public void setCx(int cx) {
this.cx = cx;
}
public int getCy() {
return cy;
}
public void setCy(int cy) {
this.cy = cy;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public int getTextSize() {
return textSize;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
public void doSikuliAction(SlideComponent slideComponent,DesktopEvent desktopEvent){
SlideAction slideAction=new SlideAction(slideComponent);
slideAction.doSikuliAction(desktopEvent);
}
@Override
public String toString(){
return "id="+id+" name="+name+
"\n offx="+offx+"\n offy="+offy+"\n cx="+cx+"\n cy="+cy
+"\n"+"width="+width+"\n"+"height="+height
+"\n"+"text: "+text+"\n order="+order+"\n"+
"background color= "+backgroundColor+
"font size="+textSize;
}
}
| chang method name
| src/main/java/org/sikuli/slides/shapes/SlideShape.java | chang method name | <ide><path>rc/main/java/org/sikuli/slides/shapes/SlideShape.java
<ide>
<ide> public void doSikuliAction(SlideComponent slideComponent,DesktopEvent desktopEvent){
<ide> SlideAction slideAction=new SlideAction(slideComponent);
<del> slideAction.doSikuliAction(desktopEvent);
<add> slideAction.doSlideAction(desktopEvent);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 21b14b5dad7e035b99243f95ff0c516fb0b1b710 | 0 | nssales/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,jerome79/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.convention;
import static com.opengamma.core.id.ExternalSchemes.bloombergTickerSecurityId;
import static com.opengamma.core.id.ExternalSchemes.icapSecurityId;
import static com.opengamma.core.id.ExternalSchemes.tullettPrebonSecurityId;
import static com.opengamma.financial.convention.InMemoryConventionBundleMaster.simpleNameSecurityId;
import org.threeten.bp.Period;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.financial.analytics.ircurve.IndexType;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventionFactory;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.financial.convention.frequency.Frequency;
import com.opengamma.financial.convention.frequency.PeriodFrequency;
import com.opengamma.financial.convention.frequency.SimpleFrequencyFactory;
import com.opengamma.financial.convention.yield.SimpleYieldConvention;
import com.opengamma.financial.sensitivities.FactorExposureData;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.ArgumentChecker;
/**
* Contains information used to construct standard versions of USD instruments.
*/
public class USConventions {
/**
* Adds conventions for deposit, Libor fixings, swaps, FRAs and IR futures.
* @param conventionMaster The convention master, not null
*/
public static synchronized void addFixedIncomeInstrumentConventions(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final BusinessDayConvention modified = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following");
final BusinessDayConvention following = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following");
final DayCount act360 = DayCountFactory.INSTANCE.getDayCount("Actual/360");
final DayCount thirty360 = DayCountFactory.INSTANCE.getDayCount("30/360");
final Frequency annual = PeriodFrequency.ANNUAL;
final Frequency semiAnnual = SimpleFrequencyFactory.INSTANCE.getFrequency(Frequency.SEMI_ANNUAL_NAME);
final Frequency quarterly = SimpleFrequencyFactory.INSTANCE.getFrequency(Frequency.QUARTERLY_NAME);
final ExternalId usgb = ExternalSchemes.financialRegionId("US+GB");
final ExternalId us = ExternalSchemes.financialRegionId("US");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
// LIBOR
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US00O/N Index"), simpleNameSecurityId("USD LIBOR O/N")),
"USD LIBOR O/N", act360, following, Period.ofDays(1), 0, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US00T/N Index"), simpleNameSecurityId("USD LIBOR T/N")),
"USD LIBOR T/N", act360, following, Period.ofDays(1), 1, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0001W Index"), simpleNameSecurityId("USD LIBOR 1w"),
tullettPrebonSecurityId("ASLIBUSD1WL")), "USD LIBOR 1w", act360, following, Period.ofDays(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0002W Index"), simpleNameSecurityId("USD LIBOR 2w"),
tullettPrebonSecurityId("ASLIBUSD2WL")), "USD LIBOR 2w", act360, following, Period.ofDays(14), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0001M Index"), simpleNameSecurityId("USD LIBOR 1m"),
tullettPrebonSecurityId("ASLIBUSD01L")), "USD LIBOR 1m", act360, modified, Period.ofMonths(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0002M Index"), simpleNameSecurityId("USD LIBOR 2m"),
tullettPrebonSecurityId("ASLIBUSD02L")), "USD LIBOR 2m", act360, modified, Period.ofMonths(2), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0003M Index"), simpleNameSecurityId("USD LIBOR 3m"),
ExternalSchemes.ricSecurityId("USD3MFSR="), tullettPrebonSecurityId("ASLIBUSD03L")),
"USD LIBOR 3m", act360, modified, Period.ofMonths(3), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0004M Index"), simpleNameSecurityId("USD LIBOR 4m"),
tullettPrebonSecurityId("ASLIBUSD04L")), "USD LIBOR 4m", act360, modified, Period.ofMonths(4), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0005M Index"), simpleNameSecurityId("USD LIBOR 5m"),
tullettPrebonSecurityId("ASLIBUSD05L")), "USD LIBOR 5m", act360, modified, Period.ofMonths(5), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0006M Index"), simpleNameSecurityId("USD LIBOR 6m"),
tullettPrebonSecurityId("ASLIBUSD06L")), "USD LIBOR 6m", act360, modified, Period.ofMonths(6), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0007M Index"), simpleNameSecurityId("USD LIBOR 7m"),
tullettPrebonSecurityId("ASLIBUSD07L")), "USD LIBOR 7m", act360, modified, Period.ofMonths(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0008M Index"), simpleNameSecurityId("USD LIBOR 8m"),
tullettPrebonSecurityId("ASLIBUSD08L")), "USD LIBOR 8m", act360, modified, Period.ofMonths(8), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0009M Index"), simpleNameSecurityId("USD LIBOR 9m"),
tullettPrebonSecurityId("ASLIBUSD09L")), "USD LIBOR 9m", act360, modified, Period.ofMonths(9), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0010M Index"), simpleNameSecurityId("USD LIBOR 10m"),
tullettPrebonSecurityId("ASLIBUSD10L")), "USD LIBOR 10m", act360, modified, Period.ofMonths(10), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0011M Index"), simpleNameSecurityId("USD LIBOR 11m"),
tullettPrebonSecurityId("ASLIBUSD11L")), "USD LIBOR 11m", act360, modified, Period.ofMonths(11), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0012M Index"), simpleNameSecurityId("USD LIBOR 12m"),
tullettPrebonSecurityId("ASLIBUSD12L")), "USD LIBOR 12m", act360, modified, Period.ofMonths(12), 2, false, us);
//TODO need to check that these are right for deposit rates
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR1T Curncy"), simpleNameSecurityId("USD DEPOSIT 1d")),
"USD DEPOSIT 1d", act360, following, Period.ofDays(1), 0, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR2T Curncy"), simpleNameSecurityId("USD DEPOSIT 2d")),
"USD DEPOSIT 2d", act360, following, Period.ofDays(1), 1, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR3T Curncy"), simpleNameSecurityId("USD DEPOSIT 3d")),
"USD DEPOSIT 3d", act360, following, Period.ofDays(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR1Z Curncy"), simpleNameSecurityId("USD DEPOSIT 1w"),
tullettPrebonSecurityId("ASDEPUSDSPT01W"), icapSecurityId("USD_1W")), "USD DEPOSIT 1w", act360, following, Period.ofDays(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR2Z Curncy"), simpleNameSecurityId("USD DEPOSIT 2w"),
tullettPrebonSecurityId("ASDEPUSDSPT02W"), icapSecurityId("USD_2W")), "USD DEPOSIT 2w", act360, following, Period.ofDays(14), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR3Z Curncy"), simpleNameSecurityId("USD DEPOSIT 3w"),
tullettPrebonSecurityId("ASDEPUSDSPT03W"), icapSecurityId("USD_3W")), "USD DEPOSIT 3w", act360, following, Period.ofDays(21), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRA Curncy"), simpleNameSecurityId("USD DEPOSIT 1m"),
tullettPrebonSecurityId("ASDEPUSDSPT01M"), icapSecurityId("USD_1M")), "USD DEPOSIT 1m", act360, following, Period.ofMonths(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRB Curncy"), simpleNameSecurityId("USD DEPOSIT 2m"),
tullettPrebonSecurityId("ASDEPUSDSPT02M"), icapSecurityId("USD_2M")), "USD DEPOSIT 2m", act360, following, Period.ofMonths(2), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRC Curncy"), simpleNameSecurityId("USD DEPOSIT 3m"),
tullettPrebonSecurityId("ASDEPUSDSPT03M"), icapSecurityId("USD_3M")), "USD DEPOSIT 3m", act360, following, Period.ofMonths(3), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRD Curncy"), simpleNameSecurityId("USD DEPOSIT 4m"),
tullettPrebonSecurityId("ASDEPUSDSPT04M"), icapSecurityId("USD_4M")), "USD DEPOSIT 4m", act360, following, Period.ofMonths(4), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRE Curncy"), simpleNameSecurityId("USD DEPOSIT 5m"),
tullettPrebonSecurityId("ASDEPUSDSPT05M"), icapSecurityId("USD_5M")), "USD DEPOSIT 5m", act360, following, Period.ofMonths(5), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRF Curncy"), simpleNameSecurityId("USD DEPOSIT 6m"),
tullettPrebonSecurityId("ASDEPUSDSPT06M"), icapSecurityId("USD_6M")), "USD DEPOSIT 6m", act360, following, Period.ofMonths(6), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRG Curncy"), simpleNameSecurityId("USD DEPOSIT 7m"),
tullettPrebonSecurityId("ASDEPUSDSPT07M"), icapSecurityId("USD_7M")), "USD DEPOSIT 7m", act360, following, Period.ofMonths(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRH Curncy"), simpleNameSecurityId("USD DEPOSIT 8m"),
tullettPrebonSecurityId("ASDEPUSDSPT08M"), icapSecurityId("USD_8M")), "USD DEPOSIT 8m", act360, following, Period.ofMonths(8), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRI Curncy"), simpleNameSecurityId("USD DEPOSIT 9m"),
tullettPrebonSecurityId("ASDEPUSDSPT09M"), icapSecurityId("USD_9M")), "USD DEPOSIT 9m", act360, following, Period.ofMonths(9), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRJ Curncy"), simpleNameSecurityId("USD DEPOSIT 10m"),
tullettPrebonSecurityId("ASDEPUSDSPT10M"), icapSecurityId("USD_10M")), "USD DEPOSIT 10m", act360, following, Period.ofMonths(10), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRK Curncy"), simpleNameSecurityId("USD DEPOSIT 11m"),
tullettPrebonSecurityId("ASDEPUSDSPT11M"), icapSecurityId("USD_11M")), "USD DEPOSIT 11m", act360, following, Period.ofMonths(11), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR1 Curncy"), simpleNameSecurityId("USD DEPOSIT 1y"),
tullettPrebonSecurityId("ASDEPUSDSPT12M"), icapSecurityId("USD_12M")), "USD DEPOSIT 1y", act360, following, Period.ofYears(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR2 Curncy"), simpleNameSecurityId("USD DEPOSIT 2y")),
"USD DEPOSIT 2y", act360, following, Period.ofYears(2), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR3 Curncy"), simpleNameSecurityId("USD DEPOSIT 3y")),
"USD DEPOSIT 3y", act360, following, Period.ofYears(3), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR4 Curncy"), simpleNameSecurityId("USD DEPOSIT 4y")),
"USD DEPOSIT 4y", act360, following, Period.ofYears(4), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR5 Curncy"), simpleNameSecurityId("USD DEPOSIT 5y")),
"USD DEPOSIT 5y", act360, following, Period.ofYears(5), 2, false, us);
//TODO with improvement in settlement days definition (i.e. including holiday and adjustment) change this
// should be 2, LON, following
// holiday for swap should be NY+LON
final DayCount swapFixedDayCount = thirty360;
final BusinessDayConvention swapFixedBusinessDay = modified;
final Frequency swapFixedPaymentFrequency = semiAnnual;
final DayCount swapFloatDayCount = act360;
final BusinessDayConvention swapFloatBusinessDay = modified;
final Frequency swapFloatPaymentFrequency = quarterly;
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_SWAP")), "USD_SWAP", swapFixedDayCount, swapFixedBusinessDay,
swapFixedPaymentFrequency, 2, usgb, swapFloatDayCount, swapFloatBusinessDay, swapFloatPaymentFrequency, 2, simpleNameSecurityId("USD LIBOR 3m"),
usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_3M_SWAP")), "USD_3M_SWAP", swapFixedDayCount, swapFixedBusinessDay,
swapFixedPaymentFrequency, 2, usgb, swapFloatDayCount, swapFloatBusinessDay, quarterly, 2, simpleNameSecurityId("USD LIBOR 3m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_6M_SWAP")), "USD_6M_SWAP", swapFixedDayCount, swapFixedBusinessDay,
swapFixedPaymentFrequency, 2, usgb, swapFloatDayCount, swapFloatBusinessDay, semiAnnual, 2, simpleNameSecurityId("USD LIBOR 6m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_IR_FUTURE")), "USD_IR_FUTURE", act360, modified, Period.ofMonths(3), 2, false,
null);
final int publicationLag = 1;
// Fed Fund effective
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("FEDL01 Index"), simpleNameSecurityId("USD FF EFFECTIVE")),
"USD FF EFFECTIVE", act360, following, Period.ofDays(1), 2, false, us, publicationLag);
// OIS swap
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_OIS_SWAP")), "USD_OIS_SWAP", thirty360, modified, annual, 2, usgb, thirty360,
modified, annual, 2, simpleNameSecurityId("USD FF EFFECTIVE"), usgb, true, publicationLag);
// FRA conventions are stored as IRS
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_3M_FRA")), "USD_3M_FRA", thirty360, modified, quarterly, 2, usgb, act360,
modified, quarterly, 2, simpleNameSecurityId("USD LIBOR 3m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_6M_FRA")), "USD_6M_FRA", thirty360, modified, semiAnnual, 2, usgb, act360,
modified, semiAnnual, 2, simpleNameSecurityId("USD LIBOR 6m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_TENOR_SWAP")), "USD_TENOR_SWAP", act360, modified, quarterly, 2,
simpleNameSecurityId("USD FF 3m"), usgb, act360, modified, quarterly, 2,
simpleNameSecurityId("USD LIBOR 3m"), usgb);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_SWAPTION")), "USD_SWAPTION", true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_GENERIC_CASH")), "USD_GENERIC_CASH", act360, following, Period.ofDays(7), 2,
true, null);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId(IndexType.Libor + "_USD_P3M")), IndexType.Libor + "_USD_P3M", thirty360, modified,
null, 2, false, usgb);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId(IndexType.Libor + "_USD_P6M")), IndexType.Libor + "_USD_P6M", thirty360, modified,
null, 2, false, usgb);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_BASIS_SWAP")), "USD_BASIS_SWAP", act360, modified, quarterly, 2,
null, usgb, act360, modified, quarterly, 2, null, usgb);
// Inflation
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("CPURNSA Index"), simpleNameSecurityId("USD CPI")),
"USD CPI", act360, modified, Period.ofMonths(1), 2, false, us);
// TODO: Add all ISDA fixing
final int[] isdaFixTenor = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30 };
// ISDA fixing 11.00 New-York
for (final int element : isdaFixTenor) {
final String tenorString = element + "Y";
final String tenorStringBbg = String.format("%02d", element);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_ISDAFIX_USDLIBOR10_" + tenorString),
ExternalSchemes.ricSecurityId("USDSFIX" + tenorString + "="), bloombergTickerSecurityId("USSW" + tenorStringBbg + " Curncy")),
"USSW" + tenorString, swapFixedDayCount, swapFixedBusinessDay, swapFixedPaymentFrequency, 2, us, act360, modified, semiAnnual, 2,
simpleNameSecurityId("USD LIBOR 3m"), us, true, Period.ofYears(element));
}
//Identifiers for external data
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.1M").toBundle(), "IR.SWAP.USD.1M", act360, modified, Period.ofMonths(1), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.6M").toBundle(), "IR.SWAP.USD.6M", act360, modified, Period.ofMonths(6), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.12M").toBundle(), "IR.SWAP.USD.12M", act360, modified, Period.ofMonths(12), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.24M").toBundle(), "IR.SWAP.USD.24M", act360, modified, Period.ofMonths(24), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.36M").toBundle(), "IR.SWAP.USD.36M", act360, modified, Period.ofMonths(36), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.60M").toBundle(), "IR.SWAP.USD.60M", act360, modified, Period.ofMonths(60), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.84M").toBundle(), "IR.SWAP.USD.84M", act360, modified, Period.ofMonths(84), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.120M").toBundle(), "IR.SWAP.USD.120M", act360, modified, Period.ofMonths(120), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.360M").toBundle(), "IR.SWAP.USD.360M", act360, modified, Period.ofMonths(360), 2, false, null);
}
/**
* @param conventionMaster The convention master, not null
*/
public static void addCAPMConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_CAPM")), "USD_CAPM",
ExternalIdBundle.of(bloombergTickerSecurityId("US0003M Index")), ExternalIdBundle.of(bloombergTickerSecurityId("SPX Index")));
}
/**
* Adds conventions for US Treasury bonds,
* @param conventionMaster The convention master, not null
*/
public static void addTreasuryBondConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("US_TREASURY_BOND_CONVENTION")), "US_TREASURY_BOND_CONVENTION", true, true, 0, 1,
true);
}
/**
* Adds conventions for USD-denominated corporate bonds
* @param conventionMaster The convention master, not null
*/
//TODO need to get the correct convention
public static void addCorporateBondConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("US_CORPORATE_BOND_CONVENTION")), "US_CORPORATE_BOND_CONVENTION", true, true, 0, 1,
true);
}
/**
* Add conventions for USD bond futures
* @param conventionMaster The convention master, not null
*/
public static void addBondFutureConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_BOND_FUTURE_DELIVERABLE_CONVENTION")),
"USD_BOND_FUTURE_DELIVERABLE_CONVENTION", true, true, 0, 0, DayCountFactory.INSTANCE.getDayCount("Actual/360"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following"),
SimpleYieldConvention.MONEY_MARKET);
}
}
| projects/OG-Financial/src/main/java/com/opengamma/financial/convention/USConventions.java | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.convention;
import static com.opengamma.core.id.ExternalSchemes.bloombergTickerSecurityId;
import static com.opengamma.core.id.ExternalSchemes.icapSecurityId;
import static com.opengamma.core.id.ExternalSchemes.tullettPrebonSecurityId;
import static com.opengamma.financial.convention.InMemoryConventionBundleMaster.simpleNameSecurityId;
import org.threeten.bp.Period;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.financial.analytics.ircurve.IndexType;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventionFactory;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.financial.convention.frequency.Frequency;
import com.opengamma.financial.convention.frequency.PeriodFrequency;
import com.opengamma.financial.convention.frequency.SimpleFrequencyFactory;
import com.opengamma.financial.convention.yield.SimpleYieldConvention;
import com.opengamma.financial.sensitivities.FactorExposureData;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.ArgumentChecker;
/**
* Contains information used to construct standard versions of USD instruments.
*/
public class USConventions {
/**
* Adds conventions for deposit, Libor fixings, swaps, FRAs and IR futures.
* @param conventionMaster The convention master, not null
*/
public static synchronized void addFixedIncomeInstrumentConventions(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final BusinessDayConvention modified = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following");
final BusinessDayConvention following = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following");
final DayCount act360 = DayCountFactory.INSTANCE.getDayCount("Actual/360");
final DayCount thirty360 = DayCountFactory.INSTANCE.getDayCount("30/360");
final Frequency annual = PeriodFrequency.ANNUAL;
final Frequency semiAnnual = SimpleFrequencyFactory.INSTANCE.getFrequency(Frequency.SEMI_ANNUAL_NAME);
final Frequency quarterly = SimpleFrequencyFactory.INSTANCE.getFrequency(Frequency.QUARTERLY_NAME);
final ExternalId usgb = ExternalSchemes.financialRegionId("US+GB");
final ExternalId us = ExternalSchemes.financialRegionId("US");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
// LIBOR
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US00O/N Index"), simpleNameSecurityId("USD LIBOR O/N")),
"USD LIBOR O/N", act360, following, Period.ofDays(1), 0, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US00T/N Index"), simpleNameSecurityId("USD LIBOR T/N")),
"USD LIBOR T/N", act360, following, Period.ofDays(1), 1, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0001W Index"), simpleNameSecurityId("USD LIBOR 1w"),
tullettPrebonSecurityId("ASLIBUSD1WL")), "USD LIBOR 1w", act360, following, Period.ofDays(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0002W Index"), simpleNameSecurityId("USD LIBOR 2w"),
tullettPrebonSecurityId("ASLIBUSD2WL")), "USD LIBOR 2w", act360, following, Period.ofDays(14), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0001M Index"), simpleNameSecurityId("USD LIBOR 1m"),
tullettPrebonSecurityId("ASLIBUSD01L")), "USD LIBOR 1m", act360, modified, Period.ofMonths(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0002M Index"), simpleNameSecurityId("USD LIBOR 2m"),
tullettPrebonSecurityId("ASLIBUSD02L")), "USD LIBOR 2m", act360, modified, Period.ofMonths(2), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0003M Index"), simpleNameSecurityId("USD LIBOR 3m"),
ExternalSchemes.ricSecurityId("USD3MFSR="), tullettPrebonSecurityId("ASLIBUSD03L")),
"USD LIBOR 3m", act360, modified, Period.ofMonths(3), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0004M Index"), simpleNameSecurityId("USD LIBOR 4m"),
tullettPrebonSecurityId("ASLIBUSD04L")), "USD LIBOR 4m", act360, modified, Period.ofMonths(4), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0005M Index"), simpleNameSecurityId("USD LIBOR 5m"),
tullettPrebonSecurityId("ASLIBUSD05L")), "USD LIBOR 5m", act360, modified, Period.ofMonths(5), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0006M Index"), simpleNameSecurityId("USD LIBOR 6m"),
tullettPrebonSecurityId("ASLIBUSD06L")), "USD LIBOR 6m", act360, modified, Period.ofMonths(6), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0007M Index"), simpleNameSecurityId("USD LIBOR 7m"),
tullettPrebonSecurityId("ASLIBUSD07L")), "USD LIBOR 7m", act360, modified, Period.ofMonths(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0008M Index"), simpleNameSecurityId("USD LIBOR 8m"),
tullettPrebonSecurityId("ASLIBUSD08L")), "USD LIBOR 8m", act360, modified, Period.ofMonths(8), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0009M Index"), simpleNameSecurityId("USD LIBOR 9m"),
tullettPrebonSecurityId("ASLIBUSD09L")), "USD LIBOR 9m", act360, modified, Period.ofMonths(9), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0010M Index"), simpleNameSecurityId("USD LIBOR 10m"),
tullettPrebonSecurityId("ASLIBUSD10L")), "USD LIBOR 10m", act360, modified, Period.ofMonths(10), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0011M Index"), simpleNameSecurityId("USD LIBOR 11m"),
tullettPrebonSecurityId("ASLIBUSD11L")), "USD LIBOR 11m", act360, modified, Period.ofMonths(11), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("US0012M Index"), simpleNameSecurityId("USD LIBOR 12m"),
tullettPrebonSecurityId("ASLIBUSD12L")), "USD LIBOR 12m", act360, modified, Period.ofMonths(12), 2, false, us);
//TODO need to check that these are right for deposit rates
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR1T Curncy"), simpleNameSecurityId("USD DEPOSIT 1d")),
"USD DEPOSIT 1d", act360, following, Period.ofDays(1), 0, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR2T Curncy"), simpleNameSecurityId("USD DEPOSIT 2d")),
"USD DEPOSIT 2d", act360, following, Period.ofDays(1), 1, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR3T Curncy"), simpleNameSecurityId("USD DEPOSIT 3d")),
"USD DEPOSIT 3d", act360, following, Period.ofDays(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR1Z Curncy"), simpleNameSecurityId("USD DEPOSIT 1w"),
tullettPrebonSecurityId("ASDEPUSDSPT01W"), icapSecurityId("USD_1W")), "USD DEPOSIT 1w", act360, following, Period.ofDays(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR2Z Curncy"), simpleNameSecurityId("USD DEPOSIT 2w"),
tullettPrebonSecurityId("ASDEPUSDSPT02W"), icapSecurityId("USD_2W")), "USD DEPOSIT 2w", act360, following, Period.ofDays(14), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR3Z Curncy"), simpleNameSecurityId("USD DEPOSIT 3w"),
tullettPrebonSecurityId("ASDEPUSDSPT03W"), icapSecurityId("USD_3W")), "USD DEPOSIT 3w", act360, following, Period.ofDays(21), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRA Curncy"), simpleNameSecurityId("USD DEPOSIT 1m"),
tullettPrebonSecurityId("ASDEPUSDSPT01M"), icapSecurityId("USD_1M")), "USD DEPOSIT 1m", act360, following, Period.ofMonths(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRB Curncy"), simpleNameSecurityId("USD DEPOSIT 2m"),
tullettPrebonSecurityId("ASDEPUSDSPT02M"), icapSecurityId("USD_2M")), "USD DEPOSIT 2m", act360, following, Period.ofMonths(2), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRC Curncy"), simpleNameSecurityId("USD DEPOSIT 3m"),
tullettPrebonSecurityId("ASDEPUSDSPT03M"), icapSecurityId("USD_3M")), "USD DEPOSIT 3m", act360, following, Period.ofMonths(3), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRD Curncy"), simpleNameSecurityId("USD DEPOSIT 4m"),
tullettPrebonSecurityId("ASDEPUSDSPT04M"), icapSecurityId("USD_4M")), "USD DEPOSIT 4m", act360, following, Period.ofMonths(4), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRE Curncy"), simpleNameSecurityId("USD DEPOSIT 5m"),
tullettPrebonSecurityId("ASDEPUSDSPT05M"), icapSecurityId("USD_5M")), "USD DEPOSIT 5m", act360, following, Period.ofMonths(5), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRF Curncy"), simpleNameSecurityId("USD DEPOSIT 6m"),
tullettPrebonSecurityId("ASDEPUSDSPT06M"), icapSecurityId("USD_6M")), "USD DEPOSIT 6m", act360, following, Period.ofMonths(6), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRG Curncy"), simpleNameSecurityId("USD DEPOSIT 7m"),
tullettPrebonSecurityId("ASDEPUSDSPT07M"), icapSecurityId("USD_7M")), "USD DEPOSIT 7m", act360, following, Period.ofMonths(7), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRH Curncy"), simpleNameSecurityId("USD DEPOSIT 8m"),
tullettPrebonSecurityId("ASDEPUSDSPT08M"), icapSecurityId("USD_8M")), "USD DEPOSIT 8m", act360, following, Period.ofMonths(8), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRI Curncy"), simpleNameSecurityId("USD DEPOSIT 9m"),
tullettPrebonSecurityId("ASDEPUSDSPT09M"), icapSecurityId("USD_9M")), "USD DEPOSIT 9m", act360, following, Period.ofMonths(9), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRJ Curncy"), simpleNameSecurityId("USD DEPOSIT 10m"),
tullettPrebonSecurityId("ASDEPUSDSPT10M"), icapSecurityId("USD_10M")), "USD DEPOSIT 10m", act360, following, Period.ofMonths(10), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDRK Curncy"), simpleNameSecurityId("USD DEPOSIT 11m"),
tullettPrebonSecurityId("ASDEPUSDSPT11M"), icapSecurityId("USD_11M")), "USD DEPOSIT 11m", act360, following, Period.ofMonths(11), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR1 Curncy"), simpleNameSecurityId("USD DEPOSIT 1y"),
tullettPrebonSecurityId("ASDEPUSDSPT12M"), icapSecurityId("USD_12M")), "USD DEPOSIT 1y", act360, following, Period.ofYears(1), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR2 Curncy"), simpleNameSecurityId("USD DEPOSIT 2y")),
"USD DEPOSIT 2y", act360, following, Period.ofYears(2), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR3 Curncy"), simpleNameSecurityId("USD DEPOSIT 3y")),
"USD DEPOSIT 3y", act360, following, Period.ofYears(3), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR4 Curncy"), simpleNameSecurityId("USD DEPOSIT 4y")),
"USD DEPOSIT 4y", act360, following, Period.ofYears(4), 2, false, us);
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("USDR5 Curncy"), simpleNameSecurityId("USD DEPOSIT 5y")),
"USD DEPOSIT 5y", act360, following, Period.ofYears(5), 2, false, us);
//TODO with improvement in settlement days definition (i.e. including holiday and adjustment) change this
// should be 2, LON, following
// holiday for swap should be NY+LON
final DayCount swapFixedDayCount = thirty360;
final BusinessDayConvention swapFixedBusinessDay = modified;
final Frequency swapFixedPaymentFrequency = semiAnnual;
final DayCount swapFloatDayCount = act360;
final BusinessDayConvention swapFloatBusinessDay = modified;
final Frequency swapFloatPaymentFrequency = quarterly;
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_SWAP")), "USD_SWAP", swapFixedDayCount, swapFixedBusinessDay,
swapFixedPaymentFrequency, 2, usgb, swapFloatDayCount, swapFloatBusinessDay, swapFloatPaymentFrequency, 2, simpleNameSecurityId("USD LIBOR 3m"),
usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_3M_SWAP")), "USD_3M_SWAP", swapFixedDayCount, swapFixedBusinessDay,
swapFixedPaymentFrequency, 2, usgb, swapFloatDayCount, swapFloatBusinessDay, quarterly, 2, simpleNameSecurityId("USD LIBOR 3m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_6M_SWAP")), "USD_6M_SWAP", swapFixedDayCount, swapFixedBusinessDay,
swapFixedPaymentFrequency, 2, usgb, swapFloatDayCount, swapFloatBusinessDay, semiAnnual, 2, simpleNameSecurityId("USD LIBOR 6m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_IR_FUTURE")), "USD_IR_FUTURE", act360, modified, Period.ofMonths(3), 2, false,
null);
final int publicationLag = 1;
// Fed Fund effective
utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("FEDL01 Index"), simpleNameSecurityId("USD FF EFFECTIVE")),
"USD FF EFFECTIVE", act360, following, Period.ofDays(1), 2, false, us, publicationLag);
// OIS swap
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_OIS_SWAP")), "USD_OIS_SWAP", thirty360, modified, annual, 2, usgb, thirty360,
modified, annual, 2, simpleNameSecurityId("USD FF EFFECTIVE"), usgb, true, publicationLag);
// FRA conventions are stored as IRS
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_3M_FRA")), "USD_3M_FRA", thirty360, modified, quarterly, 2, usgb, act360,
modified, quarterly, 2, simpleNameSecurityId("USD LIBOR 3m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_6M_FRA")), "USD_6M_FRA", thirty360, modified, semiAnnual, 2, usgb, act360,
modified, semiAnnual, 2, simpleNameSecurityId("USD LIBOR 6m"), usgb, true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_TENOR_SWAP")), "USD_TENOR_SWAP", act360, modified, quarterly, 2,
simpleNameSecurityId("USD FF 3m"), usgb, act360, modified, quarterly, 2,
simpleNameSecurityId("USD LIBOR 3m"), usgb);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_SWAPTION")), "USD_SWAPTION", true);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_GENERIC_CASH")), "USD_GENERIC_CASH", act360, following, Period.ofDays(7), 2,
true, null);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId(IndexType.Libor + "_USD_P3M")), IndexType.Libor + "_USD_P3M", thirty360, modified,
null, 2, false, usgb);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId(IndexType.Libor + "_USD_P6M")), IndexType.Libor + "_USD_P6M", thirty360, modified,
null, 2, false, usgb);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_BASIS_SWAP")), "USD_BASIS_SWAP", act360, modified, quarterly, 2,
null, usgb, act360, modified, quarterly, 2, null, usgb);
// TODO: Add all ISDA fixing
final int[] isdaFixTenor = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30 };
// ISDA fixing 11.00 New-York
for (final int element : isdaFixTenor) {
final String tenorString = element + "Y";
final String tenorStringBbg = String.format("%02d", element);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_ISDAFIX_USDLIBOR10_" + tenorString),
ExternalSchemes.ricSecurityId("USDSFIX" + tenorString + "="), bloombergTickerSecurityId("USSW" + tenorStringBbg + " Curncy")),
"USSW" + tenorString, swapFixedDayCount, swapFixedBusinessDay, swapFixedPaymentFrequency, 2, us, act360, modified, semiAnnual, 2,
simpleNameSecurityId("USD LIBOR 3m"), us, true, Period.ofYears(element));
}
//Identifiers for external data
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.1M").toBundle(), "IR.SWAP.USD.1M", act360, modified, Period.ofMonths(1), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.6M").toBundle(), "IR.SWAP.USD.6M", act360, modified, Period.ofMonths(6), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.12M").toBundle(), "IR.SWAP.USD.12M", act360, modified, Period.ofMonths(12), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.24M").toBundle(), "IR.SWAP.USD.24M", act360, modified, Period.ofMonths(24), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.36M").toBundle(), "IR.SWAP.USD.36M", act360, modified, Period.ofMonths(36), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.60M").toBundle(), "IR.SWAP.USD.60M", act360, modified, Period.ofMonths(60), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.84M").toBundle(), "IR.SWAP.USD.84M", act360, modified, Period.ofMonths(84), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.120M").toBundle(), "IR.SWAP.USD.120M", act360, modified, Period.ofMonths(120), 2, false, null);
utils.addConventionBundle(ExternalId.of(FactorExposureData.FACTOR_SCHEME, "IR.SWAP.USD.360M").toBundle(), "IR.SWAP.USD.360M", act360, modified, Period.ofMonths(360), 2, false, null);
}
/**
* @param conventionMaster The convention master, not null
*/
public static void addCAPMConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_CAPM")), "USD_CAPM",
ExternalIdBundle.of(bloombergTickerSecurityId("US0003M Index")), ExternalIdBundle.of(bloombergTickerSecurityId("SPX Index")));
}
/**
* Adds conventions for US Treasury bonds,
* @param conventionMaster The convention master, not null
*/
public static void addTreasuryBondConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("US_TREASURY_BOND_CONVENTION")), "US_TREASURY_BOND_CONVENTION", true, true, 0, 1,
true);
}
/**
* Adds conventions for USD-denominated corporate bonds
* @param conventionMaster The convention master, not null
*/
//TODO need to get the correct convention
public static void addCorporateBondConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("US_CORPORATE_BOND_CONVENTION")), "US_CORPORATE_BOND_CONVENTION", true, true, 0, 1,
true);
}
/**
* Add conventions for USD bond futures
* @param conventionMaster The convention master, not null
*/
public static void addBondFutureConvention(final ConventionBundleMaster conventionMaster) {
ArgumentChecker.notNull(conventionMaster, "convention master");
final ConventionBundleMasterUtils utils = new ConventionBundleMasterUtils(conventionMaster);
utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_BOND_FUTURE_DELIVERABLE_CONVENTION")),
"USD_BOND_FUTURE_DELIVERABLE_CONVENTION", true, true, 0, 0, DayCountFactory.INSTANCE.getDayCount("Actual/360"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following"),
SimpleYieldConvention.MONEY_MARKET);
}
}
| [PLAT-4632] Added USD inflation convention bundle
| projects/OG-Financial/src/main/java/com/opengamma/financial/convention/USConventions.java | [PLAT-4632] Added USD inflation convention bundle | <ide><path>rojects/OG-Financial/src/main/java/com/opengamma/financial/convention/USConventions.java
<ide> null, 2, false, usgb);
<ide> utils.addConventionBundle(ExternalIdBundle.of(simpleNameSecurityId("USD_BASIS_SWAP")), "USD_BASIS_SWAP", act360, modified, quarterly, 2,
<ide> null, usgb, act360, modified, quarterly, 2, null, usgb);
<add>
<add> // Inflation
<add> utils.addConventionBundle(ExternalIdBundle.of(bloombergTickerSecurityId("CPURNSA Index"), simpleNameSecurityId("USD CPI")),
<add> "USD CPI", act360, modified, Period.ofMonths(1), 2, false, us);
<ide>
<ide> // TODO: Add all ISDA fixing
<ide> final int[] isdaFixTenor = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30 }; |
|
Java | lgpl-2.1 | a9a9d76afab5b8fbbb4b796105b1d8f82cdffd54 | 0 | pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.gwt.wysiwyg.client.plugin.macro.ui;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.xwiki.gwt.user.client.Config;
import org.xwiki.gwt.user.client.StringUtils;
import org.xwiki.gwt.wysiwyg.client.Strings;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.MacroCall;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.MacroDescriptor;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.MacroServiceAsync;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.ParameterDescriptor;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.ParameterDisplayer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
/**
* Wizard step for editing macro parameters and content.
*
* @version $Id$
*/
public class EditMacroWizardStep extends AbstractMacroWizardStep
{
/**
* The call-back used by the edit dialog to be notified when a macro descriptor is being received from the server.
* Only the last request for a macro descriptor triggers an update of the edit dialog.
*/
private class MacroDescriptorAsyncCallback implements AsyncCallback<MacroDescriptor>
{
/**
* The index of the request.
*/
private int index;
/**
* The call-back used to notify the wizard that this wizard step has finished loading.
*/
private final AsyncCallback< ? > wizardCallback;
/**
* Creates a new call-back for the request with the specified index.
*
* @param wizardCallback the call-back used to notify the wizard that this wizard step has finished loading
*/
public MacroDescriptorAsyncCallback(AsyncCallback< ? > wizardCallback)
{
this.wizardCallback = wizardCallback;
this.index = ++macroDescriptorRequestIndex;
}
/**
* {@inheritDoc}
*
* @see AsyncCallback#onFailure(Throwable)
*/
public void onFailure(Throwable caught)
{
wizardCallback.onFailure(caught);
}
/**
* {@inheritDoc}
*
* @see AsyncCallback#onSuccess(Object)
*/
public void onSuccess(MacroDescriptor result)
{
// If this is the response to the last request and the wizard step wasn't canceled in the mean time then..
if (index == macroDescriptorRequestIndex && macroCall != null) {
fill(result);
wizardCallback.onSuccess(null);
}
}
}
/**
* The input and output of this wizard step. The macro call being edited.
*
* @see #init(Object, AsyncCallback)
* @see #getResult()
*/
private MacroCall macroCall;
/**
* Describes the macro used in {@link #macroCall}.
*/
private MacroDescriptor macroDescriptor;
/**
* The index of the last request for a macro descriptor.
*/
private int macroDescriptorRequestIndex = -1;
/**
* Displays the content of a macro and allows us to edit it.
*/
private ParameterDisplayer contentDisplayer;
/**
* A parameter displayer shows the value of a macro parameter and allows us to edit it.
*/
private final List<ParameterDisplayer> parameterDisplayers = new ArrayList<ParameterDisplayer>();
/**
* Creates a new wizard step for editing macro parameters and content.
*
* @param config the object used to configure the newly created wizard step
* @param macroService the macro service used to retrieve macro descriptors
*/
public EditMacroWizardStep(Config config, MacroServiceAsync macroService)
{
super(config, macroService);
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#getResult()
*/
public Object getResult()
{
return macroCall;
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#getStepTitle()
*/
public String getStepTitle()
{
String macroName =
macroDescriptor != null ? macroDescriptor.getName() : (macroCall != null ? macroCall.getName() : null);
return Strings.INSTANCE.macro() + (macroName != null ? " : " + macroName : "");
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#init(Object, AsyncCallback)
*/
public void init(Object data, AsyncCallback< ? > cb)
{
// Reset the model.
macroCall = (MacroCall) data;
macroDescriptor = null;
// Reset the UI.
getPanel().clear();
parameterDisplayers.clear();
contentDisplayer = null;
getMacroService().getMacroDescriptor(macroCall.getName(), getConfig().getParameter("syntax"),
new MacroDescriptorAsyncCallback(cb));
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#onCancel()
*/
public void onCancel()
{
macroCall = null;
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#onSubmit(AsyncCallback)
*/
public void onSubmit(AsyncCallback<Boolean> async)
{
if (validate()) {
updateMacroCall();
async.onSuccess(true);
} else {
async.onSuccess(false);
}
}
/**
* Validate all the parameters and focus the first that has an illegal value.
*
* @return {@code true} if the current parameter values and the current content are valid, {@code false} otherwise
*/
private boolean validate()
{
ParameterDisplayer failed = contentDisplayer == null || contentDisplayer.validate() ? null : contentDisplayer;
for (int i = parameterDisplayers.size() - 1; i >= 0; i--) {
ParameterDisplayer displayer = parameterDisplayers.get(i);
if (!displayer.validate()) {
failed = displayer;
}
}
if (failed != null) {
failed.setFocused(true);
return false;
}
return true;
}
/**
* Updates the macro call based on the current parameter values.
*/
private void updateMacroCall()
{
for (ParameterDisplayer displayer : parameterDisplayers) {
String value = displayer.getValue();
ParameterDescriptor descriptor = displayer.getDescriptor();
if (StringUtils.isEmpty(value)
|| (!descriptor.isMandatory() && value.equalsIgnoreCase(descriptor.getDefaultValue()))) {
macroCall.removeArgument(descriptor.getId());
} else {
macroCall.setArgument(descriptor.getId(), value);
}
}
if (contentDisplayer != null) {
macroCall.setContent(contentDisplayer.getValue());
}
}
/**
* Fills the wizard step with the controls needed to edit the underlying macro.
*
* @param macroDescriptor describes the edited macro
*/
private void fill(MacroDescriptor macroDescriptor)
{
this.macroDescriptor = macroDescriptor;
// Display the macro description.
Label macroDescription = new Label(macroDescriptor.getDescription());
macroDescription.addStyleName("xMacroDescription");
getPanel().add(macroDescription);
// Display the macro parameters.
for (Map.Entry<String, ParameterDescriptor> entry : macroDescriptor.getParameterDescriptorMap().entrySet()) {
ParameterDisplayer displayer = new ParameterDisplayer(entry.getValue());
String value = macroCall.getArgument(entry.getKey());
if (value == null) {
// Display the default value if the macro call doesn't specify one.
value = entry.getValue().getDefaultValue();
}
displayer.setValue(value);
parameterDisplayers.add(displayer);
getPanel().add(displayer.getWidget());
}
// Display the content of the macro.
if (macroDescriptor.getContentDescriptor() != null) {
contentDisplayer = new ParameterDisplayer(macroDescriptor.getContentDescriptor());
contentDisplayer.setValue(macroCall.getContent());
getPanel().add(contentDisplayer.getWidget());
}
// Focus the first input control.
if (parameterDisplayers.size() > 0) {
parameterDisplayers.get(0).setFocused(true);
} else if (contentDisplayer != null) {
contentDisplayer.setFocused(true);
}
}
}
| xwiki-platform-web/xwiki-gwt-wysiwyg-client/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/macro/ui/EditMacroWizardStep.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.gwt.wysiwyg.client.plugin.macro.ui;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.xwiki.gwt.user.client.Config;
import org.xwiki.gwt.user.client.StringUtils;
import org.xwiki.gwt.wysiwyg.client.Strings;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.MacroCall;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.MacroDescriptor;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.MacroServiceAsync;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.ParameterDescriptor;
import org.xwiki.gwt.wysiwyg.client.plugin.macro.ParameterDisplayer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
/**
* Wizard step for editing macro parameters and content.
*
* @version $Id$
*/
public class EditMacroWizardStep extends AbstractMacroWizardStep
{
/**
* The call-back used by the edit dialog to be notified when a macro descriptor is being received from the server.
* Only the last request for a macro descriptor triggers an update of the edit dialog.
*/
private class MacroDescriptorAsyncCallback implements AsyncCallback<MacroDescriptor>
{
/**
* The index of the request.
*/
private int index;
/**
* The call-back used to notify the wizard that this wizard step has finished loading.
*/
private final AsyncCallback< ? > wizardCallback;
/**
* Creates a new call-back for the request with the specified index.
*
* @param wizardCallback the call-back used to notify the wizard that this wizard step has finished loading
*/
public MacroDescriptorAsyncCallback(AsyncCallback< ? > wizardCallback)
{
this.wizardCallback = wizardCallback;
this.index = ++macroDescriptorRequestIndex;
}
/**
* {@inheritDoc}
*
* @see AsyncCallback#onFailure(Throwable)
*/
public void onFailure(Throwable caught)
{
wizardCallback.onFailure(caught);
}
/**
* {@inheritDoc}
*
* @see AsyncCallback#onSuccess(Object)
*/
public void onSuccess(MacroDescriptor result)
{
// If this is the response to the last request and the wizard step wasn't canceled in the mean time then..
if (index == macroDescriptorRequestIndex && macroCall != null) {
fill(result);
wizardCallback.onSuccess(null);
}
}
}
/**
* The input and output of this wizard step. The macro call being edited.
*
* @see #init(Object, AsyncCallback)
* @see #getResult()
*/
private MacroCall macroCall;
/**
* Describes the macro used in {@link #macroCall}.
*/
private MacroDescriptor macroDescriptor;
/**
* The index of the last request for a macro descriptor.
*/
private int macroDescriptorRequestIndex = -1;
/**
* Displays the content of a macro and allows us to edit it.
*/
private ParameterDisplayer contentDisplayer;
/**
* A parameter displayer shows the value of a macro parameter and allows us to edit it.
*/
private final List<ParameterDisplayer> parameterDisplayers = new ArrayList<ParameterDisplayer>();
/**
* Creates a new wizard step for editing macro parameters and content.
*
* @param config the object used to configure the newly created wizard step
* @param macroService the macro service used to retrieve macro descriptors
*/
public EditMacroWizardStep(Config config, MacroServiceAsync macroService)
{
super(config, macroService);
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#getResult()
*/
public Object getResult()
{
return macroCall;
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#getStepTitle()
*/
public String getStepTitle()
{
String macroName =
macroDescriptor != null ? macroDescriptor.getName() : (macroCall != null ? macroCall.getName() : null);
return Strings.INSTANCE.macro() + (macroName != null ? " : " + macroName : "");
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#init(Object, AsyncCallback)
*/
public void init(Object data, AsyncCallback< ? > cb)
{
// Reset the model.
macroCall = (MacroCall) data;
macroDescriptor = null;
// Reset the UI.
getPanel().clear();
parameterDisplayers.clear();
contentDisplayer = null;
getMacroService().getMacroDescriptor(macroCall.getName(), getConfig().getParameter("syntax"),
new MacroDescriptorAsyncCallback(cb));
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#onCancel()
*/
public void onCancel()
{
macroCall = null;
}
/**
* {@inheritDoc}
*
* @see AbstractMacroWizardStep#onSubmit(AsyncCallback)
*/
public void onSubmit(AsyncCallback<Boolean> async)
{
if (validate()) {
updateMacroCall();
async.onSuccess(true);
} else {
async.onSuccess(false);
}
}
/**
* Validate all the parameters and focus the first that has an illegal value.
*
* @return {@code true} if the current parameter values and the current content are valid, {@code false} otherwise
*/
private boolean validate()
{
ParameterDisplayer failed = contentDisplayer == null || contentDisplayer.validate() ? null : contentDisplayer;
for (int i = parameterDisplayers.size() - 1; i >= 0; i--) {
ParameterDisplayer displayer = parameterDisplayers.get(i);
if (!displayer.validate()) {
failed = displayer;
}
}
if (failed != null) {
failed.setFocused(true);
return false;
}
return true;
}
/**
* Updates the macro call based on the current parameter values.
*/
private void updateMacroCall()
{
for (ParameterDisplayer displayer : parameterDisplayers) {
String value = displayer.getValue();
ParameterDescriptor descriptor = displayer.getDescriptor();
if (StringUtils.isEmpty(value) || value.equalsIgnoreCase(descriptor.getDefaultValue())) {
macroCall.removeArgument(descriptor.getId());
} else {
macroCall.setArgument(descriptor.getId(), value);
}
}
if (contentDisplayer != null) {
macroCall.setContent(contentDisplayer.getValue());
}
}
/**
* Fills the wizard step with the controls needed to edit the underlying macro.
*
* @param macroDescriptor describes the edited macro
*/
private void fill(MacroDescriptor macroDescriptor)
{
this.macroDescriptor = macroDescriptor;
// Display the macro description.
Label macroDescription = new Label(macroDescriptor.getDescription());
macroDescription.addStyleName("xMacroDescription");
getPanel().add(macroDescription);
// Display the macro parameters.
for (Map.Entry<String, ParameterDescriptor> entry : macroDescriptor.getParameterDescriptorMap().entrySet()) {
ParameterDisplayer displayer = new ParameterDisplayer(entry.getValue());
String value = macroCall.getArgument(entry.getKey());
if (value == null) {
// Display the default value if the macro call doesn't specify one.
value = entry.getValue().getDefaultValue();
}
displayer.setValue(value);
parameterDisplayers.add(displayer);
getPanel().add(displayer.getWidget());
}
// Display the content of the macro.
if (macroDescriptor.getContentDescriptor() != null) {
contentDisplayer = new ParameterDisplayer(macroDescriptor.getContentDescriptor());
contentDisplayer.setValue(macroCall.getContent());
getPanel().add(contentDisplayer.getWidget());
}
// Focus the first input control.
if (parameterDisplayers.size() > 0) {
parameterDisplayers.get(0).setFocused(true);
} else if (contentDisplayer != null) {
contentDisplayer.setFocused(true);
}
}
}
| XWIKI-4946: Default values for the required macro parameters should be send to the server by the WYSIWYG.
git-svn-id: 04343649e741710b2e0f622af6defd1ac33e5ca5@27639 f329d543-caf0-0310-9063-dda96c69346f
| xwiki-platform-web/xwiki-gwt-wysiwyg-client/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/macro/ui/EditMacroWizardStep.java | XWIKI-4946: Default values for the required macro parameters should be send to the server by the WYSIWYG. | <ide><path>wiki-platform-web/xwiki-gwt-wysiwyg-client/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/macro/ui/EditMacroWizardStep.java
<ide> for (ParameterDisplayer displayer : parameterDisplayers) {
<ide> String value = displayer.getValue();
<ide> ParameterDescriptor descriptor = displayer.getDescriptor();
<del> if (StringUtils.isEmpty(value) || value.equalsIgnoreCase(descriptor.getDefaultValue())) {
<add> if (StringUtils.isEmpty(value)
<add> || (!descriptor.isMandatory() && value.equalsIgnoreCase(descriptor.getDefaultValue()))) {
<ide> macroCall.removeArgument(descriptor.getId());
<ide> } else {
<ide> macroCall.setArgument(descriptor.getId(), value); |
|
Java | agpl-3.0 | 4e918c7fa9a31e4b572f904bdab7c2898d4b766a | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 19f8597e-2e60-11e5-9284-b827eb9e62be | hello.java | 19f2f646-2e60-11e5-9284-b827eb9e62be | 19f8597e-2e60-11e5-9284-b827eb9e62be | hello.java | 19f8597e-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>19f2f646-2e60-11e5-9284-b827eb9e62be
<add>19f8597e-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 074309a27c500e0a355a3e5bcfcf57d8e248213d | 0 | boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk,boundary/boundary-event-sdk | src/main/java/com/boundary/sdk/EventIntegrationApp.java | package com.boundary.sdk;
import org.apache.camel.spring.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EventIntegrationApp
{
private static Logger LOG = LoggerFactory.getLogger(EventIntegrationApp.class);
private Main main;
public static void main(String[] args) throws Exception
{
EventIntegrationApp app = new EventIntegrationApp();
app.boot();
}
private void boot() throws Exception
{
// create a Main instance
main = new Main();
// enable hangup support so you can press ctrl + c to terminate the JVM
main.enableHangupSupport();
main.setApplicationContextUri("META-INF/event-application.xml");
// TODO Fixed values, need to make externally configurable
String orgID = "3ehRi7uZeeaTN12dErF5XOnRXjC";
String apiKey = "GN5HMCeu9trD5NYO5ZqYQrZe8aY";
// main.addRouteBuilder(new EventRoute(orgID,apiKey));
// main.addRouteBuilder(new BoundaryEventRoute(orgID,apiKey));
main.addRouteBuilder(new SNMPRoute());
// run until you terminate the JVM
System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
main.run();
}
}
| Deprecated code
| src/main/java/com/boundary/sdk/EventIntegrationApp.java | Deprecated code | <ide><path>rc/main/java/com/boundary/sdk/EventIntegrationApp.java
<del>package com.boundary.sdk;
<del>import org.apache.camel.spring.Main;
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<del>
<del>public class EventIntegrationApp
<del>{
<del> private static Logger LOG = LoggerFactory.getLogger(EventIntegrationApp.class);
<del>
<del> private Main main;
<del>
<del> public static void main(String[] args) throws Exception
<del> {
<del> EventIntegrationApp app = new EventIntegrationApp();
<del> app.boot();
<del> }
<del>
<del> private void boot() throws Exception
<del> {
<del> // create a Main instance
<del> main = new Main();
<del> // enable hangup support so you can press ctrl + c to terminate the JVM
<del> main.enableHangupSupport();
<del> main.setApplicationContextUri("META-INF/event-application.xml");
<del>
<del> // TODO Fixed values, need to make externally configurable
<del> String orgID = "3ehRi7uZeeaTN12dErF5XOnRXjC";
<del> String apiKey = "GN5HMCeu9trD5NYO5ZqYQrZe8aY";
<del>
<del>// main.addRouteBuilder(new EventRoute(orgID,apiKey));
<del>// main.addRouteBuilder(new BoundaryEventRoute(orgID,apiKey));
<del> main.addRouteBuilder(new SNMPRoute());
<del>
<del> // run until you terminate the JVM
<del> System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
<del> main.run();
<del> }
<del>} |
||
Java | bsd-3-clause | error: pathspec 'src/ibis/impl/messagePassing/SendSerializer.java' did not match any file(s) known to git
| a11d81e413283680acd1c0f8975bb5204c350d96 | 1 | interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl | package ibis.impl.messagePassing;
import ibis.ipl.IbisConfigurationException;
import ibis.util.ConditionVariable;
/**
* Provide multi-locks.
* If multiple send ports want to send to receive ports on one other CPU,
* flow control of the underlying message passing system requires that
* these messages are serialized, not interleaved.
* Solve this by locking the channel(s) to the cpu that underly the
* Ibis message.
* In the case of multicast, this is a special problem. because all
* channels must be locked at the same time.
*/
class SendSerializer {
private boolean[] locked;
private int[] waiting;
private ConditionVariable cv;
SendSerializer() {
if (Ibis.myIbis.nrCpus == 0) {
throw new IbisConfigurationException("Must set nrCpus before creating SendSerializer");
}
cv = Ibis.myIbis.createCV();
locked = new boolean[Ibis.myIbis.nrCpus];
waiting = new int[Ibis.myIbis.nrCpus];
}
private void lock(int i) {
locked[i] = true;
}
private boolean unlock(int i) {
if (i == Ibis.myIbis.myCpu) {
// No flow control at home
return false;
}
locked[i] = false;
return (waiting[i] > 0);
}
private boolean tryLock(int i) {
if (i == Ibis.myIbis.myCpu) {
// No flow control at home
return true;
}
if (locked[i]) {
return false;
}
locked[i] = true;
return true;
}
private void registerWaiting(int i) {
waiting[i]++;
}
private void unregisterWaiting(int i) {
waiting[i]--;
}
void lockAll(int[] cpu) {
Ibis.myIbis.checkLockOwned();
int locked;
do {
locked = 0;
for (int i = 0; i < cpu.length; i++) {
if (tryLock(cpu[i])) {
locked++;
} else {
/* Sorry, cannot lock all. Release the locks I already
* got, and try again */
boolean mustSignal = false;
for (int j = 0; j < i; j++) {
mustSignal |= unlock(cpu[j]);
}
for (int j = 0; j < cpu.length; j++) {
registerWaiting(cpu[j]);
}
if (mustSignal) {
cv.cv_bcast();
}
try {
cv.cv_wait();
} catch (InterruptedException e) {
// Ignore
}
for (int j = 0; j < cpu.length; j++) {
unregisterWaiting(cpu[j]);
}
break;
}
}
} while (locked < cpu.length);
}
void unlockAll(int[] cpu) {
Ibis.myIbis.checkLockOwned();
boolean mustSignal = false;
for (int i = 0; i < cpu.length; i++) {
mustSignal |= unlock(cpu[i]);
}
if (mustSignal) {
cv.cv_bcast();
}
}
}
| src/ibis/impl/messagePassing/SendSerializer.java | cvs add SendSerializer.java
git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@1289 aaf88347-d911-0410-b711-e54d386773bb
| src/ibis/impl/messagePassing/SendSerializer.java | cvs add SendSerializer.java | <ide><path>rc/ibis/impl/messagePassing/SendSerializer.java
<add>package ibis.impl.messagePassing;
<add>
<add>import ibis.ipl.IbisConfigurationException;
<add>import ibis.util.ConditionVariable;
<add>
<add>/**
<add> * Provide multi-locks.
<add> * If multiple send ports want to send to receive ports on one other CPU,
<add> * flow control of the underlying message passing system requires that
<add> * these messages are serialized, not interleaved.
<add> * Solve this by locking the channel(s) to the cpu that underly the
<add> * Ibis message.
<add> * In the case of multicast, this is a special problem. because all
<add> * channels must be locked at the same time.
<add> */
<add>
<add>class SendSerializer {
<add>
<add> private boolean[] locked;
<add> private int[] waiting;
<add> private ConditionVariable cv;
<add>
<add> SendSerializer() {
<add> if (Ibis.myIbis.nrCpus == 0) {
<add> throw new IbisConfigurationException("Must set nrCpus before creating SendSerializer");
<add> }
<add> cv = Ibis.myIbis.createCV();
<add> locked = new boolean[Ibis.myIbis.nrCpus];
<add> waiting = new int[Ibis.myIbis.nrCpus];
<add> }
<add>
<add>
<add> private void lock(int i) {
<add> locked[i] = true;
<add> }
<add>
<add>
<add> private boolean unlock(int i) {
<add> if (i == Ibis.myIbis.myCpu) {
<add> // No flow control at home
<add> return false;
<add> }
<add>
<add> locked[i] = false;
<add> return (waiting[i] > 0);
<add> }
<add>
<add>
<add> private boolean tryLock(int i) {
<add> if (i == Ibis.myIbis.myCpu) {
<add> // No flow control at home
<add> return true;
<add> }
<add>
<add> if (locked[i]) {
<add> return false;
<add> }
<add> locked[i] = true;
<add> return true;
<add> }
<add>
<add>
<add> private void registerWaiting(int i) {
<add> waiting[i]++;
<add> }
<add>
<add>
<add> private void unregisterWaiting(int i) {
<add> waiting[i]--;
<add> }
<add>
<add>
<add> void lockAll(int[] cpu) {
<add> Ibis.myIbis.checkLockOwned();
<add> int locked;
<add> do {
<add> locked = 0;
<add> for (int i = 0; i < cpu.length; i++) {
<add> if (tryLock(cpu[i])) {
<add> locked++;
<add> } else {
<add> /* Sorry, cannot lock all. Release the locks I already
<add> * got, and try again */
<add> boolean mustSignal = false;
<add> for (int j = 0; j < i; j++) {
<add> mustSignal |= unlock(cpu[j]);
<add> }
<add> for (int j = 0; j < cpu.length; j++) {
<add> registerWaiting(cpu[j]);
<add> }
<add> if (mustSignal) {
<add> cv.cv_bcast();
<add> }
<add>
<add> try {
<add> cv.cv_wait();
<add> } catch (InterruptedException e) {
<add> // Ignore
<add> }
<add>
<add> for (int j = 0; j < cpu.length; j++) {
<add> unregisterWaiting(cpu[j]);
<add> }
<add> break;
<add> }
<add> }
<add> } while (locked < cpu.length);
<add> }
<add>
<add>
<add> void unlockAll(int[] cpu) {
<add> Ibis.myIbis.checkLockOwned();
<add> boolean mustSignal = false;
<add> for (int i = 0; i < cpu.length; i++) {
<add> mustSignal |= unlock(cpu[i]);
<add> }
<add> if (mustSignal) {
<add> cv.cv_bcast();
<add> }
<add> }
<add>
<add>} |
|
Java | bsd-3-clause | c2e6bbedf772420362df2fac01ac5b589eae7719 | 0 | interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl | /* $Id$ */
package ibis.satin.impl;
import ibis.util.TypedProperties;
import org.apache.log4j.Logger;
/**
* Constants for the configuration of Satin. This interface is public because it
* is also used in code generated by the Satin frontend.
*/
public interface Config {
static final TypedProperties properties = TypedProperties.getDefaultConfigProperties();
static final String PROPERTY_PREFIX = "satin.";
static final String s_asserts = PROPERTY_PREFIX + "asserts";
static final String s_queue_steals = PROPERTY_PREFIX + "queueSteals";
static final String s_closed = PROPERTY_PREFIX + "closed";
static final String s_close_connections
= PROPERTY_PREFIX + "closeConnections";
static final String s_max_connections = PROPERTY_PREFIX + "maxConnections";
static final String s_connections_on_demand = PROPERTY_PREFIX + "connectionsOnDemand";
static final String s_keep_intra_connections = PROPERTY_PREFIX + "keepIntraConnections";
static final String s_throttle_steals = PROPERTY_PREFIX + "throttleSteals";
static final String s_max_steal_throttle = PROPERTY_PREFIX + "maxStealThrottle";
static final String s_stats = PROPERTY_PREFIX + "stats";
static final String s_detailed_stats = PROPERTY_PREFIX + "detailedStats";
static final String s_alg = PROPERTY_PREFIX + "alg";
static final String s_dump = PROPERTY_PREFIX + "dump";
static final String s_in_latency = PROPERTY_PREFIX + "messagesInLatency";
static final String s_so_delay = PROPERTY_PREFIX + "so.delay";
static final String s_so_size = PROPERTY_PREFIX + "so.size";
static final String s_so_lrmc = PROPERTY_PREFIX + "so.lrmc";
static final String s_so_wait_time = PROPERTY_PREFIX + "so.waitTime";
static final String s_ft_naive = PROPERTY_PREFIX + "ft.naive";
static final String s_ft_connectTimeout
= PROPERTY_PREFIX + "ft.connectTimeout";
static final String s_masterhost = PROPERTY_PREFIX + "masterHost";
static final String s_delete_time = PROPERTY_PREFIX + "deleteTime";
static final String s_steal_wait_timeout
= PROPERTY_PREFIX + "stealWaitTimeout";
static final String s_delete_cluster_time = PROPERTY_PREFIX
+ "deleteClusterTime";
static final String s_kill_time = PROPERTY_PREFIX + "killTime";
static final String[] sysprops = { s_stats, s_queue_steals,
s_detailed_stats, s_closed, s_asserts,
s_ft_naive, s_ft_connectTimeout, s_masterhost, s_in_latency,
s_delete_time, s_delete_cluster_time, s_kill_time, s_dump, s_so_delay,
s_so_size, s_alg, s_so_lrmc, s_close_connections, s_max_connections,
s_so_wait_time, s_steal_wait_timeout, s_connections_on_demand,
s_keep_intra_connections, s_throttle_steals, s_max_steal_throttle};
/** Enable or disable asserts. */
static final boolean ASSERTS = properties.getBooleanProperty(s_asserts, true);
/** True if the node should dump its datastructures during shutdown. */
static final boolean DUMP = properties.getBooleanProperty(s_dump, false);
/** Enable this if Satin should print statistics at the end. */
static final boolean STATS = properties.getBooleanProperty(s_stats, true);
/** Enable this if Satin should print statistics per machine at the end. */
static final boolean DETAILED_STATS = properties.getBooleanProperty(
s_detailed_stats, false);
/**
* Enable this if satin should run with a closed world: no nodes can join
* or leave.
*/
static final boolean CLOSED = properties.getBooleanProperty(s_closed, false);
/** Determines master hostname. */
static final String MASTER_HOST = properties.getProperty(s_masterhost);
/** Determines which load-balancing algorithm is used. */
static final String SUPPLIED_ALG = properties.getProperty(s_alg);
/**
* Fault tolerance with restarting crashed jobs, but without the global
* result table.
*/
static final boolean FT_NAIVE = properties.getBooleanProperty(s_ft_naive, false);
/** Enable or disable an optimization for handling delayed messages. */
static final boolean HANDLE_MESSAGES_IN_LATENCY = properties.getBooleanProperty(
s_in_latency, false);
/**
* Timeout for connecting to other nodes.
*/
public static final long CONNECT_TIMEOUT = properties.getLongProperty(
s_ft_connectTimeout, 60) * 1000L;
/** Timeout for waiting on a steal reply from another node. */
public static final long STEAL_WAIT_TIMEOUT = properties.getLongProperty(
s_steal_wait_timeout, CONNECT_TIMEOUT * 2 + 20 * 1000L);
/**
* Maximum time that messages may be buffered for message combining.
* If > 0, it is used for combining shared objects invocations.
* setting this to 0 disables message combining.
*/
static final int SO_MAX_INVOCATION_DELAY = properties.getIntProperty(
s_so_delay, 0);
/**
* The maximum message size if message combining is used for SO Invocations.
*/
static final int SO_MAX_MESSAGE_SIZE = properties.getIntProperty(s_so_size,
64 * 1024);
/** Wait time before requesting a shared object. */
static final int SO_WAIT_FOR_UPDATES_TIME
= properties.getIntProperty(s_so_wait_time, 60) * 1000;
/** Enable or disable label routing multicast for shared objects . */
static final boolean LABEL_ROUTING_MCAST = properties.getBooleanProperty(
s_so_lrmc, true);
/** Used in automatic ft tests */
static final int DELETE_TIME = properties.getIntProperty(s_delete_time, 0);
/** Used in automatic ft tests */
static final int DELETE_CLUSTER_TIME = properties.getIntProperty(
s_delete_cluster_time, 0);
/** Used in automatic ft tests */
static final int KILL_TIME = properties.getIntProperty(s_kill_time, 0);
/**
* Enable or disable using a seperate queue for work steal requests to
* avoid thread creation.
*/
static final boolean QUEUE_STEALS = properties.getBooleanProperty(s_queue_steals,
true);
/** Close connections after use. Used for scalability. */
static final boolean CLOSE_CONNECTIONS = properties.getBooleanProperty(
s_close_connections, true);
/** When using CLOSE_CONNECTIONS, keep open MAX_CONNECTIONS connections. */
static final int MAX_CONNECTIONS = properties.getIntProperty(s_max_connections,
64);
/** Setup connections as we need them. Used for scalability. */
static final boolean CONNECTIONS_ON_DEMAND = properties.getBooleanProperty(
s_connections_on_demand, true);
/** Do not steal as fast as we can, but use exponential backoff. */
static final boolean THROTTLE_STEALS = properties.getBooleanProperty(
s_throttle_steals, false);
/** the maximal time to sleep after a failed steal attempt in milliseconds */
static final int MAX_STEAL_THROTTLE = properties.getIntProperty(s_max_steal_throttle,
256);
/**
* When CLOSE_CONNECTIONS is set, keep intra-cluster connections.
* When set, MAX_CONNECTIONS is ignored.
*/
static final boolean KEEP_INTRA_CONNECTIONS = properties.getBooleanProperty(
s_keep_intra_connections, false);
/** Logger for communication. */
public static final Logger commLogger = Logger.getLogger("ibis.satin.comm");
/** Logger for connections. */
public static final Logger connLogger = Logger.getLogger("ibis.satin.conn");
/** Logger for job stealing. */
public static final Logger stealLogger = Logger.getLogger(
"ibis.satin.steal");
/** Logger for spawns. */
public static final Logger spawnLogger = Logger.getLogger(
"ibis.satin.spawn");
/** Logger for inlets. */
public static final Logger inletLogger = Logger.getLogger(
"ibis.satin.inlet");
/** Logger for aborts. */
public static final Logger abortLogger = Logger.getLogger(
"ibis.satin.abort");
/** Logger for fault tolerance. */
public static final Logger ftLogger = Logger.getLogger("ibis.satin.ft");
/** Logger for the global result table. */
public static final Logger grtLogger = Logger.getLogger(
"ibis.satin.ft.grt");
/** Logger for shared objects. */
public static final Logger soLogger = Logger.getLogger("ibis.satin.so");
/** Logger for shared objects broadcasts. */
public static final Logger soBcastLogger = Logger.getLogger("ibis.satin.so.bcast");
/** Generic logger. */
public static final Logger mainLogger = Logger.getLogger("ibis.satin");
}
| src/ibis/satin/impl/Config.java | /* $Id$ */
package ibis.satin.impl;
import ibis.util.TypedProperties;
import org.apache.log4j.Logger;
/**
* Constants for the configuration of Satin. This interface is public because it
* is also used in code generated by the Satin frontend.
*/
public interface Config {
static final TypedProperties properties = TypedProperties.getDefaultConfigProperties();
static final String PROPERTY_PREFIX = "satin.";
static final String s_asserts = PROPERTY_PREFIX + "asserts";
static final String s_queue_steals = PROPERTY_PREFIX + "queueSteals";
static final String s_closed = PROPERTY_PREFIX + "closed";
static final String s_localports = PROPERTY_PREFIX + "localPorts";
static final String s_close_connections
= PROPERTY_PREFIX + "closeConnections";
static final String s_max_connections = PROPERTY_PREFIX + "maxConnections";
static final String s_connections_on_demand = PROPERTY_PREFIX + "connectionsOnDemand";
static final String s_keep_intra_connections = PROPERTY_PREFIX + "keepIntraConnections";
static final String s_throttle_steals = PROPERTY_PREFIX + "throttleSteals";
static final String s_max_steal_throttle = PROPERTY_PREFIX + "maxStealThrottle";
static final String s_stats = PROPERTY_PREFIX + "stats";
static final String s_detailed_stats = PROPERTY_PREFIX + "detailedStats";
static final String s_alg = PROPERTY_PREFIX + "alg";
static final String s_dump = PROPERTY_PREFIX + "dump";
static final String s_in_latency = PROPERTY_PREFIX + "messagesInLatency";
static final String s_so_delay = PROPERTY_PREFIX + "so.delay";
static final String s_so_size = PROPERTY_PREFIX + "so.size";
static final String s_so_lrmc = PROPERTY_PREFIX + "so.lrmc";
static final String s_so_wait_time = PROPERTY_PREFIX + "so.waitTime";
static final String s_ft_naive = PROPERTY_PREFIX + "ft.naive";
static final String s_ft_connectTimeout
= PROPERTY_PREFIX + "ft.connectTimeout";
static final String s_masterhost = PROPERTY_PREFIX + "masterHost";
static final String s_delete_time = PROPERTY_PREFIX + "deleteTime";
static final String s_steal_wait_timeout
= PROPERTY_PREFIX + "stealWaitTimeout";
static final String s_delete_cluster_time = PROPERTY_PREFIX
+ "deleteClusterTime";
static final String s_kill_time = PROPERTY_PREFIX + "killTime";
static final String[] sysprops = { s_stats, s_queue_steals,
s_detailed_stats, s_closed, s_localports, s_asserts,
s_ft_naive, s_ft_connectTimeout, s_masterhost, s_in_latency,
s_delete_time, s_delete_cluster_time, s_kill_time, s_dump, s_so_delay,
s_so_size, s_alg, s_so_lrmc, s_close_connections, s_max_connections,
s_so_wait_time, s_steal_wait_timeout, s_connections_on_demand,
s_keep_intra_connections, s_throttle_steals, s_max_steal_throttle};
/** Enable or disable asserts. */
static final boolean ASSERTS = properties.getBooleanProperty(s_asserts, true);
/** True if the node should dump its datastructures during shutdown. */
static final boolean DUMP = properties.getBooleanProperty(s_dump, false);
/** Enable this if Satin should print statistics at the end. */
static final boolean STATS = properties.getBooleanProperty(s_stats, true);
/** Enable this if Satin should print statistics per machine at the end. */
static final boolean DETAILED_STATS = properties.getBooleanProperty(
s_detailed_stats, false);
/**
* Enable this if satin should run with a closed world: no nodes can join
* or leave.
*/
static final boolean CLOSED = properties.getBooleanProperty(s_closed, false);
/** Determines master hostname. */
static final String MASTER_HOST = properties.getProperty(s_masterhost);
/** Determines which load-balancing algorithm is used. */
static final String SUPPLIED_ALG = properties.getProperty(s_alg);
/**
* Fault tolerance with restarting crashed jobs, but without the global
* result table.
*/
static final boolean FT_NAIVE = properties.getBooleanProperty(s_ft_naive, false);
/** Enable or disable an optimization for handling delayed messages. */
static final boolean HANDLE_MESSAGES_IN_LATENCY = properties.getBooleanProperty(
s_in_latency, false);
/**
* Timeout for connecting to other nodes.
*/
public static final long CONNECT_TIMEOUT = properties.getLongProperty(
s_ft_connectTimeout, 60) * 1000L;
/** Timeout for waiting on a steal reply from another node. */
public static final long STEAL_WAIT_TIMEOUT = properties.getLongProperty(
s_steal_wait_timeout, CONNECT_TIMEOUT * 2 + 20 * 1000L);
/**
* Maximum time that messages may be buffered for message combining.
* If > 0, it is used for combining shared objects invocations.
* setting this to 0 disables message combining.
*/
static final int SO_MAX_INVOCATION_DELAY = properties.getIntProperty(
s_so_delay, 0);
/**
* The maximum message size if message combining is used for SO Invocations.
*/
static final int SO_MAX_MESSAGE_SIZE = properties.getIntProperty(s_so_size,
64 * 1024);
/** Wait time before requesting a shared object. */
static final int SO_WAIT_FOR_UPDATES_TIME
= properties.getIntProperty(s_so_wait_time, 60) * 1000;
/** Enable or disable label routing multicast for shared objects . */
static final boolean LABEL_ROUTING_MCAST = properties.getBooleanProperty(
s_so_lrmc, true);
/** Used in automatic ft tests */
static final int DELETE_TIME = properties.getIntProperty(s_delete_time, 0);
/** Used in automatic ft tests */
static final int DELETE_CLUSTER_TIME = properties.getIntProperty(
s_delete_cluster_time, 0);
/** Used in automatic ft tests */
static final int KILL_TIME = properties.getIntProperty(s_kill_time, 0);
/**
* Enable or disable using a seperate queue for work steal requests to
* avoid thread creation.
*/
static final boolean QUEUE_STEALS = properties.getBooleanProperty(s_queue_steals,
true);
/** Close connections after use. Used for scalability. */
static final boolean CLOSE_CONNECTIONS = properties.getBooleanProperty(
s_close_connections, true);
/** When using CLOSE_CONNECTIONS, keep open MAX_CONNECTIONS connections. */
static final int MAX_CONNECTIONS = properties.getIntProperty(s_max_connections,
64);
/** Setup connections as we need them. Used for scalability. */
static final boolean CONNECTIONS_ON_DEMAND = properties.getBooleanProperty(
s_connections_on_demand, true);
/** Do not steal as fast as we can, but use exponential backoff. */
static final boolean THROTTLE_STEALS = properties.getBooleanProperty(
s_throttle_steals, false);
/** the maximal time to sleep after a failed steal attempt in milliseconds */
static final int MAX_STEAL_THROTTLE = properties.getIntProperty(s_max_steal_throttle,
256);
/**
* When CLOSE_CONNECTIONS is set, keep intra-cluster connections.
* When set, MAX_CONNECTIONS is ignored.
*/
static final boolean KEEP_INTRA_CONNECTIONS = properties.getBooleanProperty(
s_keep_intra_connections, false);
/** Logger for communication. */
public static final Logger commLogger = Logger.getLogger("ibis.satin.comm");
/** Logger for connections. */
public static final Logger connLogger = Logger.getLogger("ibis.satin.conn");
/** Logger for job stealing. */
public static final Logger stealLogger = Logger.getLogger(
"ibis.satin.steal");
/** Logger for spawns. */
public static final Logger spawnLogger = Logger.getLogger(
"ibis.satin.spawn");
/** Logger for inlets. */
public static final Logger inletLogger = Logger.getLogger(
"ibis.satin.inlet");
/** Logger for aborts. */
public static final Logger abortLogger = Logger.getLogger(
"ibis.satin.abort");
/** Logger for fault tolerance. */
public static final Logger ftLogger = Logger.getLogger("ibis.satin.ft");
/** Logger for the global result table. */
public static final Logger grtLogger = Logger.getLogger(
"ibis.satin.ft.grt");
/** Logger for shared objects. */
public static final Logger soLogger = Logger.getLogger("ibis.satin.so");
/** Logger for shared objects broadcasts. */
public static final Logger soBcastLogger = Logger.getLogger("ibis.satin.so.bcast");
/** Generic logger. */
public static final Logger mainLogger = Logger.getLogger("ibis.satin");
}
| Removed satin.localPorts
git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@6308 aaf88347-d911-0410-b711-e54d386773bb
| src/ibis/satin/impl/Config.java | Removed satin.localPorts | <ide><path>rc/ibis/satin/impl/Config.java
<ide>
<ide> static final String s_closed = PROPERTY_PREFIX + "closed";
<ide>
<del> static final String s_localports = PROPERTY_PREFIX + "localPorts";
<del>
<ide> static final String s_close_connections
<ide> = PROPERTY_PREFIX + "closeConnections";
<ide>
<ide> static final String s_kill_time = PROPERTY_PREFIX + "killTime";
<ide>
<ide> static final String[] sysprops = { s_stats, s_queue_steals,
<del> s_detailed_stats, s_closed, s_localports, s_asserts,
<add> s_detailed_stats, s_closed, s_asserts,
<ide> s_ft_naive, s_ft_connectTimeout, s_masterhost, s_in_latency,
<ide> s_delete_time, s_delete_cluster_time, s_kill_time, s_dump, s_so_delay,
<ide> s_so_size, s_alg, s_so_lrmc, s_close_connections, s_max_connections, |
|
JavaScript | bsd-3-clause | a41aa56821346907cda083e10de074fe53e9c9a3 | 0 | primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.VBox}
* @param {!WebInspector.CanvasProfileHeader} profile
*/
WebInspector.CanvasProfileView = function(profile)
{
WebInspector.VBox.call(this);
this.registerRequiredCSS("canvasProfiler.css");
this.element.classList.add("canvas-profile-view");
this._profile = profile;
this._traceLogId = profile.traceLogId();
this._traceLogPlayer = /** @type {!WebInspector.CanvasTraceLogPlayerProxy} */ (profile.traceLogPlayer());
this._linkifier = new WebInspector.Linkifier();
this._replayInfoSplitView = new WebInspector.SplitView(true, true, "canvasProfileViewReplaySplitViewState", 0.34);
this._replayInfoSplitView.show(this.element);
this._imageSplitView = new WebInspector.SplitView(false, true, "canvasProfileViewSplitViewState", 300);
this._imageSplitView.show(this._replayInfoSplitView.mainElement());
var replayImageContainerView = new WebInspector.VBox();
replayImageContainerView.setMinimumSize(50, 28);
replayImageContainerView.show(this._imageSplitView.mainElement());
// NOTE: The replayImageContainer can NOT be a flex div (e.g. VBox or SplitView elements)!
var replayImageContainer = replayImageContainerView.element.createChild("div");
replayImageContainer.id = "canvas-replay-image-container";
this._replayImageElement = replayImageContainer.createChild("img", "canvas-replay-image");
this._debugInfoElement = replayImageContainer.createChild("div", "canvas-debug-info hidden");
this._spinnerIcon = replayImageContainer.createChild("div", "spinner-icon small hidden");
var replayLogContainerView = new WebInspector.VBox();
replayLogContainerView.setMinimumSize(22, 22);
replayLogContainerView.show(this._imageSplitView.sidebarElement());
var replayLogContainer = replayLogContainerView.element;
var controlsContainer = replayLogContainer.createChild("div", "status-bar");
var logGridContainer = replayLogContainer.createChild("div", "canvas-replay-log");
this._createControlButton(controlsContainer, "canvas-replay-first-step", WebInspector.UIString("First call."), this._onReplayFirstStepClick.bind(this));
this._createControlButton(controlsContainer, "canvas-replay-prev-step", WebInspector.UIString("Previous call."), this._onReplayStepClick.bind(this, false));
this._createControlButton(controlsContainer, "canvas-replay-next-step", WebInspector.UIString("Next call."), this._onReplayStepClick.bind(this, true));
this._createControlButton(controlsContainer, "canvas-replay-prev-draw", WebInspector.UIString("Previous drawing call."), this._onReplayDrawingCallClick.bind(this, false));
this._createControlButton(controlsContainer, "canvas-replay-next-draw", WebInspector.UIString("Next drawing call."), this._onReplayDrawingCallClick.bind(this, true));
this._createControlButton(controlsContainer, "canvas-replay-last-step", WebInspector.UIString("Last call."), this._onReplayLastStepClick.bind(this));
this._replayContextSelector = new WebInspector.StatusBarComboBox(this._onReplayContextChanged.bind(this));
this._replayContextSelector.createOption(WebInspector.UIString("<screenshot auto>"), WebInspector.UIString("Show screenshot of the last replayed resource."), "");
controlsContainer.appendChild(this._replayContextSelector.element);
this._installReplayInfoSidebarWidgets(controlsContainer);
this._replayStateView = new WebInspector.CanvasReplayStateView(this._traceLogPlayer);
this._replayStateView.show(this._replayInfoSplitView.sidebarElement());
/** @type {!Object.<string, boolean>} */
this._replayContexts = {};
var columns = [
{title: "#", sortable: false, width: "5%"},
{title: WebInspector.UIString("Call"), sortable: false, width: "75%", disclosure: true},
{title: WebInspector.UIString("Location"), sortable: false, width: "20%"}
];
this._logGrid = new WebInspector.DataGrid(columns);
this._logGrid.element.classList.add("fill");
this._logGrid.show(logGridContainer);
this._logGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._replayTraceLog, this);
this.element.addEventListener("mousedown", this._onMouseClick.bind(this), true);
this._popoverHelper = new WebInspector.ObjectPopoverHelper(this.element, this._popoverAnchor.bind(this), this._resolveObjectForPopover.bind(this), this._onHidePopover.bind(this), true);
this._popoverHelper.setRemoteObjectFormatter(this._hexNumbersFormatter.bind(this));
this._requestTraceLog(0);
}
/**
* @const
* @type {number}
*/
WebInspector.CanvasProfileView.TraceLogPollingInterval = 500;
WebInspector.CanvasProfileView.prototype = {
dispose: function()
{
this._linkifier.reset();
},
get statusBarItems()
{
return [];
},
get profile()
{
return this._profile;
},
/**
* @override
* @return {!Array.<!Element>}
*/
elementsToRestoreScrollPositionsFor: function()
{
return [this._logGrid.scrollContainer];
},
/**
* @param {!Element} controlsContainer
*/
_installReplayInfoSidebarWidgets: function(controlsContainer)
{
this._replayInfoResizeWidgetElement = controlsContainer.createChild("div", "resizer-widget");
this._replayInfoSplitView.addEventListener(WebInspector.SplitView.Events.ShowModeChanged, this._updateReplayInfoResizeWidget, this);
this._updateReplayInfoResizeWidget();
this._replayInfoSplitView.installResizer(this._replayInfoResizeWidgetElement);
this._toggleReplayStateSidebarButton = this._replayInfoSplitView.createShowHideSidebarButton("sidebar", "canvas-sidebar-show-hide-button");
controlsContainer.appendChild(this._toggleReplayStateSidebarButton.element);
this._replayInfoSplitView.hideSidebar();
},
_updateReplayInfoResizeWidget: function()
{
this._replayInfoResizeWidgetElement.classList.toggle("hidden", this._replayInfoSplitView.showMode() !== WebInspector.SplitView.ShowMode.Both);
},
/**
* @param {?Event} event
*/
_onMouseClick: function(event)
{
var resourceLinkElement = event.target.enclosingNodeOrSelfWithClass("canvas-formatted-resource");
if (resourceLinkElement) {
this._replayInfoSplitView.showBoth();
this._replayStateView.selectResource(resourceLinkElement.__resourceId);
event.consume(true);
return;
}
if (event.target.enclosingNodeOrSelfWithClass("webkit-html-resource-link"))
event.consume(false);
},
/**
* @param {!Element} parent
* @param {string} className
* @param {string} title
* @param {function(this:WebInspector.CanvasProfileView)} clickCallback
*/
_createControlButton: function(parent, className, title, clickCallback)
{
var button = new WebInspector.StatusBarButton(title, className + " canvas-replay-button");
parent.appendChild(button.element);
button.makeLongClickEnabled();
button.addEventListener("click", clickCallback, this);
button.addEventListener("longClickDown", clickCallback, this);
button.addEventListener("longClickPress", clickCallback, this);
},
_onReplayContextChanged: function()
{
var selectedContextId = this._replayContextSelector.selectedOption().value;
/**
* @param {?CanvasAgent.ResourceState} resourceState
* @this {WebInspector.CanvasProfileView}
*/
function didReceiveResourceState(resourceState)
{
this._enableWaitIcon(false);
if (selectedContextId !== this._replayContextSelector.selectedOption().value)
return;
var imageURL = (resourceState && resourceState.imageURL) || "";
this._replayImageElement.src = imageURL;
this._replayImageElement.style.visibility = imageURL ? "" : "hidden";
}
this._enableWaitIcon(true);
this._traceLogPlayer.getResourceState(selectedContextId, didReceiveResourceState.bind(this));
},
/**
* @param {boolean} forward
*/
_onReplayStepClick: function(forward)
{
var selectedNode = this._logGrid.selectedNode;
if (!selectedNode)
return;
var nextNode = selectedNode;
do {
nextNode = forward ? nextNode.traverseNextNode(false) : nextNode.traversePreviousNode(false);
} while (nextNode && typeof nextNode.index !== "number");
(nextNode || selectedNode).revealAndSelect();
},
/**
* @param {boolean} forward
*/
_onReplayDrawingCallClick: function(forward)
{
var selectedNode = this._logGrid.selectedNode;
if (!selectedNode)
return;
var nextNode = selectedNode;
while (nextNode) {
var sibling = forward ? nextNode.nextSibling : nextNode.previousSibling;
if (sibling) {
nextNode = sibling;
if (nextNode.hasChildren || nextNode.call.isDrawingCall)
break;
} else {
nextNode = nextNode.parent;
if (!forward)
break;
}
}
if (!nextNode && forward)
this._onReplayLastStepClick();
else
(nextNode || selectedNode).revealAndSelect();
},
_onReplayFirstStepClick: function()
{
var firstNode = this._logGrid.rootNode().children[0];
if (firstNode)
firstNode.revealAndSelect();
},
_onReplayLastStepClick: function()
{
var lastNode = this._logGrid.rootNode().children.peekLast();
if (!lastNode)
return;
while (lastNode.expanded) {
var lastChild = lastNode.children.peekLast();
if (!lastChild)
break;
lastNode = lastChild;
}
lastNode.revealAndSelect();
},
/**
* @param {boolean} enable
*/
_enableWaitIcon: function(enable)
{
this._spinnerIcon.classList.toggle("hidden", !enable);
this._debugInfoElement.classList.toggle("hidden", enable);
},
_replayTraceLog: function()
{
if (this._pendingReplayTraceLogEvent)
return;
var index = this._selectedCallIndex();
if (index === -1 || index === this._lastReplayCallIndex)
return;
this._lastReplayCallIndex = index;
this._pendingReplayTraceLogEvent = true;
/**
* @param {?CanvasAgent.ResourceState} resourceState
* @param {number} replayTime
* @this {WebInspector.CanvasProfileView}
*/
function didReplayTraceLog(resourceState, replayTime)
{
delete this._pendingReplayTraceLogEvent;
this._enableWaitIcon(false);
this._debugInfoElement.textContent = WebInspector.UIString("Replay time: %s", Number.secondsToString(replayTime / 1000, true));
this._onReplayContextChanged();
if (index !== this._selectedCallIndex())
this._replayTraceLog();
}
this._enableWaitIcon(true);
this._traceLogPlayer.replayTraceLog(index, didReplayTraceLog.bind(this));
},
/**
* @param {number} offset
*/
_requestTraceLog: function(offset)
{
/**
* @param {?CanvasAgent.TraceLog} traceLog
* @this {WebInspector.CanvasProfileView}
*/
function didReceiveTraceLog(traceLog)
{
this._enableWaitIcon(false);
if (!traceLog)
return;
var callNodes = [];
var calls = traceLog.calls;
var index = traceLog.startOffset;
for (var i = 0, n = calls.length; i < n; ++i)
callNodes.push(this._createCallNode(index++, calls[i]));
var contexts = traceLog.contexts;
for (var i = 0, n = contexts.length; i < n; ++i) {
var contextId = contexts[i].resourceId || "";
var description = contexts[i].description || "";
if (this._replayContexts[contextId])
continue;
this._replayContexts[contextId] = true;
this._replayContextSelector.createOption(description, WebInspector.UIString("Show screenshot of this context's canvas."), contextId);
}
this._appendCallNodes(callNodes);
if (traceLog.alive)
setTimeout(this._requestTraceLog.bind(this, index), WebInspector.CanvasProfileView.TraceLogPollingInterval);
else
this._flattenSingleFrameNode();
this._profile._updateCapturingStatus(traceLog);
this._onReplayLastStepClick(); // Automatically replay the last step.
}
this._enableWaitIcon(true);
this._traceLogPlayer.getTraceLog(offset, undefined, didReceiveTraceLog.bind(this));
},
/**
* @return {number}
*/
_selectedCallIndex: function()
{
var node = this._logGrid.selectedNode;
return node ? this._peekLastRecursively(node).index : -1;
},
/**
* @param {!WebInspector.DataGridNode} node
* @return {!WebInspector.DataGridNode}
*/
_peekLastRecursively: function(node)
{
var lastChild;
while ((lastChild = node.children.peekLast()))
node = lastChild;
return node;
},
/**
* @param {!Array.<!WebInspector.DataGridNode>} callNodes
*/
_appendCallNodes: function(callNodes)
{
var rootNode = this._logGrid.rootNode();
var frameNode = rootNode.children.peekLast();
if (frameNode && this._peekLastRecursively(frameNode).call.isFrameEndCall)
frameNode = null;
for (var i = 0, n = callNodes.length; i < n; ++i) {
if (!frameNode) {
var index = rootNode.children.length;
var data = {};
data[0] = "";
data[1] = WebInspector.UIString("Frame #%d", index + 1);
data[2] = "";
frameNode = new WebInspector.DataGridNode(data);
frameNode.selectable = true;
rootNode.appendChild(frameNode);
}
var nextFrameCallIndex = i + 1;
while (nextFrameCallIndex < n && !callNodes[nextFrameCallIndex - 1].call.isFrameEndCall)
++nextFrameCallIndex;
this._appendCallNodesToFrameNode(frameNode, callNodes, i, nextFrameCallIndex);
i = nextFrameCallIndex - 1;
frameNode = null;
}
},
/**
* @param {!WebInspector.DataGridNode} frameNode
* @param {!Array.<!WebInspector.DataGridNode>} callNodes
* @param {number} fromIndex
* @param {number} toIndex not inclusive
*/
_appendCallNodesToFrameNode: function(frameNode, callNodes, fromIndex, toIndex)
{
var self = this;
function appendDrawCallGroup()
{
var index = self._drawCallGroupsCount || 0;
var data = {};
data[0] = "";
data[1] = WebInspector.UIString("Draw call group #%d", index + 1);
data[2] = "";
var node = new WebInspector.DataGridNode(data);
node.selectable = true;
self._drawCallGroupsCount = index + 1;
frameNode.appendChild(node);
return node;
}
function splitDrawCallGroup(drawCallGroup)
{
var splitIndex = 0;
var splitNode;
while ((splitNode = drawCallGroup.children[splitIndex])) {
if (splitNode.call.isDrawingCall)
break;
++splitIndex;
}
var newDrawCallGroup = appendDrawCallGroup();
var lastNode;
while ((lastNode = drawCallGroup.children[splitIndex + 1]))
newDrawCallGroup.appendChild(lastNode);
return newDrawCallGroup;
}
var drawCallGroup = frameNode.children.peekLast();
var groupHasDrawCall = false;
if (drawCallGroup) {
for (var i = 0, n = drawCallGroup.children.length; i < n; ++i) {
if (drawCallGroup.children[i].call.isDrawingCall) {
groupHasDrawCall = true;
break;
}
}
} else
drawCallGroup = appendDrawCallGroup();
for (var i = fromIndex; i < toIndex; ++i) {
var node = callNodes[i];
drawCallGroup.appendChild(node);
if (node.call.isDrawingCall) {
if (groupHasDrawCall)
drawCallGroup = splitDrawCallGroup(drawCallGroup);
else
groupHasDrawCall = true;
}
}
},
/**
* @param {number} index
* @param {!CanvasAgent.Call} call
* @return {!WebInspector.DataGridNode}
*/
_createCallNode: function(index, call)
{
var callViewElement = document.createElement("div");
var data = {};
data[0] = index + 1;
data[1] = callViewElement;
data[2] = "";
if (call.sourceURL) {
// FIXME(62725): stack trace line/column numbers are one-based.
var lineNumber = Math.max(0, call.lineNumber - 1) || 0;
var columnNumber = Math.max(0, call.columnNumber - 1) || 0;
data[2] = this._linkifier.linkifyLocation(this.profile.target(), call.sourceURL, lineNumber, columnNumber);
}
callViewElement.createChild("span", "canvas-function-name").textContent = call.functionName || "context." + call.property;
if (call.arguments) {
callViewElement.createTextChild("(");
for (var i = 0, n = call.arguments.length; i < n; ++i) {
var argument = /** @type {!CanvasAgent.CallArgument} */ (call.arguments[i]);
if (i)
callViewElement.createTextChild(", ");
var element = WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(argument);
element.__argumentIndex = i;
callViewElement.appendChild(element);
}
callViewElement.createTextChild(")");
} else if (call.value) {
callViewElement.createTextChild(" = ");
callViewElement.appendChild(WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(call.value));
}
if (call.result) {
callViewElement.createTextChild(" => ");
callViewElement.appendChild(WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(call.result));
}
var node = new WebInspector.DataGridNode(data);
node.index = index;
node.selectable = true;
node.call = call;
return node;
},
_popoverAnchor: function(element, event)
{
var argumentElement = element.enclosingNodeOrSelfWithClass("canvas-call-argument");
if (!argumentElement || argumentElement.__suppressPopover)
return null;
return argumentElement;
},
_resolveObjectForPopover: function(argumentElement, showCallback, objectGroupName)
{
/**
* @param {?Protocol.Error} error
* @param {!RuntimeAgent.RemoteObject=} result
* @param {!CanvasAgent.ResourceState=} resourceState
* @this {WebInspector.CanvasProfileView}
*/
function showObjectPopover(error, result, resourceState)
{
if (error)
return;
// FIXME: handle resourceState also
if (!result)
return;
this._popoverAnchorElement = argumentElement.cloneNode(true);
this._popoverAnchorElement.classList.add("canvas-popover-anchor");
this._popoverAnchorElement.classList.add("source-frame-eval-expression");
argumentElement.parentElement.appendChild(this._popoverAnchorElement);
var diffLeft = this._popoverAnchorElement.boxInWindow().x - argumentElement.boxInWindow().x;
this._popoverAnchorElement.style.left = this._popoverAnchorElement.offsetLeft - diffLeft + "px";
showCallback(WebInspector.runtimeModel.createRemoteObject(result), false, this._popoverAnchorElement);
}
var evalResult = argumentElement.__evalResult;
if (evalResult)
showObjectPopover.call(this, null, evalResult);
else {
var dataGridNode = this._logGrid.dataGridNodeFromNode(argumentElement);
if (!dataGridNode || typeof dataGridNode.index !== "number") {
this._popoverHelper.hidePopover();
return;
}
var callIndex = dataGridNode.index;
var argumentIndex = argumentElement.__argumentIndex;
if (typeof argumentIndex !== "number")
argumentIndex = -1;
CanvasAgent.evaluateTraceLogCallArgument(this._traceLogId, callIndex, argumentIndex, objectGroupName, showObjectPopover.bind(this));
}
},
/**
* @param {!WebInspector.RemoteObject} object
* @return {string}
*/
_hexNumbersFormatter: function(object)
{
if (object.type === "number") {
// Show enum values in hex with min length of 4 (e.g. 0x0012).
var str = "0000" + Number(object.description).toString(16).toUpperCase();
str = str.replace(/^0+(.{4,})$/, "$1");
return "0x" + str;
}
return object.description || "";
},
_onHidePopover: function()
{
if (this._popoverAnchorElement) {
this._popoverAnchorElement.remove()
delete this._popoverAnchorElement;
}
},
_flattenSingleFrameNode: function()
{
var rootNode = this._logGrid.rootNode();
if (rootNode.children.length !== 1)
return;
var frameNode = rootNode.children[0];
while (frameNode.children[0])
rootNode.appendChild(frameNode.children[0]);
rootNode.removeChild(frameNode);
},
__proto__: WebInspector.VBox.prototype
}
/**
* @constructor
* @extends {WebInspector.ProfileType}
*/
WebInspector.CanvasProfileType = function()
{
WebInspector.ProfileType.call(this, WebInspector.CanvasProfileType.TypeId, WebInspector.UIString("Capture Canvas Frame"));
this._recording = false;
this._lastProfileHeader = null;
this._capturingModeSelector = new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));
this._capturingModeSelector.element.title = WebInspector.UIString("Canvas capture mode.");
this._capturingModeSelector.createOption(WebInspector.UIString("Single Frame"), WebInspector.UIString("Capture a single canvas frame."), "");
this._capturingModeSelector.createOption(WebInspector.UIString("Consecutive Frames"), WebInspector.UIString("Capture consecutive canvas frames."), "1");
/** @type {!Object.<string, !Element>} */
this._frameOptions = {};
/** @type {!Object.<string, boolean>} */
this._framesWithCanvases = {};
this._frameSelector = new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));
this._frameSelector.element.title = WebInspector.UIString("Frame containing the canvases to capture.");
this._frameSelector.element.classList.add("hidden");
this._target = /** @type {!WebInspector.Target} */ (WebInspector.targetManager.activeTarget());
this._target.resourceTreeModel.frames().forEach(this._addFrame, this);
this._target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this);
this._target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameRemoved, this);
this._dispatcher = new WebInspector.CanvasDispatcher(this);
this._canvasAgentEnabled = false;
this._decorationElement = document.createElement("div");
this._decorationElement.className = "profile-canvas-decoration";
this._updateDecorationElement();
}
WebInspector.CanvasProfileType.TypeId = "CANVAS_PROFILE";
WebInspector.CanvasProfileType.prototype = {
get statusBarItems()
{
return [this._capturingModeSelector.element, this._frameSelector.element];
},
get buttonTooltip()
{
if (this._isSingleFrameMode())
return WebInspector.UIString("Capture next canvas frame.");
else
return this._recording ? WebInspector.UIString("Stop capturing canvas frames.") : WebInspector.UIString("Start capturing canvas frames.");
},
/**
* @override
* @return {boolean}
*/
buttonClicked: function()
{
if (!this._canvasAgentEnabled)
return false;
if (this._recording) {
this._recording = false;
this._stopFrameCapturing();
} else if (this._isSingleFrameMode()) {
this._recording = false;
this._runSingleFrameCapturing();
} else {
this._recording = true;
this._startFrameCapturing();
}
return this._recording;
},
_runSingleFrameCapturing: function()
{
var frameId = this._selectedFrameId();
CanvasAgent.captureFrame(frameId, this._didStartCapturingFrame.bind(this, frameId));
},
_startFrameCapturing: function()
{
var frameId = this._selectedFrameId();
CanvasAgent.startCapturing(frameId, this._didStartCapturingFrame.bind(this, frameId));
},
_stopFrameCapturing: function()
{
if (!this._lastProfileHeader)
return;
var profileHeader = this._lastProfileHeader;
var traceLogId = profileHeader.traceLogId();
this._lastProfileHeader = null;
function didStopCapturing()
{
profileHeader._updateCapturingStatus();
}
CanvasAgent.stopCapturing(traceLogId, didStopCapturing);
},
/**
* @param {string|undefined} frameId
* @param {?Protocol.Error} error
* @param {!CanvasAgent.TraceLogId} traceLogId
*/
_didStartCapturingFrame: function(frameId, error, traceLogId)
{
if (error || this._lastProfileHeader && this._lastProfileHeader.traceLogId() === traceLogId)
return;
var profileHeader = new WebInspector.CanvasProfileHeader(this._target, this, traceLogId, frameId);
this._lastProfileHeader = profileHeader;
this.addProfile(profileHeader);
profileHeader._updateCapturingStatus();
},
get treeItemTitle()
{
return WebInspector.UIString("CANVAS PROFILE");
},
get description()
{
return WebInspector.UIString("Canvas calls instrumentation");
},
/**
* @override
* @return {!Element}
*/
decorationElement: function()
{
return this._decorationElement;
},
/**
* @override
* @param {!WebInspector.ProfileHeader} profile
*/
removeProfile: function(profile)
{
WebInspector.ProfileType.prototype.removeProfile.call(this, profile);
if (this._recording && profile === this._lastProfileHeader)
this._recording = false;
},
/**
* @param {boolean=} forcePageReload
*/
_updateDecorationElement: function(forcePageReload)
{
this._decorationElement.removeChildren();
this._decorationElement.createChild("div", "warning-icon-small");
this._decorationElement.appendChild(document.createTextNode(this._canvasAgentEnabled ? WebInspector.UIString("Canvas Profiler is enabled.") : WebInspector.UIString("Canvas Profiler is disabled.")));
var button = this._decorationElement.createChild("button");
button.type = "button";
button.textContent = this._canvasAgentEnabled ? WebInspector.UIString("Disable") : WebInspector.UIString("Enable");
button.addEventListener("click", this._onProfilerEnableButtonClick.bind(this, !this._canvasAgentEnabled), false);
var target = this._target;
/**
* @param {?Protocol.Error} error
* @param {boolean} result
*/
function hasUninstrumentedCanvasesCallback(error, result)
{
if (error || result)
target.resourceTreeModel.reloadPage();
}
if (forcePageReload) {
if (this._canvasAgentEnabled) {
CanvasAgent.hasUninstrumentedCanvases(hasUninstrumentedCanvasesCallback);
} else {
for (var frameId in this._framesWithCanvases) {
if (this._framesWithCanvases.hasOwnProperty(frameId)) {
target.resourceTreeModel.reloadPage();
break;
}
}
}
}
},
/**
* @param {boolean} enable
*/
_onProfilerEnableButtonClick: function(enable)
{
if (this._canvasAgentEnabled === enable)
return;
/**
* @param {?Protocol.Error} error
* @this {WebInspector.CanvasProfileType}
*/
function callback(error)
{
if (error)
return;
this._canvasAgentEnabled = enable;
this._updateDecorationElement(true);
this._dispatchViewUpdatedEvent();
}
if (enable)
CanvasAgent.enable(callback.bind(this));
else
CanvasAgent.disable(callback.bind(this));
},
/**
* @return {boolean}
*/
_isSingleFrameMode: function()
{
return !this._capturingModeSelector.selectedOption().value;
},
/**
* @param {!WebInspector.Event} event
*/
_frameAdded: function(event)
{
var frame = /** @type {!WebInspector.ResourceTreeFrame} */ (event.data);
this._addFrame(frame);
},
/**
* @param {!WebInspector.ResourceTreeFrame} frame
*/
_addFrame: function(frame)
{
var frameId = frame.id;
var option = document.createElement("option");
option.text = frame.displayName();
option.title = frame.url;
option.value = frameId;
this._frameOptions[frameId] = option;
if (this._framesWithCanvases[frameId]) {
this._frameSelector.addOption(option);
this._dispatchViewUpdatedEvent();
}
},
/**
* @param {!WebInspector.Event} event
*/
_frameRemoved: function(event)
{
var frame = /** @type {!WebInspector.ResourceTreeFrame} */ (event.data);
var frameId = frame.id;
var option = this._frameOptions[frameId];
if (option && this._framesWithCanvases[frameId]) {
this._frameSelector.removeOption(option);
this._dispatchViewUpdatedEvent();
}
delete this._frameOptions[frameId];
delete this._framesWithCanvases[frameId];
},
/**
* @param {string} frameId
*/
_contextCreated: function(frameId)
{
if (this._framesWithCanvases[frameId])
return;
this._framesWithCanvases[frameId] = true;
var option = this._frameOptions[frameId];
if (option) {
this._frameSelector.addOption(option);
this._dispatchViewUpdatedEvent();
}
},
/**
* @param {!PageAgent.FrameId=} frameId
* @param {!CanvasAgent.TraceLogId=} traceLogId
*/
_traceLogsRemoved: function(frameId, traceLogId)
{
var sidebarElementsToDelete = [];
var sidebarElements = /** @type {!Array.<!WebInspector.ProfileSidebarTreeElement>} */ ((this.treeElement && this.treeElement.children) || []);
for (var i = 0, n = sidebarElements.length; i < n; ++i) {
var header = /** @type {!WebInspector.CanvasProfileHeader} */ (sidebarElements[i].profile);
if (!header)
continue;
if (frameId && frameId !== header.frameId())
continue;
if (traceLogId && traceLogId !== header.traceLogId())
continue;
sidebarElementsToDelete.push(sidebarElements[i]);
}
for (var i = 0, n = sidebarElementsToDelete.length; i < n; ++i)
sidebarElementsToDelete[i].ondelete();
},
/**
* @return {string|undefined}
*/
_selectedFrameId: function()
{
var option = this._frameSelector.selectedOption();
return option ? option.value : undefined;
},
_dispatchViewUpdatedEvent: function()
{
this._frameSelector.element.classList.toggle("hidden", this._frameSelector.size() <= 1);
this.dispatchEventToListeners(WebInspector.ProfileType.Events.ViewUpdated);
},
/**
* @override
* @return {boolean}
*/
isInstantProfile: function()
{
return this._isSingleFrameMode();
},
/**
* @override
* @return {boolean}
*/
isEnabled: function()
{
return this._canvasAgentEnabled;
},
__proto__: WebInspector.ProfileType.prototype
}
/**
* @constructor
* @implements {CanvasAgent.Dispatcher}
* @param {!WebInspector.CanvasProfileType} profileType
*/
WebInspector.CanvasDispatcher = function(profileType)
{
this._profileType = profileType;
InspectorBackend.registerCanvasDispatcher(this);
}
WebInspector.CanvasDispatcher.prototype = {
/**
* @param {string} frameId
*/
contextCreated: function(frameId)
{
this._profileType._contextCreated(frameId);
},
/**
* @param {!PageAgent.FrameId=} frameId
* @param {!CanvasAgent.TraceLogId=} traceLogId
*/
traceLogsRemoved: function(frameId, traceLogId)
{
this._profileType._traceLogsRemoved(frameId, traceLogId);
}
}
/**
* @constructor
* @extends {WebInspector.ProfileHeader}
* @param {!WebInspector.Target} target
* @param {!WebInspector.CanvasProfileType} type
* @param {!CanvasAgent.TraceLogId=} traceLogId
* @param {!PageAgent.FrameId=} frameId
*/
WebInspector.CanvasProfileHeader = function(target, type, traceLogId, frameId)
{
WebInspector.ProfileHeader.call(this, target, type, WebInspector.UIString("Trace Log %d", type._nextProfileUid));
/** @type {!CanvasAgent.TraceLogId} */
this._traceLogId = traceLogId || "";
this._frameId = frameId;
this._alive = true;
this._traceLogSize = 0;
this._traceLogPlayer = traceLogId ? new WebInspector.CanvasTraceLogPlayerProxy(traceLogId) : null;
}
WebInspector.CanvasProfileHeader.prototype = {
/**
* @return {!CanvasAgent.TraceLogId}
*/
traceLogId: function()
{
return this._traceLogId;
},
/**
* @return {?WebInspector.CanvasTraceLogPlayerProxy}
*/
traceLogPlayer: function()
{
return this._traceLogPlayer;
},
/**
* @return {!PageAgent.FrameId|undefined}
*/
frameId: function()
{
return this._frameId;
},
/**
* @override
* @return {!WebInspector.ProfileSidebarTreeElement}
*/
createSidebarTreeElement: function()
{
return new WebInspector.ProfileSidebarTreeElement(this, "profile-sidebar-tree-item");
},
/**
* @override
* @return {!WebInspector.CanvasProfileView}
*/
createView: function()
{
return new WebInspector.CanvasProfileView(this);
},
/**
* @override
*/
dispose: function()
{
if (this._traceLogPlayer)
this._traceLogPlayer.dispose();
clearTimeout(this._requestStatusTimer);
this._alive = false;
},
/**
* @param {!CanvasAgent.TraceLog=} traceLog
*/
_updateCapturingStatus: function(traceLog)
{
if (!this._traceLogId)
return;
if (traceLog) {
this._alive = traceLog.alive;
this._traceLogSize = traceLog.totalAvailableCalls;
}
var subtitle = this._alive ? WebInspector.UIString("Capturing\u2026 %d calls", this._traceLogSize) : WebInspector.UIString("Captured %d calls", this._traceLogSize);
this.updateStatus(subtitle, this._alive);
if (this._alive) {
clearTimeout(this._requestStatusTimer);
this._requestStatusTimer = setTimeout(this._requestCapturingStatus.bind(this), WebInspector.CanvasProfileView.TraceLogPollingInterval);
}
},
_requestCapturingStatus: function()
{
/**
* @param {?CanvasAgent.TraceLog} traceLog
* @this {WebInspector.CanvasProfileHeader}
*/
function didReceiveTraceLog(traceLog)
{
if (!traceLog)
return;
this._alive = traceLog.alive;
this._traceLogSize = traceLog.totalAvailableCalls;
this._updateCapturingStatus();
}
this._traceLogPlayer.getTraceLog(0, 0, didReceiveTraceLog.bind(this));
},
__proto__: WebInspector.ProfileHeader.prototype
}
WebInspector.CanvasProfileDataGridHelper = {
/**
* @param {!CanvasAgent.CallArgument} callArgument
* @return {!Element}
*/
createCallArgumentElement: function(callArgument)
{
if (callArgument.enumName)
return WebInspector.CanvasProfileDataGridHelper.createEnumValueElement(callArgument.enumName, +callArgument.description);
var element = document.createElement("span");
element.className = "canvas-call-argument";
var description = callArgument.description;
if (callArgument.type === "string") {
const maxStringLength = 150;
element.createTextChild("\"");
element.createChild("span", "canvas-formatted-string").textContent = description.trimMiddle(maxStringLength);
element.createTextChild("\"");
element.__suppressPopover = (description.length <= maxStringLength && !/[\r\n]/.test(description));
if (!element.__suppressPopover)
element.__evalResult = WebInspector.runtimeModel.createRemoteObjectFromPrimitiveValue(description);
} else {
var type = callArgument.subtype || callArgument.type;
if (type) {
element.classList.add("canvas-formatted-" + type);
if (["null", "undefined", "boolean", "number"].indexOf(type) >= 0)
element.__suppressPopover = true;
}
element.textContent = description;
if (callArgument.remoteObject)
element.__evalResult = WebInspector.runtimeModel.createRemoteObject(callArgument.remoteObject);
}
if (callArgument.resourceId) {
element.classList.add("canvas-formatted-resource");
element.__resourceId = callArgument.resourceId;
}
return element;
},
/**
* @param {string} enumName
* @param {number} enumValue
* @return {!Element}
*/
createEnumValueElement: function(enumName, enumValue)
{
var element = document.createElement("span");
element.className = "canvas-call-argument canvas-formatted-number";
element.textContent = enumName;
element.__evalResult = WebInspector.runtimeModel.createRemoteObjectFromPrimitiveValue(enumValue);
return element;
}
}
/**
* @extends {WebInspector.Object}
* @constructor
* @param {!CanvasAgent.TraceLogId} traceLogId
*/
WebInspector.CanvasTraceLogPlayerProxy = function(traceLogId)
{
this._traceLogId = traceLogId;
/** @type {!Object.<string, !CanvasAgent.ResourceState>} */
this._currentResourceStates = {};
/** @type {?CanvasAgent.ResourceId} */
this._defaultResourceId = null;
}
/** @enum {string} */
WebInspector.CanvasTraceLogPlayerProxy.Events = {
CanvasTraceLogReceived: "CanvasTraceLogReceived",
CanvasReplayStateChanged: "CanvasReplayStateChanged",
CanvasResourceStateReceived: "CanvasResourceStateReceived",
}
WebInspector.CanvasTraceLogPlayerProxy.prototype = {
/**
* @param {number|undefined} startOffset
* @param {number|undefined} maxLength
* @param {function(?CanvasAgent.TraceLog):void} userCallback
*/
getTraceLog: function(startOffset, maxLength, userCallback)
{
/**
* @param {?Protocol.Error} error
* @param {!CanvasAgent.TraceLog} traceLog
* @this {WebInspector.CanvasTraceLogPlayerProxy}
*/
function callback(error, traceLog)
{
if (error || !traceLog) {
userCallback(null);
return;
}
userCallback(traceLog);
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasTraceLogReceived, traceLog);
}
CanvasAgent.getTraceLog(this._traceLogId, startOffset, maxLength, callback.bind(this));
},
dispose: function()
{
this._currentResourceStates = {};
CanvasAgent.dropTraceLog(this._traceLogId);
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);
},
/**
* @param {?CanvasAgent.ResourceId} resourceId
* @param {function(?CanvasAgent.ResourceState):void} userCallback
*/
getResourceState: function(resourceId, userCallback)
{
resourceId = resourceId || this._defaultResourceId;
if (!resourceId) {
userCallback(null); // Has not been replayed yet.
return;
}
var effectiveResourceId = /** @type {!CanvasAgent.ResourceId} */ (resourceId);
if (this._currentResourceStates[effectiveResourceId]) {
userCallback(this._currentResourceStates[effectiveResourceId]);
return;
}
/**
* @param {?Protocol.Error} error
* @param {!CanvasAgent.ResourceState} resourceState
* @this {WebInspector.CanvasTraceLogPlayerProxy}
*/
function callback(error, resourceState)
{
if (error || !resourceState) {
userCallback(null);
return;
}
this._currentResourceStates[effectiveResourceId] = resourceState;
userCallback(resourceState);
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived, resourceState);
}
CanvasAgent.getResourceState(this._traceLogId, effectiveResourceId, callback.bind(this));
},
/**
* @param {number} index
* @param {function(?CanvasAgent.ResourceState, number):void} userCallback
*/
replayTraceLog: function(index, userCallback)
{
/**
* @param {?Protocol.Error} error
* @param {!CanvasAgent.ResourceState} resourceState
* @param {number} replayTime
* @this {WebInspector.CanvasTraceLogPlayerProxy}
*/
function callback(error, resourceState, replayTime)
{
this._currentResourceStates = {};
if (error) {
userCallback(null, replayTime);
} else {
this._defaultResourceId = resourceState.id;
this._currentResourceStates[resourceState.id] = resourceState;
userCallback(resourceState, replayTime);
}
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);
if (!error)
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived, resourceState);
}
CanvasAgent.replayTraceLog(this._traceLogId, index, callback.bind(this));
},
clearResourceStates: function()
{
this._currentResourceStates = {};
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);
},
__proto__: WebInspector.Object.prototype
}
| Source/devtools/front_end/profiler/CanvasProfileView.js | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.VBox}
* @param {!WebInspector.CanvasProfileHeader} profile
*/
WebInspector.CanvasProfileView = function(profile)
{
WebInspector.VBox.call(this);
this.registerRequiredCSS("canvasProfiler.css");
this.element.classList.add("canvas-profile-view");
this._profile = profile;
this._traceLogId = profile.traceLogId();
this._traceLogPlayer = /** @type {!WebInspector.CanvasTraceLogPlayerProxy} */ (profile.traceLogPlayer());
this._linkifier = new WebInspector.Linkifier();
this._replayInfoSplitView = new WebInspector.SplitView(true, true, "canvasProfileViewReplaySplitViewState", 0.34);
this._replayInfoSplitView.show(this.element);
this._imageSplitView = new WebInspector.SplitView(false, true, "canvasProfileViewSplitViewState", 300);
this._imageSplitView.show(this._replayInfoSplitView.mainElement());
var replayImageContainerView = new WebInspector.VBox();
replayImageContainerView.setMinimumSize(50, 28);
replayImageContainerView.show(this._imageSplitView.mainElement());
var replayImageContainer = replayImageContainerView.element;
replayImageContainer.id = "canvas-replay-image-container";
this._replayImageElement = replayImageContainer.createChild("img", "canvas-replay-image");
this._debugInfoElement = replayImageContainer.createChild("div", "canvas-debug-info hidden");
this._spinnerIcon = replayImageContainer.createChild("div", "spinner-icon small hidden");
var replayLogContainerView = new WebInspector.VBox();
replayLogContainerView.setMinimumSize(22, 22);
replayLogContainerView.show(this._imageSplitView.sidebarElement());
var replayLogContainer = replayLogContainerView.element;
var controlsContainer = replayLogContainer.createChild("div", "status-bar");
var logGridContainer = replayLogContainer.createChild("div", "canvas-replay-log");
this._createControlButton(controlsContainer, "canvas-replay-first-step", WebInspector.UIString("First call."), this._onReplayFirstStepClick.bind(this));
this._createControlButton(controlsContainer, "canvas-replay-prev-step", WebInspector.UIString("Previous call."), this._onReplayStepClick.bind(this, false));
this._createControlButton(controlsContainer, "canvas-replay-next-step", WebInspector.UIString("Next call."), this._onReplayStepClick.bind(this, true));
this._createControlButton(controlsContainer, "canvas-replay-prev-draw", WebInspector.UIString("Previous drawing call."), this._onReplayDrawingCallClick.bind(this, false));
this._createControlButton(controlsContainer, "canvas-replay-next-draw", WebInspector.UIString("Next drawing call."), this._onReplayDrawingCallClick.bind(this, true));
this._createControlButton(controlsContainer, "canvas-replay-last-step", WebInspector.UIString("Last call."), this._onReplayLastStepClick.bind(this));
this._replayContextSelector = new WebInspector.StatusBarComboBox(this._onReplayContextChanged.bind(this));
this._replayContextSelector.createOption(WebInspector.UIString("<screenshot auto>"), WebInspector.UIString("Show screenshot of the last replayed resource."), "");
controlsContainer.appendChild(this._replayContextSelector.element);
this._installReplayInfoSidebarWidgets(controlsContainer);
this._replayStateView = new WebInspector.CanvasReplayStateView(this._traceLogPlayer);
this._replayStateView.show(this._replayInfoSplitView.sidebarElement());
/** @type {!Object.<string, boolean>} */
this._replayContexts = {};
var columns = [
{title: "#", sortable: false, width: "5%"},
{title: WebInspector.UIString("Call"), sortable: false, width: "75%", disclosure: true},
{title: WebInspector.UIString("Location"), sortable: false, width: "20%"}
];
this._logGrid = new WebInspector.DataGrid(columns);
this._logGrid.element.classList.add("fill");
this._logGrid.show(logGridContainer);
this._logGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._replayTraceLog, this);
this.element.addEventListener("mousedown", this._onMouseClick.bind(this), true);
this._popoverHelper = new WebInspector.ObjectPopoverHelper(this.element, this._popoverAnchor.bind(this), this._resolveObjectForPopover.bind(this), this._onHidePopover.bind(this), true);
this._popoverHelper.setRemoteObjectFormatter(this._hexNumbersFormatter.bind(this));
this._requestTraceLog(0);
}
/**
* @const
* @type {number}
*/
WebInspector.CanvasProfileView.TraceLogPollingInterval = 500;
WebInspector.CanvasProfileView.prototype = {
dispose: function()
{
this._linkifier.reset();
},
get statusBarItems()
{
return [];
},
get profile()
{
return this._profile;
},
/**
* @override
* @return {!Array.<!Element>}
*/
elementsToRestoreScrollPositionsFor: function()
{
return [this._logGrid.scrollContainer];
},
/**
* @param {!Element} controlsContainer
*/
_installReplayInfoSidebarWidgets: function(controlsContainer)
{
this._replayInfoResizeWidgetElement = controlsContainer.createChild("div", "resizer-widget");
this._replayInfoSplitView.addEventListener(WebInspector.SplitView.Events.ShowModeChanged, this._updateReplayInfoResizeWidget, this);
this._updateReplayInfoResizeWidget();
this._replayInfoSplitView.installResizer(this._replayInfoResizeWidgetElement);
this._toggleReplayStateSidebarButton = this._replayInfoSplitView.createShowHideSidebarButton("sidebar", "canvas-sidebar-show-hide-button");
controlsContainer.appendChild(this._toggleReplayStateSidebarButton.element);
this._replayInfoSplitView.hideSidebar();
},
_updateReplayInfoResizeWidget: function()
{
this._replayInfoResizeWidgetElement.classList.toggle("hidden", this._replayInfoSplitView.showMode() !== WebInspector.SplitView.ShowMode.Both);
},
/**
* @param {?Event} event
*/
_onMouseClick: function(event)
{
var resourceLinkElement = event.target.enclosingNodeOrSelfWithClass("canvas-formatted-resource");
if (resourceLinkElement) {
this._replayInfoSplitView.showBoth();
this._replayStateView.selectResource(resourceLinkElement.__resourceId);
event.consume(true);
return;
}
if (event.target.enclosingNodeOrSelfWithClass("webkit-html-resource-link"))
event.consume(false);
},
/**
* @param {!Element} parent
* @param {string} className
* @param {string} title
* @param {function(this:WebInspector.CanvasProfileView)} clickCallback
*/
_createControlButton: function(parent, className, title, clickCallback)
{
var button = new WebInspector.StatusBarButton(title, className + " canvas-replay-button");
parent.appendChild(button.element);
button.makeLongClickEnabled();
button.addEventListener("click", clickCallback, this);
button.addEventListener("longClickDown", clickCallback, this);
button.addEventListener("longClickPress", clickCallback, this);
},
_onReplayContextChanged: function()
{
var selectedContextId = this._replayContextSelector.selectedOption().value;
/**
* @param {?CanvasAgent.ResourceState} resourceState
* @this {WebInspector.CanvasProfileView}
*/
function didReceiveResourceState(resourceState)
{
this._enableWaitIcon(false);
if (selectedContextId !== this._replayContextSelector.selectedOption().value)
return;
var imageURL = (resourceState && resourceState.imageURL) || "";
this._replayImageElement.src = imageURL;
this._replayImageElement.style.visibility = imageURL ? "" : "hidden";
}
this._enableWaitIcon(true);
this._traceLogPlayer.getResourceState(selectedContextId, didReceiveResourceState.bind(this));
},
/**
* @param {boolean} forward
*/
_onReplayStepClick: function(forward)
{
var selectedNode = this._logGrid.selectedNode;
if (!selectedNode)
return;
var nextNode = selectedNode;
do {
nextNode = forward ? nextNode.traverseNextNode(false) : nextNode.traversePreviousNode(false);
} while (nextNode && typeof nextNode.index !== "number");
(nextNode || selectedNode).revealAndSelect();
},
/**
* @param {boolean} forward
*/
_onReplayDrawingCallClick: function(forward)
{
var selectedNode = this._logGrid.selectedNode;
if (!selectedNode)
return;
var nextNode = selectedNode;
while (nextNode) {
var sibling = forward ? nextNode.nextSibling : nextNode.previousSibling;
if (sibling) {
nextNode = sibling;
if (nextNode.hasChildren || nextNode.call.isDrawingCall)
break;
} else {
nextNode = nextNode.parent;
if (!forward)
break;
}
}
if (!nextNode && forward)
this._onReplayLastStepClick();
else
(nextNode || selectedNode).revealAndSelect();
},
_onReplayFirstStepClick: function()
{
var firstNode = this._logGrid.rootNode().children[0];
if (firstNode)
firstNode.revealAndSelect();
},
_onReplayLastStepClick: function()
{
var lastNode = this._logGrid.rootNode().children.peekLast();
if (!lastNode)
return;
while (lastNode.expanded) {
var lastChild = lastNode.children.peekLast();
if (!lastChild)
break;
lastNode = lastChild;
}
lastNode.revealAndSelect();
},
/**
* @param {boolean} enable
*/
_enableWaitIcon: function(enable)
{
this._spinnerIcon.classList.toggle("hidden", !enable);
this._debugInfoElement.classList.toggle("hidden", enable);
},
_replayTraceLog: function()
{
if (this._pendingReplayTraceLogEvent)
return;
var index = this._selectedCallIndex();
if (index === -1 || index === this._lastReplayCallIndex)
return;
this._lastReplayCallIndex = index;
this._pendingReplayTraceLogEvent = true;
/**
* @param {?CanvasAgent.ResourceState} resourceState
* @param {number} replayTime
* @this {WebInspector.CanvasProfileView}
*/
function didReplayTraceLog(resourceState, replayTime)
{
delete this._pendingReplayTraceLogEvent;
this._enableWaitIcon(false);
this._debugInfoElement.textContent = WebInspector.UIString("Replay time: %s", Number.secondsToString(replayTime / 1000, true));
this._onReplayContextChanged();
if (index !== this._selectedCallIndex())
this._replayTraceLog();
}
this._enableWaitIcon(true);
this._traceLogPlayer.replayTraceLog(index, didReplayTraceLog.bind(this));
},
/**
* @param {number} offset
*/
_requestTraceLog: function(offset)
{
/**
* @param {?CanvasAgent.TraceLog} traceLog
* @this {WebInspector.CanvasProfileView}
*/
function didReceiveTraceLog(traceLog)
{
this._enableWaitIcon(false);
if (!traceLog)
return;
var callNodes = [];
var calls = traceLog.calls;
var index = traceLog.startOffset;
for (var i = 0, n = calls.length; i < n; ++i)
callNodes.push(this._createCallNode(index++, calls[i]));
var contexts = traceLog.contexts;
for (var i = 0, n = contexts.length; i < n; ++i) {
var contextId = contexts[i].resourceId || "";
var description = contexts[i].description || "";
if (this._replayContexts[contextId])
continue;
this._replayContexts[contextId] = true;
this._replayContextSelector.createOption(description, WebInspector.UIString("Show screenshot of this context's canvas."), contextId);
}
this._appendCallNodes(callNodes);
if (traceLog.alive)
setTimeout(this._requestTraceLog.bind(this, index), WebInspector.CanvasProfileView.TraceLogPollingInterval);
else
this._flattenSingleFrameNode();
this._profile._updateCapturingStatus(traceLog);
this._onReplayLastStepClick(); // Automatically replay the last step.
}
this._enableWaitIcon(true);
this._traceLogPlayer.getTraceLog(offset, undefined, didReceiveTraceLog.bind(this));
},
/**
* @return {number}
*/
_selectedCallIndex: function()
{
var node = this._logGrid.selectedNode;
return node ? this._peekLastRecursively(node).index : -1;
},
/**
* @param {!WebInspector.DataGridNode} node
* @return {!WebInspector.DataGridNode}
*/
_peekLastRecursively: function(node)
{
var lastChild;
while ((lastChild = node.children.peekLast()))
node = lastChild;
return node;
},
/**
* @param {!Array.<!WebInspector.DataGridNode>} callNodes
*/
_appendCallNodes: function(callNodes)
{
var rootNode = this._logGrid.rootNode();
var frameNode = rootNode.children.peekLast();
if (frameNode && this._peekLastRecursively(frameNode).call.isFrameEndCall)
frameNode = null;
for (var i = 0, n = callNodes.length; i < n; ++i) {
if (!frameNode) {
var index = rootNode.children.length;
var data = {};
data[0] = "";
data[1] = WebInspector.UIString("Frame #%d", index + 1);
data[2] = "";
frameNode = new WebInspector.DataGridNode(data);
frameNode.selectable = true;
rootNode.appendChild(frameNode);
}
var nextFrameCallIndex = i + 1;
while (nextFrameCallIndex < n && !callNodes[nextFrameCallIndex - 1].call.isFrameEndCall)
++nextFrameCallIndex;
this._appendCallNodesToFrameNode(frameNode, callNodes, i, nextFrameCallIndex);
i = nextFrameCallIndex - 1;
frameNode = null;
}
},
/**
* @param {!WebInspector.DataGridNode} frameNode
* @param {!Array.<!WebInspector.DataGridNode>} callNodes
* @param {number} fromIndex
* @param {number} toIndex not inclusive
*/
_appendCallNodesToFrameNode: function(frameNode, callNodes, fromIndex, toIndex)
{
var self = this;
function appendDrawCallGroup()
{
var index = self._drawCallGroupsCount || 0;
var data = {};
data[0] = "";
data[1] = WebInspector.UIString("Draw call group #%d", index + 1);
data[2] = "";
var node = new WebInspector.DataGridNode(data);
node.selectable = true;
self._drawCallGroupsCount = index + 1;
frameNode.appendChild(node);
return node;
}
function splitDrawCallGroup(drawCallGroup)
{
var splitIndex = 0;
var splitNode;
while ((splitNode = drawCallGroup.children[splitIndex])) {
if (splitNode.call.isDrawingCall)
break;
++splitIndex;
}
var newDrawCallGroup = appendDrawCallGroup();
var lastNode;
while ((lastNode = drawCallGroup.children[splitIndex + 1]))
newDrawCallGroup.appendChild(lastNode);
return newDrawCallGroup;
}
var drawCallGroup = frameNode.children.peekLast();
var groupHasDrawCall = false;
if (drawCallGroup) {
for (var i = 0, n = drawCallGroup.children.length; i < n; ++i) {
if (drawCallGroup.children[i].call.isDrawingCall) {
groupHasDrawCall = true;
break;
}
}
} else
drawCallGroup = appendDrawCallGroup();
for (var i = fromIndex; i < toIndex; ++i) {
var node = callNodes[i];
drawCallGroup.appendChild(node);
if (node.call.isDrawingCall) {
if (groupHasDrawCall)
drawCallGroup = splitDrawCallGroup(drawCallGroup);
else
groupHasDrawCall = true;
}
}
},
/**
* @param {number} index
* @param {!CanvasAgent.Call} call
* @return {!WebInspector.DataGridNode}
*/
_createCallNode: function(index, call)
{
var callViewElement = document.createElement("div");
var data = {};
data[0] = index + 1;
data[1] = callViewElement;
data[2] = "";
if (call.sourceURL) {
// FIXME(62725): stack trace line/column numbers are one-based.
var lineNumber = Math.max(0, call.lineNumber - 1) || 0;
var columnNumber = Math.max(0, call.columnNumber - 1) || 0;
data[2] = this._linkifier.linkifyLocation(this.profile.target(), call.sourceURL, lineNumber, columnNumber);
}
callViewElement.createChild("span", "canvas-function-name").textContent = call.functionName || "context." + call.property;
if (call.arguments) {
callViewElement.createTextChild("(");
for (var i = 0, n = call.arguments.length; i < n; ++i) {
var argument = /** @type {!CanvasAgent.CallArgument} */ (call.arguments[i]);
if (i)
callViewElement.createTextChild(", ");
var element = WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(argument);
element.__argumentIndex = i;
callViewElement.appendChild(element);
}
callViewElement.createTextChild(")");
} else if (call.value) {
callViewElement.createTextChild(" = ");
callViewElement.appendChild(WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(call.value));
}
if (call.result) {
callViewElement.createTextChild(" => ");
callViewElement.appendChild(WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(call.result));
}
var node = new WebInspector.DataGridNode(data);
node.index = index;
node.selectable = true;
node.call = call;
return node;
},
_popoverAnchor: function(element, event)
{
var argumentElement = element.enclosingNodeOrSelfWithClass("canvas-call-argument");
if (!argumentElement || argumentElement.__suppressPopover)
return null;
return argumentElement;
},
_resolveObjectForPopover: function(argumentElement, showCallback, objectGroupName)
{
/**
* @param {?Protocol.Error} error
* @param {!RuntimeAgent.RemoteObject=} result
* @param {!CanvasAgent.ResourceState=} resourceState
* @this {WebInspector.CanvasProfileView}
*/
function showObjectPopover(error, result, resourceState)
{
if (error)
return;
// FIXME: handle resourceState also
if (!result)
return;
this._popoverAnchorElement = argumentElement.cloneNode(true);
this._popoverAnchorElement.classList.add("canvas-popover-anchor");
this._popoverAnchorElement.classList.add("source-frame-eval-expression");
argumentElement.parentElement.appendChild(this._popoverAnchorElement);
var diffLeft = this._popoverAnchorElement.boxInWindow().x - argumentElement.boxInWindow().x;
this._popoverAnchorElement.style.left = this._popoverAnchorElement.offsetLeft - diffLeft + "px";
showCallback(WebInspector.runtimeModel.createRemoteObject(result), false, this._popoverAnchorElement);
}
var evalResult = argumentElement.__evalResult;
if (evalResult)
showObjectPopover.call(this, null, evalResult);
else {
var dataGridNode = this._logGrid.dataGridNodeFromNode(argumentElement);
if (!dataGridNode || typeof dataGridNode.index !== "number") {
this._popoverHelper.hidePopover();
return;
}
var callIndex = dataGridNode.index;
var argumentIndex = argumentElement.__argumentIndex;
if (typeof argumentIndex !== "number")
argumentIndex = -1;
CanvasAgent.evaluateTraceLogCallArgument(this._traceLogId, callIndex, argumentIndex, objectGroupName, showObjectPopover.bind(this));
}
},
/**
* @param {!WebInspector.RemoteObject} object
* @return {string}
*/
_hexNumbersFormatter: function(object)
{
if (object.type === "number") {
// Show enum values in hex with min length of 4 (e.g. 0x0012).
var str = "0000" + Number(object.description).toString(16).toUpperCase();
str = str.replace(/^0+(.{4,})$/, "$1");
return "0x" + str;
}
return object.description || "";
},
_onHidePopover: function()
{
if (this._popoverAnchorElement) {
this._popoverAnchorElement.remove()
delete this._popoverAnchorElement;
}
},
_flattenSingleFrameNode: function()
{
var rootNode = this._logGrid.rootNode();
if (rootNode.children.length !== 1)
return;
var frameNode = rootNode.children[0];
while (frameNode.children[0])
rootNode.appendChild(frameNode.children[0]);
rootNode.removeChild(frameNode);
},
__proto__: WebInspector.VBox.prototype
}
/**
* @constructor
* @extends {WebInspector.ProfileType}
*/
WebInspector.CanvasProfileType = function()
{
WebInspector.ProfileType.call(this, WebInspector.CanvasProfileType.TypeId, WebInspector.UIString("Capture Canvas Frame"));
this._recording = false;
this._lastProfileHeader = null;
this._capturingModeSelector = new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));
this._capturingModeSelector.element.title = WebInspector.UIString("Canvas capture mode.");
this._capturingModeSelector.createOption(WebInspector.UIString("Single Frame"), WebInspector.UIString("Capture a single canvas frame."), "");
this._capturingModeSelector.createOption(WebInspector.UIString("Consecutive Frames"), WebInspector.UIString("Capture consecutive canvas frames."), "1");
/** @type {!Object.<string, !Element>} */
this._frameOptions = {};
/** @type {!Object.<string, boolean>} */
this._framesWithCanvases = {};
this._frameSelector = new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));
this._frameSelector.element.title = WebInspector.UIString("Frame containing the canvases to capture.");
this._frameSelector.element.classList.add("hidden");
this._target = /** @type {!WebInspector.Target} */ (WebInspector.targetManager.activeTarget());
this._target.resourceTreeModel.frames().forEach(this._addFrame, this);
this._target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this);
this._target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameRemoved, this);
this._dispatcher = new WebInspector.CanvasDispatcher(this);
this._canvasAgentEnabled = false;
this._decorationElement = document.createElement("div");
this._decorationElement.className = "profile-canvas-decoration";
this._updateDecorationElement();
}
WebInspector.CanvasProfileType.TypeId = "CANVAS_PROFILE";
WebInspector.CanvasProfileType.prototype = {
get statusBarItems()
{
return [this._capturingModeSelector.element, this._frameSelector.element];
},
get buttonTooltip()
{
if (this._isSingleFrameMode())
return WebInspector.UIString("Capture next canvas frame.");
else
return this._recording ? WebInspector.UIString("Stop capturing canvas frames.") : WebInspector.UIString("Start capturing canvas frames.");
},
/**
* @override
* @return {boolean}
*/
buttonClicked: function()
{
if (!this._canvasAgentEnabled)
return false;
if (this._recording) {
this._recording = false;
this._stopFrameCapturing();
} else if (this._isSingleFrameMode()) {
this._recording = false;
this._runSingleFrameCapturing();
} else {
this._recording = true;
this._startFrameCapturing();
}
return this._recording;
},
_runSingleFrameCapturing: function()
{
var frameId = this._selectedFrameId();
CanvasAgent.captureFrame(frameId, this._didStartCapturingFrame.bind(this, frameId));
},
_startFrameCapturing: function()
{
var frameId = this._selectedFrameId();
CanvasAgent.startCapturing(frameId, this._didStartCapturingFrame.bind(this, frameId));
},
_stopFrameCapturing: function()
{
if (!this._lastProfileHeader)
return;
var profileHeader = this._lastProfileHeader;
var traceLogId = profileHeader.traceLogId();
this._lastProfileHeader = null;
function didStopCapturing()
{
profileHeader._updateCapturingStatus();
}
CanvasAgent.stopCapturing(traceLogId, didStopCapturing);
},
/**
* @param {string|undefined} frameId
* @param {?Protocol.Error} error
* @param {!CanvasAgent.TraceLogId} traceLogId
*/
_didStartCapturingFrame: function(frameId, error, traceLogId)
{
if (error || this._lastProfileHeader && this._lastProfileHeader.traceLogId() === traceLogId)
return;
var profileHeader = new WebInspector.CanvasProfileHeader(this._target, this, traceLogId, frameId);
this._lastProfileHeader = profileHeader;
this.addProfile(profileHeader);
profileHeader._updateCapturingStatus();
},
get treeItemTitle()
{
return WebInspector.UIString("CANVAS PROFILE");
},
get description()
{
return WebInspector.UIString("Canvas calls instrumentation");
},
/**
* @override
* @return {!Element}
*/
decorationElement: function()
{
return this._decorationElement;
},
/**
* @override
* @param {!WebInspector.ProfileHeader} profile
*/
removeProfile: function(profile)
{
WebInspector.ProfileType.prototype.removeProfile.call(this, profile);
if (this._recording && profile === this._lastProfileHeader)
this._recording = false;
},
/**
* @param {boolean=} forcePageReload
*/
_updateDecorationElement: function(forcePageReload)
{
this._decorationElement.removeChildren();
this._decorationElement.createChild("div", "warning-icon-small");
this._decorationElement.appendChild(document.createTextNode(this._canvasAgentEnabled ? WebInspector.UIString("Canvas Profiler is enabled.") : WebInspector.UIString("Canvas Profiler is disabled.")));
var button = this._decorationElement.createChild("button");
button.type = "button";
button.textContent = this._canvasAgentEnabled ? WebInspector.UIString("Disable") : WebInspector.UIString("Enable");
button.addEventListener("click", this._onProfilerEnableButtonClick.bind(this, !this._canvasAgentEnabled), false);
var target = this._target;
/**
* @param {?Protocol.Error} error
* @param {boolean} result
*/
function hasUninstrumentedCanvasesCallback(error, result)
{
if (error || result)
target.resourceTreeModel.reloadPage();
}
if (forcePageReload) {
if (this._canvasAgentEnabled) {
CanvasAgent.hasUninstrumentedCanvases(hasUninstrumentedCanvasesCallback);
} else {
for (var frameId in this._framesWithCanvases) {
if (this._framesWithCanvases.hasOwnProperty(frameId)) {
target.resourceTreeModel.reloadPage();
break;
}
}
}
}
},
/**
* @param {boolean} enable
*/
_onProfilerEnableButtonClick: function(enable)
{
if (this._canvasAgentEnabled === enable)
return;
/**
* @param {?Protocol.Error} error
* @this {WebInspector.CanvasProfileType}
*/
function callback(error)
{
if (error)
return;
this._canvasAgentEnabled = enable;
this._updateDecorationElement(true);
this._dispatchViewUpdatedEvent();
}
if (enable)
CanvasAgent.enable(callback.bind(this));
else
CanvasAgent.disable(callback.bind(this));
},
/**
* @return {boolean}
*/
_isSingleFrameMode: function()
{
return !this._capturingModeSelector.selectedOption().value;
},
/**
* @param {!WebInspector.Event} event
*/
_frameAdded: function(event)
{
var frame = /** @type {!WebInspector.ResourceTreeFrame} */ (event.data);
this._addFrame(frame);
},
/**
* @param {!WebInspector.ResourceTreeFrame} frame
*/
_addFrame: function(frame)
{
var frameId = frame.id;
var option = document.createElement("option");
option.text = frame.displayName();
option.title = frame.url;
option.value = frameId;
this._frameOptions[frameId] = option;
if (this._framesWithCanvases[frameId]) {
this._frameSelector.addOption(option);
this._dispatchViewUpdatedEvent();
}
},
/**
* @param {!WebInspector.Event} event
*/
_frameRemoved: function(event)
{
var frame = /** @type {!WebInspector.ResourceTreeFrame} */ (event.data);
var frameId = frame.id;
var option = this._frameOptions[frameId];
if (option && this._framesWithCanvases[frameId]) {
this._frameSelector.removeOption(option);
this._dispatchViewUpdatedEvent();
}
delete this._frameOptions[frameId];
delete this._framesWithCanvases[frameId];
},
/**
* @param {string} frameId
*/
_contextCreated: function(frameId)
{
if (this._framesWithCanvases[frameId])
return;
this._framesWithCanvases[frameId] = true;
var option = this._frameOptions[frameId];
if (option) {
this._frameSelector.addOption(option);
this._dispatchViewUpdatedEvent();
}
},
/**
* @param {!PageAgent.FrameId=} frameId
* @param {!CanvasAgent.TraceLogId=} traceLogId
*/
_traceLogsRemoved: function(frameId, traceLogId)
{
var sidebarElementsToDelete = [];
var sidebarElements = /** @type {!Array.<!WebInspector.ProfileSidebarTreeElement>} */ ((this.treeElement && this.treeElement.children) || []);
for (var i = 0, n = sidebarElements.length; i < n; ++i) {
var header = /** @type {!WebInspector.CanvasProfileHeader} */ (sidebarElements[i].profile);
if (!header)
continue;
if (frameId && frameId !== header.frameId())
continue;
if (traceLogId && traceLogId !== header.traceLogId())
continue;
sidebarElementsToDelete.push(sidebarElements[i]);
}
for (var i = 0, n = sidebarElementsToDelete.length; i < n; ++i)
sidebarElementsToDelete[i].ondelete();
},
/**
* @return {string|undefined}
*/
_selectedFrameId: function()
{
var option = this._frameSelector.selectedOption();
return option ? option.value : undefined;
},
_dispatchViewUpdatedEvent: function()
{
this._frameSelector.element.classList.toggle("hidden", this._frameSelector.size() <= 1);
this.dispatchEventToListeners(WebInspector.ProfileType.Events.ViewUpdated);
},
/**
* @override
* @return {boolean}
*/
isInstantProfile: function()
{
return this._isSingleFrameMode();
},
/**
* @override
* @return {boolean}
*/
isEnabled: function()
{
return this._canvasAgentEnabled;
},
__proto__: WebInspector.ProfileType.prototype
}
/**
* @constructor
* @implements {CanvasAgent.Dispatcher}
* @param {!WebInspector.CanvasProfileType} profileType
*/
WebInspector.CanvasDispatcher = function(profileType)
{
this._profileType = profileType;
InspectorBackend.registerCanvasDispatcher(this);
}
WebInspector.CanvasDispatcher.prototype = {
/**
* @param {string} frameId
*/
contextCreated: function(frameId)
{
this._profileType._contextCreated(frameId);
},
/**
* @param {!PageAgent.FrameId=} frameId
* @param {!CanvasAgent.TraceLogId=} traceLogId
*/
traceLogsRemoved: function(frameId, traceLogId)
{
this._profileType._traceLogsRemoved(frameId, traceLogId);
}
}
/**
* @constructor
* @extends {WebInspector.ProfileHeader}
* @param {!WebInspector.Target} target
* @param {!WebInspector.CanvasProfileType} type
* @param {!CanvasAgent.TraceLogId=} traceLogId
* @param {!PageAgent.FrameId=} frameId
*/
WebInspector.CanvasProfileHeader = function(target, type, traceLogId, frameId)
{
WebInspector.ProfileHeader.call(this, target, type, WebInspector.UIString("Trace Log %d", type._nextProfileUid));
/** @type {!CanvasAgent.TraceLogId} */
this._traceLogId = traceLogId || "";
this._frameId = frameId;
this._alive = true;
this._traceLogSize = 0;
this._traceLogPlayer = traceLogId ? new WebInspector.CanvasTraceLogPlayerProxy(traceLogId) : null;
}
WebInspector.CanvasProfileHeader.prototype = {
/**
* @return {!CanvasAgent.TraceLogId}
*/
traceLogId: function()
{
return this._traceLogId;
},
/**
* @return {?WebInspector.CanvasTraceLogPlayerProxy}
*/
traceLogPlayer: function()
{
return this._traceLogPlayer;
},
/**
* @return {!PageAgent.FrameId|undefined}
*/
frameId: function()
{
return this._frameId;
},
/**
* @override
* @return {!WebInspector.ProfileSidebarTreeElement}
*/
createSidebarTreeElement: function()
{
return new WebInspector.ProfileSidebarTreeElement(this, "profile-sidebar-tree-item");
},
/**
* @override
* @return {!WebInspector.CanvasProfileView}
*/
createView: function()
{
return new WebInspector.CanvasProfileView(this);
},
/**
* @override
*/
dispose: function()
{
if (this._traceLogPlayer)
this._traceLogPlayer.dispose();
clearTimeout(this._requestStatusTimer);
this._alive = false;
},
/**
* @param {!CanvasAgent.TraceLog=} traceLog
*/
_updateCapturingStatus: function(traceLog)
{
if (!this._traceLogId)
return;
if (traceLog) {
this._alive = traceLog.alive;
this._traceLogSize = traceLog.totalAvailableCalls;
}
var subtitle = this._alive ? WebInspector.UIString("Capturing\u2026 %d calls", this._traceLogSize) : WebInspector.UIString("Captured %d calls", this._traceLogSize);
this.updateStatus(subtitle, this._alive);
if (this._alive) {
clearTimeout(this._requestStatusTimer);
this._requestStatusTimer = setTimeout(this._requestCapturingStatus.bind(this), WebInspector.CanvasProfileView.TraceLogPollingInterval);
}
},
_requestCapturingStatus: function()
{
/**
* @param {?CanvasAgent.TraceLog} traceLog
* @this {WebInspector.CanvasProfileHeader}
*/
function didReceiveTraceLog(traceLog)
{
if (!traceLog)
return;
this._alive = traceLog.alive;
this._traceLogSize = traceLog.totalAvailableCalls;
this._updateCapturingStatus();
}
this._traceLogPlayer.getTraceLog(0, 0, didReceiveTraceLog.bind(this));
},
__proto__: WebInspector.ProfileHeader.prototype
}
WebInspector.CanvasProfileDataGridHelper = {
/**
* @param {!CanvasAgent.CallArgument} callArgument
* @return {!Element}
*/
createCallArgumentElement: function(callArgument)
{
if (callArgument.enumName)
return WebInspector.CanvasProfileDataGridHelper.createEnumValueElement(callArgument.enumName, +callArgument.description);
var element = document.createElement("span");
element.className = "canvas-call-argument";
var description = callArgument.description;
if (callArgument.type === "string") {
const maxStringLength = 150;
element.createTextChild("\"");
element.createChild("span", "canvas-formatted-string").textContent = description.trimMiddle(maxStringLength);
element.createTextChild("\"");
element.__suppressPopover = (description.length <= maxStringLength && !/[\r\n]/.test(description));
if (!element.__suppressPopover)
element.__evalResult = WebInspector.runtimeModel.createRemoteObjectFromPrimitiveValue(description);
} else {
var type = callArgument.subtype || callArgument.type;
if (type) {
element.classList.add("canvas-formatted-" + type);
if (["null", "undefined", "boolean", "number"].indexOf(type) >= 0)
element.__suppressPopover = true;
}
element.textContent = description;
if (callArgument.remoteObject)
element.__evalResult = WebInspector.runtimeModel.createRemoteObject(callArgument.remoteObject);
}
if (callArgument.resourceId) {
element.classList.add("canvas-formatted-resource");
element.__resourceId = callArgument.resourceId;
}
return element;
},
/**
* @param {string} enumName
* @param {number} enumValue
* @return {!Element}
*/
createEnumValueElement: function(enumName, enumValue)
{
var element = document.createElement("span");
element.className = "canvas-call-argument canvas-formatted-number";
element.textContent = enumName;
element.__evalResult = WebInspector.runtimeModel.createRemoteObjectFromPrimitiveValue(enumValue);
return element;
}
}
/**
* @extends {WebInspector.Object}
* @constructor
* @param {!CanvasAgent.TraceLogId} traceLogId
*/
WebInspector.CanvasTraceLogPlayerProxy = function(traceLogId)
{
this._traceLogId = traceLogId;
/** @type {!Object.<string, !CanvasAgent.ResourceState>} */
this._currentResourceStates = {};
/** @type {?CanvasAgent.ResourceId} */
this._defaultResourceId = null;
}
/** @enum {string} */
WebInspector.CanvasTraceLogPlayerProxy.Events = {
CanvasTraceLogReceived: "CanvasTraceLogReceived",
CanvasReplayStateChanged: "CanvasReplayStateChanged",
CanvasResourceStateReceived: "CanvasResourceStateReceived",
}
WebInspector.CanvasTraceLogPlayerProxy.prototype = {
/**
* @param {number|undefined} startOffset
* @param {number|undefined} maxLength
* @param {function(?CanvasAgent.TraceLog):void} userCallback
*/
getTraceLog: function(startOffset, maxLength, userCallback)
{
/**
* @param {?Protocol.Error} error
* @param {!CanvasAgent.TraceLog} traceLog
* @this {WebInspector.CanvasTraceLogPlayerProxy}
*/
function callback(error, traceLog)
{
if (error || !traceLog) {
userCallback(null);
return;
}
userCallback(traceLog);
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasTraceLogReceived, traceLog);
}
CanvasAgent.getTraceLog(this._traceLogId, startOffset, maxLength, callback.bind(this));
},
dispose: function()
{
this._currentResourceStates = {};
CanvasAgent.dropTraceLog(this._traceLogId);
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);
},
/**
* @param {?CanvasAgent.ResourceId} resourceId
* @param {function(?CanvasAgent.ResourceState):void} userCallback
*/
getResourceState: function(resourceId, userCallback)
{
resourceId = resourceId || this._defaultResourceId;
if (!resourceId) {
userCallback(null); // Has not been replayed yet.
return;
}
var effectiveResourceId = /** @type {!CanvasAgent.ResourceId} */ (resourceId);
if (this._currentResourceStates[effectiveResourceId]) {
userCallback(this._currentResourceStates[effectiveResourceId]);
return;
}
/**
* @param {?Protocol.Error} error
* @param {!CanvasAgent.ResourceState} resourceState
* @this {WebInspector.CanvasTraceLogPlayerProxy}
*/
function callback(error, resourceState)
{
if (error || !resourceState) {
userCallback(null);
return;
}
this._currentResourceStates[effectiveResourceId] = resourceState;
userCallback(resourceState);
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived, resourceState);
}
CanvasAgent.getResourceState(this._traceLogId, effectiveResourceId, callback.bind(this));
},
/**
* @param {number} index
* @param {function(?CanvasAgent.ResourceState, number):void} userCallback
*/
replayTraceLog: function(index, userCallback)
{
/**
* @param {?Protocol.Error} error
* @param {!CanvasAgent.ResourceState} resourceState
* @param {number} replayTime
* @this {WebInspector.CanvasTraceLogPlayerProxy}
*/
function callback(error, resourceState, replayTime)
{
this._currentResourceStates = {};
if (error) {
userCallback(null, replayTime);
} else {
this._defaultResourceId = resourceState.id;
this._currentResourceStates[resourceState.id] = resourceState;
userCallback(resourceState, replayTime);
}
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);
if (!error)
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived, resourceState);
}
CanvasAgent.replayTraceLog(this._traceLogId, index, callback.bind(this));
},
clearResourceStates: function()
{
this._currentResourceStates = {};
this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);
},
__proto__: WebInspector.Object.prototype
}
| DevTools: Fix regression in canvas profiler.
BUG=367117
[email protected], dgozman, pfeldman
Review URL: https://codereview.chromium.org/258693005
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@172639 bbb929c8-8fbe-4397-9dbb-9b2b20218538
| Source/devtools/front_end/profiler/CanvasProfileView.js | DevTools: Fix regression in canvas profiler. | <ide><path>ource/devtools/front_end/profiler/CanvasProfileView.js
<ide> replayImageContainerView.setMinimumSize(50, 28);
<ide> replayImageContainerView.show(this._imageSplitView.mainElement());
<ide>
<del> var replayImageContainer = replayImageContainerView.element;
<add> // NOTE: The replayImageContainer can NOT be a flex div (e.g. VBox or SplitView elements)!
<add> var replayImageContainer = replayImageContainerView.element.createChild("div");
<ide> replayImageContainer.id = "canvas-replay-image-container";
<ide> this._replayImageElement = replayImageContainer.createChild("img", "canvas-replay-image");
<ide> this._debugInfoElement = replayImageContainer.createChild("div", "canvas-debug-info hidden"); |
|
Java | apache-2.0 | 90c916f14c8202b835994b711fd536d8bf9a8c3c | 0 | Tim108/corve,Tim108/corve | package corve.save;
import corve.setup.Settings;
import corve.util.Chore;
import corve.util.Record;
import corve.util.Room;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DBController {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private Connection conn;
/**
* Finds the most recent record of the given chore and returns its room id
* Searches in both the records table as well as the archive table
*/
public int getLastRoomID(Chore chore) {
openConnection();
int roomID = -1;
try {
PreparedStatement ps = conn.prepareStatement("SELECT room_id FROM (SELECT * FROM archive UNION SELECT * FROM records) r where r.chore_id =" + chore.getId() + " ORDER BY start_date DESC LIMIT 1");
ResultSet rs = ps.executeQuery();
if (rs.first()) {
roomID = rs.getInt("room_id");
}
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return roomID;
}
public void addRecord(Record record) {
openConnection();
try {
PreparedStatement ps = conn.prepareStatement("INSERT INTO records (room_id, chore_id, start_date, end_date, done_room_id, code) VALUES (?,?,?,?,?,?)");
if (record.getId() != -1) {
ps = conn.prepareStatement("INSERT INTO records (room_id, chore_id, start_date, end_date, done_room_id, code, id) VALUES (?,?,?,?,?,?,?)");
ps.setInt(7, record.getId());
}
ps.setInt(1, record.getRoom_id());
ps.setInt(2, record.getChore_id());
ps.setTimestamp(3, record.getStart_date());
ps.setTimestamp(4, record.getEnd_date());
ps.setInt(5, record.getDone_room_id());
ps.setString(6, record.getCode());
ps.execute();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
}
public void punish() throws SQLException {
openConnection();
PreparedStatement ps1 = conn.prepareStatement("set @N := (now());");
PreparedStatement ps2 = conn.prepareStatement("INSERT INTO settlements(room_id, record_id, amount) SELECT x.id, x.room_id, -10 FROM (SELECT * FROM records WHERE @N > records.end_date AND records.done_room_id = -1) x ;");
PreparedStatement ps3 = conn.prepareStatement("INSERT INTO archive select * FROM records where records.end_date < @N;");
PreparedStatement ps4 = conn.prepareStatement("DELETE FROM records where records.end_date < @N;");
try {
conn.setAutoCommit(false);
ps1.execute();
ps2.execute();
ps3.execute();
ps4.execute();
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
System.err.print("Transaction is being rolled back");
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
} finally {
if (ps1 != null) {
ps1.close();
}
if (ps2 != null) {
ps2.close();
}
if (ps3 != null) {
ps3.close();
}
if (ps4 != null) {
ps4.close();
}
conn.setAutoCommit(true);
}
closeConnection();
}
public List<Room> getRooms() {
openConnection();
List<Room> rooms = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM rooms");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
rooms.add(new Room(id, name, email));
}
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return rooms;
}
public List<Chore> getChores() {
openConnection();
List<Chore> chores = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM chores");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String description = rs.getString("description");
int choreinterval = rs.getInt("choreinterval");
chores.add(new Chore(id, name, choreinterval));
}
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return chores;
}
/**
* opens the database connection
*/
private void openConnection() {
System.out.println("Database connection opened");
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(Settings.DB_URL, Settings.DB_USERNAME, Settings.DB_PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
/**
* closes the database connections
*/
private void closeConnection() {
System.out.println("Database connection closed");
try {
conn.close();
} catch (SQLException e) {
//it's fine
}
}
}
| src/corve/save/DBController.java | package corve.save;
import corve.setup.Settings;
import corve.util.Chore;
import corve.util.Record;
import corve.util.Room;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DBController {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private Connection conn;
/**
* Finds the most recent record of the given chore and returns its room id
* Searches in both the records table as well as the archive table
*/
public int getLastRoomID(Chore chore) {
openConnection();
int roomID = -1;
try {
PreparedStatement ps = conn.prepareStatement("SELECT room_id FROM (SELECT * FROM archive UNION SELECT * FROM records) r where r.chore_id =" + chore.getId() + " ORDER BY start_date DESC LIMIT 1");
ResultSet rs = ps.executeQuery();
if (rs.first()) {
roomID = rs.getInt("room_id");
}
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return roomID;
}
public void addRecord(Record record) {
openConnection();
try {
PreparedStatement ps = conn.prepareStatement("INSERT INTO records (room_id, chore_id, start_date, end_date, done_room_id, code) VALUES (?,?,?,?,?,?)");
if (record.getId() != -1) {
ps = conn.prepareStatement("INSERT INTO records (room_id, chore_id, start_date, end_date, done_room_id, code, id) VALUES (?,?,?,?,?,?,?)");
ps.setInt(7, record.getId());
}
ps.setInt(1, record.getRoom_id());
ps.setInt(2, record.getChore_id());
ps.setTimestamp(3, record.getStart_date());
ps.setTimestamp(4, record.getEnd_date());
ps.setInt(5, record.getDone_room_id());
ps.setString(6, record.getCode());
ps.execute();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
}
public void punish() throws SQLException {
openConnection();
PreparedStatement ps1 = conn.prepareStatement("set @N := (now());");
PreparedStatement ps2 = conn.prepareStatement("INSERT INTO settlements(room_id, record_id, amount) SELECT x.id, x.room_id, 10 FROM (SELECT * FROM records WHERE @N > records.end_date AND records.done_room_id = -1) x ;");
PreparedStatement ps3 = conn.prepareStatement("INSERT INTO archive select * FROM records where records.end_date < @N;");
PreparedStatement ps4 = conn.prepareStatement("DELETE FROM records where records.end_date < @N;");
try {
conn.setAutoCommit(false);
ps1.execute();
ps2.execute();
ps3.execute();
ps4.execute();
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
System.err.print("Transaction is being rolled back");
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
} finally {
if (ps1 != null) {
ps1.close();
}
if (ps2 != null) {
ps2.close();
}
if (ps3 != null) {
ps3.close();
}
if (ps4 != null) {
ps4.close();
}
conn.setAutoCommit(true);
}
closeConnection();
}
public List<Room> getRooms() {
openConnection();
List<Room> rooms = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM rooms");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
rooms.add(new Room(id, name, email));
}
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return rooms;
}
public List<Chore> getChores() {
openConnection();
List<Chore> chores = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM chores");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String description = rs.getString("description");
int choreinterval = rs.getInt("choreinterval");
chores.add(new Chore(id, name, choreinterval));
}
} catch (SQLException e) {
e.printStackTrace();
}
closeConnection();
return chores;
}
/**
* opens the database connection
*/
private void openConnection() {
System.out.println("Database connection opened");
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(Settings.DB_URL, Settings.DB_USERNAME, Settings.DB_PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
/**
* closes the database connections
*/
private void closeConnection() {
System.out.println("Database connection closed");
try {
conn.close();
} catch (SQLException e) {
//it's fine
}
}
}
| punishing now puts -10 as settlement instead of 10
| src/corve/save/DBController.java | punishing now puts -10 as settlement instead of 10 | <ide><path>rc/corve/save/DBController.java
<ide> public void punish() throws SQLException {
<ide> openConnection();
<ide> PreparedStatement ps1 = conn.prepareStatement("set @N := (now());");
<del> PreparedStatement ps2 = conn.prepareStatement("INSERT INTO settlements(room_id, record_id, amount) SELECT x.id, x.room_id, 10 FROM (SELECT * FROM records WHERE @N > records.end_date AND records.done_room_id = -1) x ;");
<add> PreparedStatement ps2 = conn.prepareStatement("INSERT INTO settlements(room_id, record_id, amount) SELECT x.id, x.room_id, -10 FROM (SELECT * FROM records WHERE @N > records.end_date AND records.done_room_id = -1) x ;");
<ide> PreparedStatement ps3 = conn.prepareStatement("INSERT INTO archive select * FROM records where records.end_date < @N;");
<ide> PreparedStatement ps4 = conn.prepareStatement("DELETE FROM records where records.end_date < @N;");
<ide> |
|
Java | mit | error: pathspec 'java/src/easy_leetcode/next_greater_element_1.java' did not match any file(s) known to git
| 612e3530d29b8930f7c167216d995d94e16db2e0 | 1 | sinderpl/CodingExamples,sinderpl/CodingExamples,sinderpl/CodingExamples,sinderpl/CodingExamples,sinderpl/CodingExamples | /**
* You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2.
Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, return -1 for this number.
*/
public class next_greater_element_1{
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] output = new int[nums1.length];
int curr = 0;
for(int i = 0; i < nums1.length; i++){
output[curr] = -1;
for(int y = i; y < nums2.length; y ++){
if(nums2[y] > nums1[i]){
output[curr] = nums2[y];
break;
}
}
curr++;
}
return output;
}
} | java/src/easy_leetcode/next_greater_element_1.java | next greater element
| java/src/easy_leetcode/next_greater_element_1.java | next greater element | <ide><path>ava/src/easy_leetcode/next_greater_element_1.java
<add>/**
<add> * You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2.
<add>
<add>Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
<add>
<add>The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, return -1 for this number.
<add> */
<add>
<add>public class next_greater_element_1{
<add> public int[] nextGreaterElement(int[] nums1, int[] nums2) {
<add> int[] output = new int[nums1.length];
<add> int curr = 0;
<add>
<add> for(int i = 0; i < nums1.length; i++){
<add> output[curr] = -1;
<add> for(int y = i; y < nums2.length; y ++){
<add> if(nums2[y] > nums1[i]){
<add> output[curr] = nums2[y];
<add> break;
<add> }
<add> }
<add> curr++;
<add> }
<add>
<add> return output;
<add> }
<add>} |
|
Java | apache-2.0 | error: pathspec 'addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactModificationTests.java' did not match any file(s) known to git
| 2092ffba63064caa446cd561fe507078fe4fb175 | 1 | anaximines/training_jft | package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
/**
* Created by anaximines on 26/07/16.
*/
public class ContactModificationTests extends TestBase {
@Test
public void testContactModificationFromContactsList(){
app.getNavigationHelper().gotoHomePage();
app.getContactHelper().openEditForm();
app.getContactHelper().fillContactInfo(new ContactData("changedFirstName", "middleName", "lastName", "nickname", "title", "company", "address", "homeTel", "mobileTel", "workTel", "faxTel", "email", "email2", "email3", "homepage", "secondaryAddress", "secondaryHome", "secondaryNotes"));
app.getContactHelper().submitContactModification();
app.getNavigationHelper().returnToHomePage();
}
@Test
public void testContactModificationFromContactCard(){
app.getNavigationHelper().gotoHomePage();
app.getContactHelper().openContactCard();
app.getContactHelper().initContactModification();
app.getContactHelper().fillContactInfo(new ContactData("changedFirstName", "middleName", "lastName", "nickname", "title", "company", "address", "homeTel", "mobileTel", "workTel", "faxTel", "email", "email2", "email3", "homepage", "secondaryAddress", "secondaryHome", "secondaryNotes"));
app.getContactHelper().submitContactModification();
app.getNavigationHelper().returnToHomePage();
}
}
| addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactModificationTests.java | Создан набор тестов на изменение контакта
| addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactModificationTests.java | Создан набор тестов на изменение контакта | <ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactModificationTests.java
<add>package ru.stqa.pft.addressbook.tests;
<add>
<add>import org.testng.annotations.Test;
<add>import ru.stqa.pft.addressbook.model.ContactData;
<add>
<add>/**
<add> * Created by anaximines on 26/07/16.
<add> */
<add>public class ContactModificationTests extends TestBase {
<add>
<add> @Test
<add> public void testContactModificationFromContactsList(){
<add> app.getNavigationHelper().gotoHomePage();
<add> app.getContactHelper().openEditForm();
<add> app.getContactHelper().fillContactInfo(new ContactData("changedFirstName", "middleName", "lastName", "nickname", "title", "company", "address", "homeTel", "mobileTel", "workTel", "faxTel", "email", "email2", "email3", "homepage", "secondaryAddress", "secondaryHome", "secondaryNotes"));
<add> app.getContactHelper().submitContactModification();
<add> app.getNavigationHelper().returnToHomePage();
<add> }
<add>
<add> @Test
<add> public void testContactModificationFromContactCard(){
<add> app.getNavigationHelper().gotoHomePage();
<add> app.getContactHelper().openContactCard();
<add> app.getContactHelper().initContactModification();
<add> app.getContactHelper().fillContactInfo(new ContactData("changedFirstName", "middleName", "lastName", "nickname", "title", "company", "address", "homeTel", "mobileTel", "workTel", "faxTel", "email", "email2", "email3", "homepage", "secondaryAddress", "secondaryHome", "secondaryNotes"));
<add> app.getContactHelper().submitContactModification();
<add> app.getNavigationHelper().returnToHomePage();
<add> }
<add>} |
|
JavaScript | apache-2.0 | af088e230cae05874b8c583646632aa206107ae4 | 0 | KlausTrainer/pouchdb,mikeymckay/pouchdb,lukevanhorn/pouchdb,callahanchris/pouchdb,mikeymckay/pouchdb,ramdhavepreetam/pouchdb,ramdhavepreetam/pouchdb,Knowledge-OTP/pouchdb,cshum/pouchdb,TechnicalPursuit/pouchdb,HospitalRun/pouchdb,cdaringe/pouchdb,mattbailey/pouchdb,tohagan/pouchdb,nickcolley/pouchdb,KlausTrainer/pouchdb,patrickgrey/pouchdb,KlausTrainer/pouchdb,mainerror/pouchdb,mattbailey/pouchdb,optikfluffel/pouchdb,microlv/pouchdb,Dashed/pouchdb,colinskow/pouchdb,yaronyg/pouchdb,h4ki/pouchdb,jhs/pouchdb,asmiller/pouchdb,nicolasbrugneaux/pouchdb,greyhwndz/pouchdb,microlv/pouchdb,seigel/pouchdb,janl/pouchdb,mwksl/pouchdb,callahanchris/pouchdb,Knowledge-OTP/pouchdb,yaronyg/pouchdb,ramdhavepreetam/pouchdb,crissdev/pouchdb,janl/pouchdb,ntwcklng/pouchdb,Actonate/pouchdb,lukevanhorn/pouchdb,HospitalRun/pouchdb,h4ki/pouchdb,mattbailey/pouchdb,tohagan/pouchdb,janraasch/pouchdb,tyler-johnson/pouchdb,lukevanhorn/pouchdb,johnofkorea/pouchdb,microlv/pouchdb,bbenezech/pouchdb,bbenezech/pouchdb,slang800/pouchdb,daleharvey/pouchdb,optikfluffel/pouchdb,nickcolley/pouchdb,nicolasbrugneaux/pouchdb,cshum/pouchdb,cesarmarinhorj/pouchdb,mainerror/pouchdb,garrensmith/pouchdb,adamvert/pouchdb,Actonate/pouchdb,pouchdb/pouchdb,cshum/pouchdb,janraasch/pouchdb,optikfluffel/pouchdb,daleharvey/pouchdb,p5150j/pouchdb,ntwcklng/pouchdb,pouchdb/pouchdb,pouchdb/pouchdb,shimaore/pouchdb,Knowledge-OTP/pouchdb,willholley/pouchdb,Charlotteis/pouchdb,p5150j/pouchdb,colinskow/pouchdb,slang800/pouchdb,willholley/pouchdb,cesarmarinhorj/pouchdb,elkingtonmcb/pouchdb,greyhwndz/pouchdb,Charlotteis/pouchdb,elkingtonmcb/pouchdb,marcusandre/pouchdb,mwksl/pouchdb,seigel/pouchdb,cdaringe/pouchdb,asmiller/pouchdb,marcusandre/pouchdb,patrickgrey/pouchdb,garrensmith/pouchdb,willholley/pouchdb,adamvert/pouchdb,lakhansamani/pouchdb,Actonate/pouchdb,HospitalRun/pouchdb,tyler-johnson/pouchdb,daleharvey/pouchdb,slang800/pouchdb,p5150j/pouchdb,johnofkorea/pouchdb,mikeymckay/pouchdb,janraasch/pouchdb,nickcolley/pouchdb,Dashed/pouchdb,garrensmith/pouchdb,patrickgrey/pouchdb,lakhansamani/pouchdb,callahanchris/pouchdb,ntwcklng/pouchdb,nicolasbrugneaux/pouchdb,lakhansamani/pouchdb,cdaringe/pouchdb,jhs/pouchdb,jhs/pouchdb,crissdev/pouchdb,seigel/pouchdb,mainerror/pouchdb,yaronyg/pouchdb,marcusandre/pouchdb,evidenceprime/pouchdb,johnofkorea/pouchdb,colinskow/pouchdb,crissdev/pouchdb,elkingtonmcb/pouchdb,shimaore/pouchdb,Dashed/pouchdb,cesarmarinhorj/pouchdb,janl/pouchdb,tohagan/pouchdb,Charlotteis/pouchdb,greyhwndz/pouchdb,shimaore/pouchdb,bbenezech/pouchdb,asmiller/pouchdb,tyler-johnson/pouchdb,mwksl/pouchdb,adamvert/pouchdb,TechnicalPursuit/pouchdb,h4ki/pouchdb,TechnicalPursuit/pouchdb |
'use strict';
var adapters = ['http', 'local'];
adapters.forEach(function (adapter) {
describe('test.changes.js-' + adapter, function () {
var dbs = {};
beforeEach(function (done) {
dbs.name = testUtils.adapterUrl(adapter, 'testdb');
dbs.remote = testUtils.adapterUrl(adapter, 'test_repl_remote');
testUtils.cleanup([dbs.name, dbs.remote], done);
});
after(function (done) {
testUtils.cleanup([dbs.name, dbs.remote], done);
});
it('All changes', function (done) {
var db = new PouchDB(dbs.name);
db.post({ test: 'somestuff' }, function (err, info) {
var promise = db.changes({
onChange: function (change) {
change.should.not.have.property('doc');
change.should.have.property('seq');
done();
}
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
it('Promise resolved when changes cancelled', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
{_id: '8', integer: 9},
{_id: '9', integer: 9},
{_id: '10', integer: 10},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
var changeCount = 0;
var promise = db.changes({
onChange: function (change) {
changeCount++;
if (changeCount === 5) {
promise.cancel();
}
}
});
should.exist(promise);
should.exist(promise.then);
promise.then.should.be.a('function');
promise.then(
function (result) {
changeCount.should.equal(5, 'changeCount');
should.exist(result);
result.should.deep.equal({status: 'cancelled'});
done();
}, function (err) {
changeCount.should.equal(5, 'changeCount');
should.exist(err);
done();
});
});
});
it('Changes Since Old Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
{_id: '8', integer: 9},
{_id: '9', integer: 9},
{_id: '10', integer: 10},
{_id: '11', integer: 11}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
var docs2 = [
{_id: '12', integer: 12},
{_id: '13', integer: 13}
];
db.bulkDocs({ docs: docs2 }, function (err, info) {
var promise = db.changes({
since: update_seq,
complete: function (err, results) {
results.results.length.should.be.at.least(2);
done();
}
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
});
});
it('Changes Since New Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
{_id: '8', integer: 9},
{_id: '9', integer: 9},
{_id: '10', integer: 10},
{_id: '11', integer: 11}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
var docs2 = [
{_id: '12', integer: 12},
{_id: '13', integer: 13}
];
db.bulkDocs({ docs: docs2 }, function (err, info) {
var promise = db.changes({
since: update_seq
}).on('complete', function (results) {
results.results.length.should.be.at.least(2);
done();
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
});
});
it('Changes Since and limit Old Style liimt 1', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
var docs2 = [
{_id: '3', integer: 3},
{_id: '4', integer: 4}
];
db.bulkDocs({ docs: docs2 }, function (err, info) {
db.changes({
since: update_seq,
limit: 1,
complete: function (err, results) {
results.results.length.should.equal(1);
done();
}
});
});
});
});
});
it('Changes Since and limit New Style limit 1', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 1
}).on('complete', function (results) {
results.results.length.should.equal(1);
done();
});
});
});
it('Changes Since and limit Old Style limit 0', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 0,
complete: function (err, results) {
results.results.length.should.equal(1);
done();
}
});
});
});
it('Changes Since and limit New Style limit 0', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 0
}).on('complete', function (results) {
results.results.length.should.equal(1);
done();
});
});
});
it('Changes limit Old Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
var db = new PouchDB(dbs.name);
// we use writeDocs since bulkDocs looks to have undefined
// order of doing insertions
testUtils.writeDocs(db, docs1, function (err, info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
db.put(docs2[0], function (err, info) {
db.put(docs2[1], function (err, info) {
db.changes({
limit: 2,
since: 2,
include_docs: true,
complete: function (err, results) {
results.last_seq.should.equal(6);
results = results.results;
results.length.should.equal(2);
results[0].id.should.equal('2');
results[0].seq.should.equal(5);
results[0].doc.integer.should.equal(11);
results[1].id.should.equal('3');
results[1].seq.should.equal(6);
results[1].doc.integer.should.equal(12);
done();
}
});
});
});
});
});
it('Changes limit New Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
var db = new PouchDB(dbs.name);
// we use writeDocs since bulkDocs looks to have undefined
// order of doing insertions
testUtils.writeDocs(db, docs1, function (err, info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
db.put(docs2[0], function (err, info) {
db.put(docs2[1], function (err, info) {
db.changes({
limit: 2,
since: 2,
include_docs: true
}).on('complete', function (results) {
results.last_seq.should.equal(6);
results = results.results;
results.length.should.equal(2);
results[0].id.should.equal('2');
results[0].seq.should.equal(5);
results[0].doc.integer.should.equal(11);
results[1].id.should.equal('3');
results[1].seq.should.equal(6);
results[1].doc.integer.should.equal(12);
done();
});
});
});
});
});
it('Changes with filter not present in ddoc', function (done) {
this.timeout(15000);
var docs = [
{_id: '1', integer: 1},
{ _id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: 'foo/odd',
limit: 2,
include_docs: true,
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: odd');
should.not.exist(results);
done();
}
});
});
});
it('Changes with `filters` key not present in ddoc', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
views: {
even: {
map: 'function (doc) { if (doc.integer % 2 === 1)' +
' { emit(doc._id, null) }; }'
}
}
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: 'foo/even',
limit: 2,
include_docs: true,
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: filters');
should.not.exist(results);
done();
}
});
});
});
it('Changes limit and filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2}
];
var db = new PouchDB(dbs.name);
var docs2 = [
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{
_id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
testUtils.writeDocs(db, docs2, function (err, info) {
var promise = db.changes({
filter: 'foo/even',
limit: 2,
since: update_seq,
include_docs: true,
complete: function (err, results) {
results.results.length.should.equal(2);
results.results[0].id.should.equal('3');
results.results[0].doc.integer.should.equal(3);
results.results[1].id.should.equal('5');
results.results[1].doc.integer.should.equal(5);
done();
}
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
});
});
it('Changes with filter from nonexistent ddoc', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: 'foobar/odd',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
should.not.exist(results);
done();
}
});
});
});
it('Changes with view not present in ddoc', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
views:
{ even:
{ map: 'function (doc) { if (doc.integer % 2 === 1) { ' +
'emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
view: 'foo/odd',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: odd');
should.not.exist(results);
done();
}
});
});
});
it('Changes with `views` key not present in ddoc', function (done) {
var docs = [
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
view: 'foo/even',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: views',
// 'correct error reason returned');
should.not.exist(results);
done();
}
});
});
});
it('Changes with missing param `view` in request', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
views: { even: { map: 'function (doc) { if (doc.integer % 2 === 1) ' +
'{ emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.BAD_REQUEST.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.BAD_REQUEST.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should
// .equal('`view` filter parameter is not provided.',
// 'correct error reason returned');
should.not.exist(results);
done();
}
});
});
});
it('Changes limit and view instead of filter', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{
_id: '_design/foo',
integer: 4,
views: { even: { map: 'function (doc) { if (doc.integer % 2 === 1) ' +
'{ emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
view: 'foo/even',
limit: 2,
since: 2,
include_docs: true,
complete: function (err, results) {
results.results.length.should.equal(2);
results.results[0].id.should.equal('3');
results.results[0].seq.should.equal(4);
results.results[0].doc.integer.should.equal(3);
results.results[1].id.should.equal('5');
results.results[1].seq.should.equal(6);
results.results[1].doc.integer.should.equal(5);
done();
}
});
});
});
it('Changes last_seq', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{
_id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
var db = new PouchDB(dbs.name);
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(0);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(5);
db.changes({
filter: 'foo/even',
complete: function (err, results) {
results.last_seq.should.equal(5);
results.results.length.should.equal(2);
done();
}
});
}
});
});
}
});
});
it('Changes last_seq with view instead of filter', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{
_id: '_design/foo',
integer: 4,
views:
{ even:
{ map: 'function (doc) { if (doc.integer % 2 === 1) { ' +
'emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(0);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(5);
db.changes({
filter: '_view',
view: 'foo/even',
complete: function (err, results) {
results.last_seq.should.equal(5);
results.results.length.should.equal(2);
done();
}
});
}
});
});
}
});
});
it('Changes with style = all_docs', function (done) {
var simpleTree = [
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-b', value: 'foo b'},
{_id: 'foo', _rev: '3-c', value: 'foo c'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-d', value: 'foo d'},
{_id: 'foo', _rev: '3-e', value: 'foo e'},
{_id: 'foo', _rev: '4-f', value: 'foo f'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-g', value: 'foo g', _deleted: true}]
];
var db = new PouchDB(dbs.name);
testUtils.putTree(db, simpleTree, function () {
db.changes({
complete: function (err, res) {
res.results[0].changes.length.should.equal(1);
res.results[0].changes[0].rev.should.equal('4-f');
db.changes({
style: 'all_docs',
complete: function (err, res) {
res.results[0].changes.length.should.equal(3);
var changes = res.results[0].changes;
changes.sort(function (a, b) {
return a.rev < b.rev;
});
changes[0].rev.should.equal('4-f');
changes[1].rev.should.equal('3-c');
changes[2].rev.should.equal('2-g');
done();
}
});
}
});
});
});
it('Changes with style = all_docs and a callback for complete',
function (done) {
var simpleTree = [
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-b', value: 'foo b'},
{_id: 'foo', _rev: '3-c', value: 'foo c'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-d', value: 'foo d'},
{_id: 'foo', _rev: '3-e', value: 'foo e'},
{_id: 'foo', _rev: '4-f', value: 'foo f'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-g', value: 'foo g', _deleted: true}]
];
var db = new PouchDB(dbs.name);
testUtils.putTree(db, simpleTree, function () {
db.changes(function (err, res) {
res.results[0].changes.length.should.equal(1);
res.results[0].changes[0].rev.should.equal('4-f');
db.changes({
style: 'all_docs',
complete: function () {
done(new Error('this should never be called'));
}
}, function (err, res) {
res.results[0].changes.length.should.equal(3);
var changes = res.results[0].changes;
changes.sort(function (a, b) {
return a.rev < b.rev;
});
changes[0].rev.should.equal('4-f');
changes[1].rev.should.equal('3-c');
changes[2].rev.should.equal('2-g');
done();
});
});
});
});
it('Changes limit = 0', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
limit: 0,
complete: function (err, results) {
results.results.length.should.equal(1);
done();
}
});
});
});
// Note for the following test that CouchDB's implementation of /_changes
// with `descending=true` ignores any `since` parameter.
it('Descending changes', function (done) {
var db = new PouchDB(dbs.name);
db.post({_id: '0', test: 'ing'}, function (err, res) {
db.post({_id: '1', test: 'ing'}, function (err, res) {
db.post({_id: '2', test: 'ing'}, function (err, res) {
db.changes({
descending: true,
since: 1,
complete: function (err, results) {
results.results.length.should.equal(3);
var ids = ['2', '1', '0'];
results.results.forEach(function (row, i) {
row.id.should.equal(ids[i]);
});
done();
}
});
});
});
});
});
it('Changes doc Old Style', function (done) {
var db = new PouchDB(dbs.name);
db.post({ test: 'somestuff' }, function (err, info) {
db.changes({
include_docs: true,
onChange: function (change) {
change.doc._id.should.equal(change.id);
change.doc._rev.should
.equal(change.changes[change.changes.length - 1].rev);
done();
}
});
});
});
it('Changes doc New Style', function (done) {
var db = new PouchDB(dbs.name);
db.post({ test: 'somestuff' }, function (err, info) {
db.changes({
include_docs: true
}).on('change', function (change) {
change.doc._id.should.equal(change.id);
change.doc._rev.should
.equal(change.changes[change.changes.length - 1].rev);
done();
});
});
});
// Note for the following test that CouchDB's implementation of /_changes
// with `descending=true` ignores any `since` parameter.
it('Descending many changes Old Style', function (done) {
var db = new PouchDB(dbs.name);
var docs = [];
var num = 100;
for (var i = 0; i < num; i++) {
docs.push({
_id: 'doc_' + i,
foo: 'bar_' + i
});
}
var changes = 0;
db.bulkDocs({ docs: docs }, function (err, info) {
if (err) {
return done(err);
}
db.changes({
descending: true,
onChange: function (change) {
changes++;
},
complete: function (err, results) {
if (err) {
return done(err);
}
changes.should.equal(num, 'correct number of changes');
done();
}
});
});
});
it('Descending many changes New Style', function (done) {
var db = new PouchDB(dbs.name);
var docs = [];
var num = 100;
for (var i = 0; i < num; i++) {
docs.push({
_id: 'doc_' + i,
foo: 'bar_' + i
});
}
var changes = 0;
db.bulkDocs({ docs: docs }, function (err, info) {
if (err) {
return done(err);
}
db.changes({
descending: true
}).on('change', function (change) {
changes++;
}).on('complete', function (results) {
changes.should.equal(num, 'correct number of changes');
done();
}).on('error', function (err) {
done(err);
});
});
});
it('live-changes Old Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes = db.changes({
live: true,
complete: function () {
count.should.equal(1);
done();
},
onChange: function (change) {
count += 1;
change.should.not.have.property('doc');
count.should.equal(1);
changes.cancel();
},
});
db.post({ test: 'adoc' });
});
it('live-changes New Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes = db.changes({
live: true
}).on('complete', function () {
count.should.equal(1);
done();
}).on('change', function (change) {
count += 1;
change.should.not.have.property('doc');
count.should.equal(1);
changes.cancel();
});
db.post({ test: 'adoc' });
});
it('Multiple watchers Old Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes1Complete = false;
var changes2Complete = false;
function checkCount() {
if (changes1Complete && changes2Complete) {
count.should.equal(2);
done();
}
}
var changes1 = db.changes({
complete: function () {
changes1Complete = true;
checkCount();
},
onChange: function (change) {
count += 1;
changes1.cancel();
changes1 = null;
},
live: true
});
var changes2 = db.changes({
complete: function () {
changes2Complete = true;
checkCount();
},
onChange: function (change) {
count += 1;
changes2.cancel();
changes2 = null;
},
live: true
});
db.post({test: 'adoc'});
});
it('Multiple watchers New Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes1Complete = false;
var changes2Complete = false;
function checkCount() {
if (changes1Complete && changes2Complete) {
count.should.equal(2);
done();
}
}
var changes1 = db.changes({
live: true
}).on('complete', function () {
changes1Complete = true;
checkCount();
}).on('change', function (change) {
count += 1;
changes1.cancel();
changes1 = null;
});
var changes2 = db.changes({
live: true
}).on('complete', function () {
changes2Complete = true;
checkCount();
}).on('change', function (change) {
count += 1;
changes2.cancel();
changes2 = null;
});
db.post({test: 'adoc'});
});
it('Continuous changes doc', function (done) {
var db = new PouchDB(dbs.name);
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
onChange: function (change) {
change.should.have.property('doc');
change.doc.should.have.property('_rev');
changes.cancel();
},
live: true,
include_docs: true
});
db.post({ test: 'adoc' });
});
it('Cancel changes Old Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var interval;
var docPosted = false;
// We want to wait for a period of time after the final
// document was posted to ensure we didnt see another
// change
function waitForDocPosted() {
if (!docPosted) {
return;
}
clearInterval(interval);
setTimeout(function () {
count.should.equal(1);
done();
}, 200);
}
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
// This setTimeout ensures that once we cancel a change we dont
// recieve subsequent callbacks, so it is needed
interval = setInterval(waitForDocPosted, 100);
},
onChange: function (change) {
count += 1;
if (count === 1) {
changes.cancel();
db.post({ test: 'another doc' }, function (err, res) {
if (err) {
return done(err);
}
docPosted = true;
});
}
},
live: true
});
db.post({ test: 'adoc' });
});
it('Cancel changes New Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var interval;
var docPosted = false;
// We want to wait for a period of time after the final
// document was posted to ensure we didnt see another
// change
function waitForDocPosted() {
if (!docPosted) {
return;
}
clearInterval(interval);
setTimeout(function () {
count.should.equal(1);
done();
}, 200);
}
var changes = db.changes({
live: true
}).on('complete', function (result) {
result.status.should.equal('cancelled');
// This setTimeout ensures that once we cancel a change we dont recieve
// subsequent callbacks, so it is needed
interval = setInterval(waitForDocPosted, 100);
}).on('change', function (change) {
count += 1;
if (count === 1) {
changes.cancel();
db.post({ test: 'another doc' }, function (err, res) {
if (err) {
return done(err);
}
docPosted = true;
});
}
});
db.post({ test: 'adoc' });
});
// TODO: https://github.com/daleharvey/pouchdb/issues/1460
it('Kill database while listening to live changes', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
db.changes({
complete: function (err, result) {
done();
},
onChange: function (change) {
count++;
if (count === 1) {
PouchDB.destroy(dbs.name);
}
},
live: true
});
db.post({ test: 'adoc' });
});
it('#3136 style=all_docs, right order', function () {
var db = new PouchDB(dbs.name);
var chain = PouchDB.utils.Promise.resolve();
var docIds = ['b', 'c', 'a', 'z', 'd', 'e'];
docIds.forEach(function (docId) {
chain = chain.then(function () {
return db.put({_id: docId});
});
});
return chain.then(function () {
return db.changes({style: 'all_docs'});
}).then(function (res) {
var ids = res.results.map(function (x) {
return x.id;
});
ids.should.deep.equal(docIds);
});
});
it('#3136 style=all_docs & include_docs, right order', function () {
var db = new PouchDB(dbs.name);
var chain = PouchDB.utils.Promise.resolve();
var docIds = ['b', 'c', 'a', 'z', 'd', 'e'];
docIds.forEach(function (docId) {
chain = chain.then(function () {
return db.put({_id: docId});
});
});
return chain.then(function () {
return db.changes({
style: 'all_docs',
include_docs: true
});
}).then(function (res) {
var ids = res.results.map(function (x) {
return x.id;
});
ids.should.deep.equal(docIds);
});
});
it('#3136 tricky changes, limit/descending', function () {
var db = new PouchDB(dbs.name);
var docs = [
{
_id: 'alpha',
_rev: '1-a',
_revisions: {
start: 1,
ids: ['a']
}
}, {
_id: 'beta',
_rev: '1-b',
_revisions: {
start: 1,
ids: ['b']
}
}, {
_id: 'gamma',
_rev: '1-b',
_revisions: {
start: 1,
ids: ['b']
}
}, {
_id: 'alpha',
_rev: '2-d',
_revisions: {
start: 2,
ids: ['d', 'a']
}
}, {
_id: 'beta',
_rev: '2-e',
_revisions: {
start: 2,
ids: ['e', 'b']
}
}, {
_id: 'beta',
_rev: '3-f',
_deleted: true,
_revisions: {
start: 3,
ids: ['f', 'e', 'b']
}
}
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [];
docs.forEach(function (doc) {
chain = chain.then(function () {
return db.bulkDocs([doc], {new_edits: false}).then(function () {
return db.changes({doc_ids: [doc._id]});
}).then(function (res) {
seqs.push(res.results[0].seq);
});
});
});
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
return chain.then(function () {
return db.changes();
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [
{
"seq": seqs[2],
"id": "gamma",
"changes": [{ "rev": "1-b"}
]
},
{
"seq": seqs[3],
"id": "alpha",
"changes": [{ "rev": "2-d"}
]
},
{
"seq": seqs[5],
"id": "beta",
"deleted": true,
"changes": [{ "rev": "3-f"}
]
}
]
//, "last_seq": seqs[5]
});
return db.changes({limit: 0});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}]
//, "last_seq": seqs[2]
}, '1:' + JSON.stringify(result));
return db.changes({limit: 1});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}]
//, "last_seq": seqs[2]
}, '2:' + JSON.stringify(result));
return db.changes({limit: 2});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}, {"seq": seqs[3], "id": "alpha", "changes": [{"rev": "2-d"}]}]
//, last_seq": seqs[3]
}, '3:' + JSON.stringify(result));
return db.changes({limit: 1, descending: true});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[5],
"id": "beta",
"changes": [{"rev": "3-f"}],
"deleted": true
}]
//, "last_seq": seqs[5]
}, '4:' + JSON.stringify(result));
return db.changes({limit: 2, descending: true});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
var expected = {
"results": [{
"seq": seqs[5],
"id": "beta",
"changes": [{"rev": "3-f"}],
"deleted": true
}, {"seq": seqs[3], "id": "alpha", "changes": [{"rev": "2-d"}]}]
//, "last_seq": seqs[3]
};
result.should.deep.equal(expected, '5:' + JSON.stringify(result) +
', shoulda got: ' + JSON.stringify(expected));
return db.changes({descending: true});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
var expected = {
"results": [{
"seq": seqs[5],
"id": "beta",
"changes": [{"rev": "3-f"}],
"deleted": true
}, {"seq": seqs[3], "id": "alpha", "changes": [{"rev": "2-d"}]}, {
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}]
//, "last_seq": seqs[2]
};
result.should.deep.equal(expected, '6:' + JSON.stringify(result) +
', shoulda got: ' + JSON.stringify(expected));
});
});
it('#3136 winningRev has a lower seq, style=all_docs', function () {
var db = new PouchDB(dbs.name);
var tree = [
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-e',
_deleted: true,
_revisions: {start: 2, ids: ['e', 'a']}
},
{
_id: 'foo',
_rev: '3-g',
_revisions: {start: 3, ids: ['g', 'e', 'a']}
}
],
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-b',
_revisions: {start: 2, ids: ['b', 'a']}
},
{
_id: 'foo',
_rev: '3-c',
_revisions: {start: 3, ids: ['c', 'b', 'a']}
}
],
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-d',
_revisions: {start: 2, ids: ['d', 'a']}
},
{
_id: 'foo',
_rev: '3-h',
_revisions: {start: 3, ids: ['h', 'd', 'a']}
},
{
_id: 'foo',
_rev: '4-f',
_revisions: {start: 4, ids: ['f', 'h', 'd', 'a']}
}
]
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [0];
function getExpected(i) {
var expecteds = [
{
"results": [
{
"seq": seqs[1],
"id": "foo",
"changes": [{"rev": "3-g"}],
"doc": {"_id": "foo", "_rev": "3-g"}
}
],
"last_seq" : seqs[1]
},
{
"results": [
{
"seq": seqs[2],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}],
"doc": {"_id": "foo", "_rev": "3-g"}
}
],
"last_seq" : seqs[2]
},
{
"results": [
{
"seq": seqs[3],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}, {"rev": "4-f"}],
"doc": {"_id": "foo", "_rev": "4-f"}
}
],
"last_seq" : seqs[3]
}
];
return expecteds[i];
}
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
tree.forEach(function (docs, i) {
chain = chain.then(function () {
return db.bulkDocs(docs, {new_edits: false}).then(function () {
return db.changes({
style: 'all_docs',
since: seqs[seqs.length - 1],
include_docs: true
});
}).then(function (result) {
seqs.push(result.last_seq);
var expected = getExpected(i);
normalizeResult(result);
result.should.deep.equal(expected,
i + ': should get: ' + JSON.stringify(expected) +
', but got: ' + JSON.stringify(result));
});
});
});
return chain;
});
it('#3136 winningRev has a lower seq, style=all_docs 2', function () {
var db = new PouchDB(dbs.name);
var tree = [
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-e',
_deleted: true,
_revisions: {start: 2, ids: ['e', 'a']}
},
{
_id: 'foo',
_rev: '3-g',
_revisions: {start: 3, ids: ['g', 'e', 'a']}
}
], [
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-b',
_revisions: {start: 2, ids: ['b', 'a']}
},
{
_id: 'foo',
_rev: '3-c',
_revisions: {start: 3, ids: ['c', 'b', 'a']}
},
], [
{
_id: 'bar',
_rev: '1-z',
_revisions: {start: 1, ids: ['z']}
}
]
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [0];
tree.forEach(function (docs, i) {
chain = chain.then(function () {
return db.bulkDocs(docs, {new_edits: false}).then(function () {
return db.changes();
}).then(function (result) {
seqs.push(result.last_seq);
});
});
});
return chain.then(function () {
var expecteds = [
{
"results": [{
"seq": seqs[2],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}]
}, {"seq": seqs[3], "id": "bar", "changes": [{"rev": "1-z"}]}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[2],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}]
}, {"seq": seqs[3], "id": "bar", "changes": [{"rev": "1-z"}]}],
"last_seq": seqs[3]
},
{
"results": [{"seq": seqs[3], "id": "bar",
"changes": [{"rev": "1-z"}]}],
"last_seq": seqs[3]
},
{"results": [], "last_seq": seqs[3]}
];
var chain2 = PouchDB.utils.Promise.resolve();
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
seqs.forEach(function (seq, i) {
chain2 = chain2.then(function () {
return db.changes({
since: seq,
style: 'all_docs'
}).then(function (res) {
normalizeResult(res);
res.should.deep.equal(expecteds[i], 'since=' + seq +
': got: ' +
JSON.stringify(res) +
', shoulda got: ' +
JSON.stringify(expecteds[i]));
});
});
});
return chain2;
});
});
it('#3136 winningRev has a higher seq, using limit', function () {
var db = new PouchDB(dbs.name);
var tree = [
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
}
], [
{
_id: 'foo',
_rev: '2-b',
_revisions: {start: 2, ids: ['b', 'a']}
}
], [
{
_id: 'bar',
_rev: '1-x',
_revisions: {start: 1, ids: ['x']}
}
], [
{
_id: 'foo',
_rev: '2-c',
_deleted: true,
_revisions: {start: 2, ids: ['c', 'a']}
},
]
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [0];
tree.forEach(function (docs, i) {
chain = chain.then(function () {
return db.bulkDocs(docs, {new_edits: false}).then(function () {
return db.changes().then(function (result) {
seqs.push(result.last_seq);
});
});
});
});
return chain.then(function () {
var expecteds = [{
"results": [{
"seq": seqs[3],
"id": "bar",
"changes": [{"rev": "1-x"}],
"doc": {"_id": "bar", "_rev": "1-x"}
}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[3],
"id": "bar",
"changes": [{"rev": "1-x"}],
"doc": {"_id": "bar", "_rev": "1-x"}
}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[3],
"id": "bar",
"changes": [{"rev": "1-x"}],
"doc": {"_id": "bar", "_rev": "1-x"}
}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[4],
"id": "foo",
"changes": [{"rev": "2-b"}, {"rev": "2-c"}],
"doc": {"_id": "foo", "_rev": "2-b"}
}],
"last_seq": seqs[4]
},
{"results": [], "last_seq": seqs[4]}
];
var chain2 = PouchDB.utils.Promise.resolve();
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
seqs.forEach(function (seq, i) {
chain2 = chain2.then(function () {
return db.changes({
style: 'all_docs',
since: seq,
limit: 1,
include_docs: true
});
}).then(function (result) {
normalizeResult(result);
result.should.deep.equal(expecteds[i],
i + ': got: ' + JSON.stringify(result) +
', shoulda got: ' + JSON.stringify(expecteds[i]));
});
});
return chain2;
});
});
it('changes-filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
];
var db = new PouchDB(dbs.name);
var count = 0;
db.bulkDocs({ docs: docs1 }, function (err, info) {
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
filter: function (doc) {
return doc.integer % 2 === 0;
},
onChange: function (change) {
count += 1;
if (count === 4) {
changes.cancel();
}
},
live: true
});
db.bulkDocs({ docs: docs2 });
});
});
it('changes-filter with query params', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
];
var params = { 'abc': true };
var db = new PouchDB(dbs.name);
var count = 0;
db.bulkDocs({ docs: docs1 }, function (err, info) {
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
filter: function (doc, req) {
if (req.query.abc) {
return doc.integer % 2 === 0;
}
},
query_params: params,
onChange: function (change) {
count += 1;
if (count === 4) {
changes.cancel();
}
},
live: true
});
db.bulkDocs({ docs: docs2 });
});
});
it('Non-live changes filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.changes({
filter: function (doc) {
return doc.integer % 2 === 0;
},
complete: function (err, changes) {
// Should get docs 0 and 2 if the filter has been applied correctly.
changes.results.length.should.equal(2);
done();
}
});
});
});
it('#2569 Non-live doc_ids filter', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
doc_ids: ['1', '3']
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
ids.sort().should.deep.equal(['1', '3']);
});
});
it('#2569 Big non-live doc_ids filter', function () {
var docs = [];
for (var i = 0; i < 5; i++) {
var id = '';
for (var j = 0; j < 50; j++) {
// make a huge id
id += PouchDB.utils.btoa(Math.random().toString());
}
docs.push({_id: id});
}
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
doc_ids: [docs[1]._id, docs[3]._id]
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
var expectedIds = [docs[1]._id, docs[3]._id];
ids.sort().should.deep.equal(expectedIds.sort());
});
});
it('#2569 Live doc_ids filter', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return new PouchDB.utils.Promise(function (resolve, reject) {
var retChanges = [];
var changes = db.changes({
doc_ids: ['1', '3'],
live: true
}).on('change', function (change) {
retChanges.push(change);
if (retChanges.length === 2) {
changes.cancel();
resolve(retChanges);
}
}).on('error', reject);
});
}).then(function (changes) {
var ids = changes.map(function (x) {
return x.id;
});
var expectedIds = ['1', '3'];
ids.sort().should.deep.equal(expectedIds);
});
});
it('#2569 Big live doc_ids filter', function () {
var docs = [];
for (var i = 0; i < 5; i++) {
var id = '';
for (var j = 0; j < 50; j++) {
// make a huge id
id += PouchDB.utils.btoa(Math.random().toString());
}
docs.push({_id: id});
}
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return new PouchDB.utils.Promise(function (resolve, reject) {
var retChanges = [];
var changes = db.changes({
doc_ids: [docs[1]._id, docs[3]._id],
live: true
}).on('change', function (change) {
retChanges.push(change);
if (retChanges.length === 2) {
changes.cancel();
resolve(retChanges);
}
}).on('error', reject);
});
}).then(function (changes) {
var ids = changes.map(function (x) {
return x.id;
});
var expectedIds = [docs[1]._id, docs[3]._id];
ids.sort().should.deep.equal(expectedIds.sort());
});
});
it('#2569 Non-live doc_ids filter with filter=_doc_ids', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
filter: '_doc_ids',
doc_ids: ['1', '3']
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
ids.sort().should.deep.equal(['1', '3']);
});
});
it('#2569 Live doc_ids filter with filter=_doc_ids', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
filter: '_doc_ids',
doc_ids: ['1', '3']
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
ids.sort().should.deep.equal(['1', '3']);
});
});
it('Changes to same doc are grouped', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
db.put(docs2[0], function (err, info) {
db.put(docs2[1], function (err, info) {
db.changes({
include_docs: true,
complete: function (err, changes) {
changes.results.length.should.equal(4);
changes.results[2].seq.should.equal(5);
changes.results[2].id.should.equal('2');
changes.results[2].changes.length.should.equal(1);
changes.results[2].doc.integer.should.equal(11);
done();
}
});
});
});
});
});
it('Changes with conflicts are handled correctly', function (testDone) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
new PouchDB(dbs.name).then(function (localdb) {
var remotedb = new PouchDB(dbs.remote);
return localdb.bulkDocs({ docs: docs1 }).then(function (info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
return localdb.put(docs2[0]).then(function (info) {
return localdb.put(docs2[1]).then(function (info) {
var rev2 = info.rev;
return PouchDB.replicate(localdb, remotedb).then(function (done) {
// update remote once, local twice, then replicate from
// remote to local so the remote losing conflict is later in
// the tree
return localdb.put({
_id: '3',
_rev: rev2,
integer: 20
}).then(function (resp) {
var rev3Doc = {
_id: '3',
_rev: resp.rev,
integer: 30
};
return localdb.put(rev3Doc).then(function (resp) {
var rev4local = resp.rev;
var rev4Doc = {
_id: '3',
_rev: rev2,
integer: 100
};
return remotedb.put(rev4Doc).then(function (resp) {
var remoterev = resp.rev;
return PouchDB.replicate(remotedb, localdb).then(
function (done) {
return localdb.changes({
include_docs: true,
style: 'all_docs',
conflicts: true
}).on('error', testDone)
.then(function (changes) {
changes.results.length.should.equal(4);
var ch = changes.results[3];
ch.id.should.equal('3');
ch.changes.length.should.equal(2);
ch.doc.integer.should.equal(30);
ch.doc._rev.should.equal(rev4local);
ch.changes.should.deep.equal([
{ rev: rev4local },
{ rev: remoterev }
]);
ch.doc.should.have.property('_conflicts');
ch.doc._conflicts.length.should.equal(1);
ch.doc._conflicts[0].should.equal(remoterev);
});
});
});
});
});
});
});
});
}).then(function () {
testDone();
}, testDone);
});
});
it('Change entry for a deleted doc', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
var rev = info[3].rev;
db.remove({
_id: '3',
_rev: rev
}, function (err, info) {
db.changes({
include_docs: true,
complete: function (err, changes) {
changes.results.length.should.equal(4);
var ch = changes.results[3];
ch.id.should.equal('3');
ch.seq.should.equal(5);
ch.deleted.should.equal(true);
done();
}
});
});
});
});
it('changes large number of docs', function (done) {
var docs = [];
var num = 30;
for (var i = 0; i < num; i++) {
docs.push({
_id: 'doc_' + i,
foo: 'bar_' + i
});
}
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
complete: function (err, res) {
res.results.length.should.equal(num);
done();
}
});
});
});
it('Calling db.changes({since: \'now\'})', function (done) {
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: [{ foo: 'bar' }] }, function (err, data) {
db.info(function (err, info) {
var api = db.changes({
since: 'now',
complete: function (err, res) {
should.not.exist(err);
res.last_seq.should.equal(info.update_seq);
done();
}
});
api.should.be.an('object');
api.cancel.should.be.an('function');
});
});
});
//Duplicate to make sure both api options work.
it('Calling db.changes({since: \'latest\'})', function (done) {
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: [{ foo: 'bar' }] }, function (err, data) {
db.info(function (err, info) {
var api = db.changes({
since: 'latest',
complete: function (err, res) {
should.not.exist(err);
res.last_seq.should.equal(info.update_seq);
done();
}
});
api.should.be.an('object');
api.cancel.should.be.an('function');
});
});
});
it('Closing db does not cause a crash if changes cancelled',
function (done) {
var db = new PouchDB(dbs.name);
var called = 0;
function checkDone() {
called++;
if (called === 2) {
done();
}
}
db.bulkDocs({ docs: [{ foo: 'bar' }] }, function (err, data) {
var changes = db.changes({
live: true,
onChange: function () { },
complete: function (err, result) {
result.status.should.equal('cancelled');
checkDone();
}
});
should.exist(changes);
changes.cancel.should.be.a('function');
changes.cancel();
db.close(function (error) {
should.not.exist(error);
checkDone();
});
});
});
it('fire-complete-on-cancel', function (done) {
var db = new PouchDB(dbs.name);
var cancelled = false;
var changes = db.changes({
live: true,
complete: function (err, result) {
cancelled.should.equal(true);
should.not.exist(err);
should.exist(result);
if (result) {
result.status.should.equal('cancelled');
}
done();
}
});
should.exist(changes);
changes.cancel.should.be.a('function');
setTimeout(function () {
cancelled = true;
changes.cancel();
}, 100);
});
it('changes are not duplicated', function (done) {
var db = new PouchDB(dbs.name);
var called = 0;
var changes = db.changes({
live: true,
onChange: function () {
called++;
if (called === 1) {
setTimeout(function () {
changes.cancel();
}, 1000);
}
},
complete: function (err) {
called.should.equal(1);
done();
}
});
db.post({key: 'value'});
});
function waitASec(fun, time) {
return new PouchDB.utils.Promise(function (fulfill) {
setTimeout(function () {
fulfill(fun());
}, time);
});
}
it('CRUD events are handled correclty', function (done) {
var db = new PouchDB(dbs.name);
var changes = db.changes({
live: true,
style: 'all_docs'
});
var deleted = 0;
var updated = 0;
var created = 0;
function chuckDone() {
if ((deleted + updated + created) === 6) {
changes.cancel();
}
}
changes.on('cancel', function () {
setTimeout(function () {
deleted.should.equal(1, 'correct number of deleted');
created.should.equal(2, 'create number of created');
updated.should.equal(3, 'correct number of updates');
done();
}, 100);
}).on('delete', function (change) {
deleted++;
chuckDone();
}).on('create', function (change) {
created++;
chuckDone();
}).on('update', function (change) {
updated++;
chuckDone();
}).on('error', function (err) {
done(err);
});
var rev1, rev2;
db.put({
title: 'Holding On For Life'
}, 'currentSong').then(function (resp) {
rev1 = resp.rev;
return waitASec(function () {
return db.put({
title: 'Sushi'
}, 'nextSong');
}, 100);
}).then(function (resp) {
rev2 = resp.rev;
return waitASec(function () {
return db.put({
title: 'Holding On For Life',
artist: 'Broken Bells'
}, 'currentSong', rev1);
}, 100);
}).then(function (resp) {
rev1 = resp.rev;
return waitASec(function () {
return db.put({
title: 'Sushi',
artist: 'Kyle Andrews'
}, 'nextSong', rev2);
}, 100);
}).then(function (resp) {
rev2 = resp.rev;
return waitASec(function () {
return db.remove({
_id: 'currentSong',
_rev: rev1
});
}, 100);
}).then(function (resp) {
return db.put({
title: 'Sushi',
artist: 'Kyle Andrews',
album: 'Real Blasty'
}, 'nextSong', rev2);
});
});
it('supports returnDocs=false', function (done) {
var db = new PouchDB(dbs.name);
var docs = [];
var num = 10;
for (var i = 0; i < num; i++) {
docs.push({ _id: 'doc_' + i, });
}
var changes = 0;
db.bulkDocs({ docs: docs }, function (err, info) {
if (err) {
return done(err);
}
db.changes({
descending: true,
returnDocs : false
}).on('change', function (change) {
changes++;
}).on('complete', function (results) {
results.results.should.have.length(0, '0 results returned');
changes.should.equal(num, 'correct number of changes');
done();
}).on('error', function (err) {
done(err);
});
});
});
it('should respects limit', function (done) {
var docs1 = [
{_id: '_local/foo'},
{_id: 'a', integer: 0},
{_id: 'b', integer: 1},
{_id: 'c', integer: 2},
{_id: 'd', integer: 3}
];
var called = 0;
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.changes({
limit: 1
}).on('change', function (ch) {
(called++).should.equal(0);
}).on('complete', function () {
setTimeout(function () {
done();
}, 50);
});
});
});
it.skip('should respects limit with live replication', function (done) {
var docs1 = [
{_id: '_local/foo'},
{_id: 'a', integer: 0},
{_id: 'b', integer: 1},
{_id: 'c', integer: 2},
{_id: 'd', integer: 3}
];
var called = 0;
var doneCalled = 0;
function calldone() {
doneCalled++;
if (doneCalled === 2) {
done();
}
}
var db = new PouchDB(dbs.name);
db.changes({
limit: 1,
live: true
}).on('change', function (ch) {
ch.id.should.equal('a');
(called++).should.equal(0);
}).on('complete', function () {
calldone();
});
db.bulkDocs({ docs: docs1 }).then(calldone);
});
it('doesn\'t throw if opts.complete is undefined', function (done) {
var db = new PouchDB(dbs.name);
db.put({_id: 'foo'}).then(function () {
db.changes().on('change', function () {
done();
}).on('error', function (err) {
done(err);
});
}, done);
});
it('it handles a bunch of individual changes in live replication',
function (done) {
var db = new PouchDB(dbs.name);
var len = 80;
var called = 0;
var changesDone = false;
var changesWritten = 0;
var changes = db.changes({live: true});
changes.on('change', function () {
called++;
if (called === len) {
changes.cancel();
}
}).on('error', done).on('complete', function () {
changesDone = true;
maybeDone();
});
var i = -1;
function maybeDone() {
if (changesDone && changesWritten === len) {
done();
}
}
function after() {
changesWritten++;
db.listeners('destroyed').should.have.length.lessThan(5);
maybeDone();
}
while (++i < len) {
db.post({}).then(after).catch(done);
}
});
it('changes-filter without filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
];
var db = new PouchDB(dbs.name);
var count = 0;
db.bulkDocs({ docs: docs1 }, function (err, info) {
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
onChange: function (change) {
count += 1;
if (count === 8) {
changes.cancel();
}
},
live: true
});
db.bulkDocs({ docs: docs2 });
});
});
});
});
describe('changes-standalone', function () {
it('Changes reports errors', function (done) {
this.timeout(2000);
var db = new PouchDB('http://infiniterequest.com', { skipSetup: true });
db.changes({
timeout: 1000,
complete: function (err, changes) {
should.exist(err);
done();
}
});
});
});
| tests/integration/test.changes.js |
'use strict';
var adapters = ['http', 'local'];
adapters.forEach(function (adapter) {
describe('test.changes.js-' + adapter, function () {
var dbs = {};
beforeEach(function (done) {
dbs.name = testUtils.adapterUrl(adapter, 'testdb');
dbs.remote = testUtils.adapterUrl(adapter, 'test_repl_remote');
testUtils.cleanup([dbs.name, dbs.remote], done);
});
after(function (done) {
testUtils.cleanup([dbs.name, dbs.remote], done);
});
it('All changes', function (done) {
var db = new PouchDB(dbs.name);
db.post({ test: 'somestuff' }, function (err, info) {
var promise = db.changes({
onChange: function (change) {
change.should.not.have.property('doc');
change.should.have.property('seq');
done();
}
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
it('Promise resolved when changes cancelled', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
{_id: '8', integer: 9},
{_id: '9', integer: 9},
{_id: '10', integer: 10},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
var changeCount = 0;
var promise = db.changes({
onChange: function (change) {
changeCount++;
if (changeCount === 5) {
promise.cancel();
}
}
});
should.exist(promise);
should.exist(promise.then);
promise.then.should.be.a('function');
promise.then(
function (result) {
changeCount.should.equal(5, 'changeCount');
should.exist(result);
result.should.deep.equal({status: 'cancelled'});
done();
}, function (err) {
changeCount.should.equal(5, 'changeCount');
should.exist(err);
done();
});
});
});
it('Changes Since Old Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
{_id: '8', integer: 9},
{_id: '9', integer: 9},
{_id: '10', integer: 10},
{_id: '11', integer: 11}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
var docs2 = [
{_id: '12', integer: 12},
{_id: '13', integer: 13}
];
db.bulkDocs({ docs: docs2 }, function (err, info) {
var promise = db.changes({
since: update_seq,
complete: function (err, results) {
results.results.length.should.be.at.least(2);
done();
}
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
});
});
it('Changes Since New Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
{_id: '8', integer: 9},
{_id: '9', integer: 9},
{_id: '10', integer: 10},
{_id: '11', integer: 11}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
var docs2 = [
{_id: '12', integer: 12},
{_id: '13', integer: 13}
];
db.bulkDocs({ docs: docs2 }, function (err, info) {
var promise = db.changes({
since: update_seq
}).on('complete', function (results) {
results.results.length.should.be.at.least(2);
done();
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
});
});
it('Changes Since and limit Old Style limit 1', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 1,
complete: function (err, results) {
results.results.length.should.equal(1);
done();
}
});
});
});
it('Changes Since and limit New Style limit 1', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 1
}).on('complete', function (results) {
results.results.length.should.equal(1);
done();
});
});
});
it('Changes Since and limit Old Style limit 0', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 0,
complete: function (err, results) {
results.results.length.should.equal(1);
done();
}
});
});
});
it('Changes Since and limit New Style limit 0', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
since: 2,
limit: 0
}).on('complete', function (results) {
results.results.length.should.equal(1);
done();
});
});
});
it('Changes limit Old Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
var db = new PouchDB(dbs.name);
// we use writeDocs since bulkDocs looks to have undefined
// order of doing insertions
testUtils.writeDocs(db, docs1, function (err, info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
db.put(docs2[0], function (err, info) {
db.put(docs2[1], function (err, info) {
db.changes({
limit: 2,
since: 2,
include_docs: true,
complete: function (err, results) {
results.last_seq.should.equal(6);
results = results.results;
results.length.should.equal(2);
results[0].id.should.equal('2');
results[0].seq.should.equal(5);
results[0].doc.integer.should.equal(11);
results[1].id.should.equal('3');
results[1].seq.should.equal(6);
results[1].doc.integer.should.equal(12);
done();
}
});
});
});
});
});
it('Changes limit New Style', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
var db = new PouchDB(dbs.name);
// we use writeDocs since bulkDocs looks to have undefined
// order of doing insertions
testUtils.writeDocs(db, docs1, function (err, info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
db.put(docs2[0], function (err, info) {
db.put(docs2[1], function (err, info) {
db.changes({
limit: 2,
since: 2,
include_docs: true
}).on('complete', function (results) {
results.last_seq.should.equal(6);
results = results.results;
results.length.should.equal(2);
results[0].id.should.equal('2');
results[0].seq.should.equal(5);
results[0].doc.integer.should.equal(11);
results[1].id.should.equal('3');
results[1].seq.should.equal(6);
results[1].doc.integer.should.equal(12);
done();
});
});
});
});
});
it('Changes with filter not present in ddoc', function (done) {
this.timeout(15000);
var docs = [
{_id: '1', integer: 1},
{ _id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: 'foo/odd',
limit: 2,
include_docs: true,
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: odd');
should.not.exist(results);
done();
}
});
});
});
it('Changes with `filters` key not present in ddoc', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
views: {
even: {
map: 'function (doc) { if (doc.integer % 2 === 1)' +
' { emit(doc._id, null) }; }'
}
}
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: 'foo/even',
limit: 2,
include_docs: true,
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: filters');
should.not.exist(results);
done();
}
});
});
});
it('Changes limit and filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2}
];
var db = new PouchDB(dbs.name);
var docs2 = [
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{
_id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.info(function (err, info) {
var update_seq = info.update_seq;
testUtils.writeDocs(db, docs2, function (err, info) {
var promise = db.changes({
filter: 'foo/even',
limit: 2,
since: update_seq,
include_docs: true,
complete: function (err, results) {
results.results.length.should.equal(2);
results.results[0].id.should.equal('3');
results.results[0].doc.integer.should.equal(3);
results.results[1].id.should.equal('5');
results.results[1].doc.integer.should.equal(5);
done();
}
});
should.exist(promise);
promise.cancel.should.be.a('function');
});
});
});
});
it('Changes with filter from nonexistent ddoc', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: 'foobar/odd',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
should.not.exist(results);
done();
}
});
});
});
it('Changes with view not present in ddoc', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
views:
{ even:
{ map: 'function (doc) { if (doc.integer % 2 === 1) { ' +
'emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
view: 'foo/odd',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: odd');
should.not.exist(results);
done();
}
});
});
});
it('Changes with `views` key not present in ddoc', function (done) {
var docs = [
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
view: 'foo/even',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.MISSING_DOC.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.MISSING_DOC.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should.equal('missing json key: views',
// 'correct error reason returned');
should.not.exist(results);
done();
}
});
});
});
it('Changes with missing param `view` in request', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{
_id: '_design/foo',
integer: 4,
views: { even: { map: 'function (doc) { if (doc.integer % 2 === 1) ' +
'{ emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
complete: function (err, results) {
err.status.should.equal(PouchDB.Errors.BAD_REQUEST.status,
'correct error status returned');
err.message.should.equal(PouchDB.Errors.BAD_REQUEST.message,
'correct error message returned');
// todo: does not work in pouchdb-server.
// err.reason.should
// .equal('`view` filter parameter is not provided.',
// 'correct error reason returned');
should.not.exist(results);
done();
}
});
});
});
it('Changes limit and view instead of filter', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{
_id: '_design/foo',
integer: 4,
views: { even: { map: 'function (doc) { if (doc.integer % 2 === 1) ' +
'{ emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
testUtils.writeDocs(db, docs, function (err, info) {
db.changes({
filter: '_view',
view: 'foo/even',
limit: 2,
since: 2,
include_docs: true,
complete: function (err, results) {
results.results.length.should.equal(2);
results.results[0].id.should.equal('3');
results.results[0].seq.should.equal(4);
results.results[0].doc.integer.should.equal(3);
results.results[1].id.should.equal('5');
results.results[1].seq.should.equal(6);
results.results[1].doc.integer.should.equal(5);
done();
}
});
});
});
it('Changes last_seq', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{
_id: '_design/foo',
integer: 4,
filters: { even: 'function (doc) { return doc.integer % 2 === 1; }' }
}
];
var db = new PouchDB(dbs.name);
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(0);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(5);
db.changes({
filter: 'foo/even',
complete: function (err, results) {
results.last_seq.should.equal(5);
results.results.length.should.equal(2);
done();
}
});
}
});
});
}
});
});
it('Changes last_seq with view instead of filter', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
{
_id: '_design/foo',
integer: 4,
views:
{ even:
{ map: 'function (doc) { if (doc.integer % 2 === 1) { ' +
'emit(doc._id, null) }; }' } }
}
];
var db = new PouchDB(dbs.name);
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(0);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
complete: function (err, results) {
results.last_seq.should.equal(5);
db.changes({
filter: '_view',
view: 'foo/even',
complete: function (err, results) {
results.last_seq.should.equal(5);
results.results.length.should.equal(2);
done();
}
});
}
});
});
}
});
});
it('Changes with style = all_docs', function (done) {
var simpleTree = [
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-b', value: 'foo b'},
{_id: 'foo', _rev: '3-c', value: 'foo c'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-d', value: 'foo d'},
{_id: 'foo', _rev: '3-e', value: 'foo e'},
{_id: 'foo', _rev: '4-f', value: 'foo f'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-g', value: 'foo g', _deleted: true}]
];
var db = new PouchDB(dbs.name);
testUtils.putTree(db, simpleTree, function () {
db.changes({
complete: function (err, res) {
res.results[0].changes.length.should.equal(1);
res.results[0].changes[0].rev.should.equal('4-f');
db.changes({
style: 'all_docs',
complete: function (err, res) {
res.results[0].changes.length.should.equal(3);
var changes = res.results[0].changes;
changes.sort(function (a, b) {
return a.rev < b.rev;
});
changes[0].rev.should.equal('4-f');
changes[1].rev.should.equal('3-c');
changes[2].rev.should.equal('2-g');
done();
}
});
}
});
});
});
it('Changes with style = all_docs and a callback for complete',
function (done) {
var simpleTree = [
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-b', value: 'foo b'},
{_id: 'foo', _rev: '3-c', value: 'foo c'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-d', value: 'foo d'},
{_id: 'foo', _rev: '3-e', value: 'foo e'},
{_id: 'foo', _rev: '4-f', value: 'foo f'}],
[{_id: 'foo', _rev: '1-a', value: 'foo a'},
{_id: 'foo', _rev: '2-g', value: 'foo g', _deleted: true}]
];
var db = new PouchDB(dbs.name);
testUtils.putTree(db, simpleTree, function () {
db.changes(function (err, res) {
res.results[0].changes.length.should.equal(1);
res.results[0].changes[0].rev.should.equal('4-f');
db.changes({
style: 'all_docs',
complete: function () {
done(new Error('this should never be called'));
}
}, function (err, res) {
res.results[0].changes.length.should.equal(3);
var changes = res.results[0].changes;
changes.sort(function (a, b) {
return a.rev < b.rev;
});
changes[0].rev.should.equal('4-f');
changes[1].rev.should.equal('3-c');
changes[2].rev.should.equal('2-g');
done();
});
});
});
});
it('Changes limit = 0', function (done) {
var docs = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
limit: 0,
complete: function (err, results) {
results.results.length.should.equal(1);
done();
}
});
});
});
// Note for the following test that CouchDB's implementation of /_changes
// with `descending=true` ignores any `since` parameter.
it('Descending changes', function (done) {
var db = new PouchDB(dbs.name);
db.post({_id: '0', test: 'ing'}, function (err, res) {
db.post({_id: '1', test: 'ing'}, function (err, res) {
db.post({_id: '2', test: 'ing'}, function (err, res) {
db.changes({
descending: true,
since: 1,
complete: function (err, results) {
results.results.length.should.equal(3);
var ids = ['2', '1', '0'];
results.results.forEach(function (row, i) {
row.id.should.equal(ids[i]);
});
done();
}
});
});
});
});
});
it('Changes doc Old Style', function (done) {
var db = new PouchDB(dbs.name);
db.post({ test: 'somestuff' }, function (err, info) {
db.changes({
include_docs: true,
onChange: function (change) {
change.doc._id.should.equal(change.id);
change.doc._rev.should
.equal(change.changes[change.changes.length - 1].rev);
done();
}
});
});
});
it('Changes doc New Style', function (done) {
var db = new PouchDB(dbs.name);
db.post({ test: 'somestuff' }, function (err, info) {
db.changes({
include_docs: true
}).on('change', function (change) {
change.doc._id.should.equal(change.id);
change.doc._rev.should
.equal(change.changes[change.changes.length - 1].rev);
done();
});
});
});
// Note for the following test that CouchDB's implementation of /_changes
// with `descending=true` ignores any `since` parameter.
it('Descending many changes Old Style', function (done) {
var db = new PouchDB(dbs.name);
var docs = [];
var num = 100;
for (var i = 0; i < num; i++) {
docs.push({
_id: 'doc_' + i,
foo: 'bar_' + i
});
}
var changes = 0;
db.bulkDocs({ docs: docs }, function (err, info) {
if (err) {
return done(err);
}
db.changes({
descending: true,
onChange: function (change) {
changes++;
},
complete: function (err, results) {
if (err) {
return done(err);
}
changes.should.equal(num, 'correct number of changes');
done();
}
});
});
});
it('Descending many changes New Style', function (done) {
var db = new PouchDB(dbs.name);
var docs = [];
var num = 100;
for (var i = 0; i < num; i++) {
docs.push({
_id: 'doc_' + i,
foo: 'bar_' + i
});
}
var changes = 0;
db.bulkDocs({ docs: docs }, function (err, info) {
if (err) {
return done(err);
}
db.changes({
descending: true
}).on('change', function (change) {
changes++;
}).on('complete', function (results) {
changes.should.equal(num, 'correct number of changes');
done();
}).on('error', function (err) {
done(err);
});
});
});
it('live-changes Old Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes = db.changes({
live: true,
complete: function () {
count.should.equal(1);
done();
},
onChange: function (change) {
count += 1;
change.should.not.have.property('doc');
count.should.equal(1);
changes.cancel();
},
});
db.post({ test: 'adoc' });
});
it('live-changes New Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes = db.changes({
live: true
}).on('complete', function () {
count.should.equal(1);
done();
}).on('change', function (change) {
count += 1;
change.should.not.have.property('doc');
count.should.equal(1);
changes.cancel();
});
db.post({ test: 'adoc' });
});
it('Multiple watchers Old Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes1Complete = false;
var changes2Complete = false;
function checkCount() {
if (changes1Complete && changes2Complete) {
count.should.equal(2);
done();
}
}
var changes1 = db.changes({
complete: function () {
changes1Complete = true;
checkCount();
},
onChange: function (change) {
count += 1;
changes1.cancel();
changes1 = null;
},
live: true
});
var changes2 = db.changes({
complete: function () {
changes2Complete = true;
checkCount();
},
onChange: function (change) {
count += 1;
changes2.cancel();
changes2 = null;
},
live: true
});
db.post({test: 'adoc'});
});
it('Multiple watchers New Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var changes1Complete = false;
var changes2Complete = false;
function checkCount() {
if (changes1Complete && changes2Complete) {
count.should.equal(2);
done();
}
}
var changes1 = db.changes({
live: true
}).on('complete', function () {
changes1Complete = true;
checkCount();
}).on('change', function (change) {
count += 1;
changes1.cancel();
changes1 = null;
});
var changes2 = db.changes({
live: true
}).on('complete', function () {
changes2Complete = true;
checkCount();
}).on('change', function (change) {
count += 1;
changes2.cancel();
changes2 = null;
});
db.post({test: 'adoc'});
});
it('Continuous changes doc', function (done) {
var db = new PouchDB(dbs.name);
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
onChange: function (change) {
change.should.have.property('doc');
change.doc.should.have.property('_rev');
changes.cancel();
},
live: true,
include_docs: true
});
db.post({ test: 'adoc' });
});
it('Cancel changes Old Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var interval;
var docPosted = false;
// We want to wait for a period of time after the final
// document was posted to ensure we didnt see another
// change
function waitForDocPosted() {
if (!docPosted) {
return;
}
clearInterval(interval);
setTimeout(function () {
count.should.equal(1);
done();
}, 200);
}
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
// This setTimeout ensures that once we cancel a change we dont
// recieve subsequent callbacks, so it is needed
interval = setInterval(waitForDocPosted, 100);
},
onChange: function (change) {
count += 1;
if (count === 1) {
changes.cancel();
db.post({ test: 'another doc' }, function (err, res) {
if (err) {
return done(err);
}
docPosted = true;
});
}
},
live: true
});
db.post({ test: 'adoc' });
});
it('Cancel changes New Style', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
var interval;
var docPosted = false;
// We want to wait for a period of time after the final
// document was posted to ensure we didnt see another
// change
function waitForDocPosted() {
if (!docPosted) {
return;
}
clearInterval(interval);
setTimeout(function () {
count.should.equal(1);
done();
}, 200);
}
var changes = db.changes({
live: true
}).on('complete', function (result) {
result.status.should.equal('cancelled');
// This setTimeout ensures that once we cancel a change we dont recieve
// subsequent callbacks, so it is needed
interval = setInterval(waitForDocPosted, 100);
}).on('change', function (change) {
count += 1;
if (count === 1) {
changes.cancel();
db.post({ test: 'another doc' }, function (err, res) {
if (err) {
return done(err);
}
docPosted = true;
});
}
});
db.post({ test: 'adoc' });
});
// TODO: https://github.com/daleharvey/pouchdb/issues/1460
it('Kill database while listening to live changes', function (done) {
var db = new PouchDB(dbs.name);
var count = 0;
db.changes({
complete: function (err, result) {
done();
},
onChange: function (change) {
count++;
if (count === 1) {
PouchDB.destroy(dbs.name);
}
},
live: true
});
db.post({ test: 'adoc' });
});
it('#3136 style=all_docs, right order', function () {
var db = new PouchDB(dbs.name);
var chain = PouchDB.utils.Promise.resolve();
var docIds = ['b', 'c', 'a', 'z', 'd', 'e'];
docIds.forEach(function (docId) {
chain = chain.then(function () {
return db.put({_id: docId});
});
});
return chain.then(function () {
return db.changes({style: 'all_docs'});
}).then(function (res) {
var ids = res.results.map(function (x) {
return x.id;
});
ids.should.deep.equal(docIds);
});
});
it('#3136 style=all_docs & include_docs, right order', function () {
var db = new PouchDB(dbs.name);
var chain = PouchDB.utils.Promise.resolve();
var docIds = ['b', 'c', 'a', 'z', 'd', 'e'];
docIds.forEach(function (docId) {
chain = chain.then(function () {
return db.put({_id: docId});
});
});
return chain.then(function () {
return db.changes({
style: 'all_docs',
include_docs: true
});
}).then(function (res) {
var ids = res.results.map(function (x) {
return x.id;
});
ids.should.deep.equal(docIds);
});
});
it('#3136 tricky changes, limit/descending', function () {
var db = new PouchDB(dbs.name);
var docs = [
{
_id: 'alpha',
_rev: '1-a',
_revisions: {
start: 1,
ids: ['a']
}
}, {
_id: 'beta',
_rev: '1-b',
_revisions: {
start: 1,
ids: ['b']
}
}, {
_id: 'gamma',
_rev: '1-b',
_revisions: {
start: 1,
ids: ['b']
}
}, {
_id: 'alpha',
_rev: '2-d',
_revisions: {
start: 2,
ids: ['d', 'a']
}
}, {
_id: 'beta',
_rev: '2-e',
_revisions: {
start: 2,
ids: ['e', 'b']
}
}, {
_id: 'beta',
_rev: '3-f',
_deleted: true,
_revisions: {
start: 3,
ids: ['f', 'e', 'b']
}
}
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [];
docs.forEach(function (doc) {
chain = chain.then(function () {
return db.bulkDocs([doc], {new_edits: false}).then(function () {
return db.changes({doc_ids: [doc._id]});
}).then(function (res) {
seqs.push(res.results[0].seq);
});
});
});
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
return chain.then(function () {
return db.changes();
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [
{
"seq": seqs[2],
"id": "gamma",
"changes": [{ "rev": "1-b"}
]
},
{
"seq": seqs[3],
"id": "alpha",
"changes": [{ "rev": "2-d"}
]
},
{
"seq": seqs[5],
"id": "beta",
"deleted": true,
"changes": [{ "rev": "3-f"}
]
}
]
//, "last_seq": seqs[5]
});
return db.changes({limit: 0});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}]
//, "last_seq": seqs[2]
}, '1:' + JSON.stringify(result));
return db.changes({limit: 1});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}]
//, "last_seq": seqs[2]
}, '2:' + JSON.stringify(result));
return db.changes({limit: 2});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}, {"seq": seqs[3], "id": "alpha", "changes": [{"rev": "2-d"}]}]
//, last_seq": seqs[3]
}, '3:' + JSON.stringify(result));
return db.changes({limit: 1, descending: true});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
result.should.deep.equal({
"results": [{
"seq": seqs[5],
"id": "beta",
"changes": [{"rev": "3-f"}],
"deleted": true
}]
//, "last_seq": seqs[5]
}, '4:' + JSON.stringify(result));
return db.changes({limit: 2, descending: true});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
var expected = {
"results": [{
"seq": seqs[5],
"id": "beta",
"changes": [{"rev": "3-f"}],
"deleted": true
}, {"seq": seqs[3], "id": "alpha", "changes": [{"rev": "2-d"}]}]
//, "last_seq": seqs[3]
};
result.should.deep.equal(expected, '5:' + JSON.stringify(result) +
', shoulda got: ' + JSON.stringify(expected));
return db.changes({descending: true});
}).then(function (result) {
normalizeResult(result);
delete result.last_seq;
var expected = {
"results": [{
"seq": seqs[5],
"id": "beta",
"changes": [{"rev": "3-f"}],
"deleted": true
}, {"seq": seqs[3], "id": "alpha", "changes": [{"rev": "2-d"}]}, {
"seq": seqs[2],
"id": "gamma",
"changes": [{"rev": "1-b"}]
}]
//, "last_seq": seqs[2]
};
result.should.deep.equal(expected, '6:' + JSON.stringify(result) +
', shoulda got: ' + JSON.stringify(expected));
});
});
it('#3136 winningRev has a lower seq, style=all_docs', function () {
var db = new PouchDB(dbs.name);
var tree = [
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-e',
_deleted: true,
_revisions: {start: 2, ids: ['e', 'a']}
},
{
_id: 'foo',
_rev: '3-g',
_revisions: {start: 3, ids: ['g', 'e', 'a']}
}
],
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-b',
_revisions: {start: 2, ids: ['b', 'a']}
},
{
_id: 'foo',
_rev: '3-c',
_revisions: {start: 3, ids: ['c', 'b', 'a']}
}
],
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-d',
_revisions: {start: 2, ids: ['d', 'a']}
},
{
_id: 'foo',
_rev: '3-h',
_revisions: {start: 3, ids: ['h', 'd', 'a']}
},
{
_id: 'foo',
_rev: '4-f',
_revisions: {start: 4, ids: ['f', 'h', 'd', 'a']}
}
]
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [0];
function getExpected(i) {
var expecteds = [
{
"results": [
{
"seq": seqs[1],
"id": "foo",
"changes": [{"rev": "3-g"}],
"doc": {"_id": "foo", "_rev": "3-g"}
}
],
"last_seq" : seqs[1]
},
{
"results": [
{
"seq": seqs[2],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}],
"doc": {"_id": "foo", "_rev": "3-g"}
}
],
"last_seq" : seqs[2]
},
{
"results": [
{
"seq": seqs[3],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}, {"rev": "4-f"}],
"doc": {"_id": "foo", "_rev": "4-f"}
}
],
"last_seq" : seqs[3]
}
];
return expecteds[i];
}
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
tree.forEach(function (docs, i) {
chain = chain.then(function () {
return db.bulkDocs(docs, {new_edits: false}).then(function () {
return db.changes({
style: 'all_docs',
since: seqs[seqs.length - 1],
include_docs: true
});
}).then(function (result) {
seqs.push(result.last_seq);
var expected = getExpected(i);
normalizeResult(result);
result.should.deep.equal(expected,
i + ': should get: ' + JSON.stringify(expected) +
', but got: ' + JSON.stringify(result));
});
});
});
return chain;
});
it('#3136 winningRev has a lower seq, style=all_docs 2', function () {
var db = new PouchDB(dbs.name);
var tree = [
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-e',
_deleted: true,
_revisions: {start: 2, ids: ['e', 'a']}
},
{
_id: 'foo',
_rev: '3-g',
_revisions: {start: 3, ids: ['g', 'e', 'a']}
}
], [
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
},
{
_id: 'foo',
_rev: '2-b',
_revisions: {start: 2, ids: ['b', 'a']}
},
{
_id: 'foo',
_rev: '3-c',
_revisions: {start: 3, ids: ['c', 'b', 'a']}
},
], [
{
_id: 'bar',
_rev: '1-z',
_revisions: {start: 1, ids: ['z']}
}
]
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [0];
tree.forEach(function (docs, i) {
chain = chain.then(function () {
return db.bulkDocs(docs, {new_edits: false}).then(function () {
return db.changes();
}).then(function (result) {
seqs.push(result.last_seq);
});
});
});
return chain.then(function () {
var expecteds = [
{
"results": [{
"seq": seqs[2],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}]
}, {"seq": seqs[3], "id": "bar", "changes": [{"rev": "1-z"}]}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[2],
"id": "foo",
"changes": [{"rev": "3-c"}, {"rev": "3-g"}]
}, {"seq": seqs[3], "id": "bar", "changes": [{"rev": "1-z"}]}],
"last_seq": seqs[3]
},
{
"results": [{"seq": seqs[3], "id": "bar",
"changes": [{"rev": "1-z"}]}],
"last_seq": seqs[3]
},
{"results": [], "last_seq": seqs[3]}
];
var chain2 = PouchDB.utils.Promise.resolve();
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
seqs.forEach(function (seq, i) {
chain2 = chain2.then(function () {
return db.changes({
since: seq,
style: 'all_docs'
}).then(function (res) {
normalizeResult(res);
res.should.deep.equal(expecteds[i], 'since=' + seq +
': got: ' +
JSON.stringify(res) +
', shoulda got: ' +
JSON.stringify(expecteds[i]));
});
});
});
return chain2;
});
});
it('#3136 winningRev has a higher seq, using limit', function () {
var db = new PouchDB(dbs.name);
var tree = [
[
{
_id: 'foo',
_rev: '1-a',
_revisions: {start: 1, ids: ['a']}
}
], [
{
_id: 'foo',
_rev: '2-b',
_revisions: {start: 2, ids: ['b', 'a']}
}
], [
{
_id: 'bar',
_rev: '1-x',
_revisions: {start: 1, ids: ['x']}
}
], [
{
_id: 'foo',
_rev: '2-c',
_deleted: true,
_revisions: {start: 2, ids: ['c', 'a']}
},
]
];
var chain = PouchDB.utils.Promise.resolve();
var seqs = [0];
tree.forEach(function (docs, i) {
chain = chain.then(function () {
return db.bulkDocs(docs, {new_edits: false}).then(function () {
return db.changes().then(function (result) {
seqs.push(result.last_seq);
});
});
});
});
return chain.then(function () {
var expecteds = [{
"results": [{
"seq": seqs[3],
"id": "bar",
"changes": [{"rev": "1-x"}],
"doc": {"_id": "bar", "_rev": "1-x"}
}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[3],
"id": "bar",
"changes": [{"rev": "1-x"}],
"doc": {"_id": "bar", "_rev": "1-x"}
}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[3],
"id": "bar",
"changes": [{"rev": "1-x"}],
"doc": {"_id": "bar", "_rev": "1-x"}
}],
"last_seq": seqs[3]
},
{
"results": [{
"seq": seqs[4],
"id": "foo",
"changes": [{"rev": "2-b"}, {"rev": "2-c"}],
"doc": {"_id": "foo", "_rev": "2-b"}
}],
"last_seq": seqs[4]
},
{"results": [], "last_seq": seqs[4]}
];
var chain2 = PouchDB.utils.Promise.resolve();
function normalizeResult(result) {
// order of changes doesn't matter
result.results.forEach(function (ch) {
ch.changes = ch.changes.sort(function (a, b) {
return a.rev < b.rev ? -1 : 1;
});
});
}
seqs.forEach(function (seq, i) {
chain2 = chain2.then(function () {
return db.changes({
style: 'all_docs',
since: seq,
limit: 1,
include_docs: true
});
}).then(function (result) {
normalizeResult(result);
result.should.deep.equal(expecteds[i],
i + ': got: ' + JSON.stringify(result) +
', shoulda got: ' + JSON.stringify(expecteds[i]));
});
});
return chain2;
});
});
it('changes-filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
];
var db = new PouchDB(dbs.name);
var count = 0;
db.bulkDocs({ docs: docs1 }, function (err, info) {
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
filter: function (doc) {
return doc.integer % 2 === 0;
},
onChange: function (change) {
count += 1;
if (count === 4) {
changes.cancel();
}
},
live: true
});
db.bulkDocs({ docs: docs2 });
});
});
it('changes-filter with query params', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
];
var params = { 'abc': true };
var db = new PouchDB(dbs.name);
var count = 0;
db.bulkDocs({ docs: docs1 }, function (err, info) {
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
filter: function (doc, req) {
if (req.query.abc) {
return doc.integer % 2 === 0;
}
},
query_params: params,
onChange: function (change) {
count += 1;
if (count === 4) {
changes.cancel();
}
},
live: true
});
db.bulkDocs({ docs: docs2 });
});
});
it('Non-live changes filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.changes({
filter: function (doc) {
return doc.integer % 2 === 0;
},
complete: function (err, changes) {
// Should get docs 0 and 2 if the filter has been applied correctly.
changes.results.length.should.equal(2);
done();
}
});
});
});
it('#2569 Non-live doc_ids filter', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
doc_ids: ['1', '3']
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
ids.sort().should.deep.equal(['1', '3']);
});
});
it('#2569 Big non-live doc_ids filter', function () {
var docs = [];
for (var i = 0; i < 5; i++) {
var id = '';
for (var j = 0; j < 50; j++) {
// make a huge id
id += PouchDB.utils.btoa(Math.random().toString());
}
docs.push({_id: id});
}
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
doc_ids: [docs[1]._id, docs[3]._id]
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
var expectedIds = [docs[1]._id, docs[3]._id];
ids.sort().should.deep.equal(expectedIds.sort());
});
});
it('#2569 Live doc_ids filter', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return new PouchDB.utils.Promise(function (resolve, reject) {
var retChanges = [];
var changes = db.changes({
doc_ids: ['1', '3'],
live: true
}).on('change', function (change) {
retChanges.push(change);
if (retChanges.length === 2) {
changes.cancel();
resolve(retChanges);
}
}).on('error', reject);
});
}).then(function (changes) {
var ids = changes.map(function (x) {
return x.id;
});
var expectedIds = ['1', '3'];
ids.sort().should.deep.equal(expectedIds);
});
});
it('#2569 Big live doc_ids filter', function () {
var docs = [];
for (var i = 0; i < 5; i++) {
var id = '';
for (var j = 0; j < 50; j++) {
// make a huge id
id += PouchDB.utils.btoa(Math.random().toString());
}
docs.push({_id: id});
}
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return new PouchDB.utils.Promise(function (resolve, reject) {
var retChanges = [];
var changes = db.changes({
doc_ids: [docs[1]._id, docs[3]._id],
live: true
}).on('change', function (change) {
retChanges.push(change);
if (retChanges.length === 2) {
changes.cancel();
resolve(retChanges);
}
}).on('error', reject);
});
}).then(function (changes) {
var ids = changes.map(function (x) {
return x.id;
});
var expectedIds = [docs[1]._id, docs[3]._id];
ids.sort().should.deep.equal(expectedIds.sort());
});
});
it('#2569 Non-live doc_ids filter with filter=_doc_ids', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
filter: '_doc_ids',
doc_ids: ['1', '3']
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
ids.sort().should.deep.equal(['1', '3']);
});
});
it('#2569 Live doc_ids filter with filter=_doc_ids', function () {
var docs = [
{_id: '0'},
{_id: '1'},
{_id: '2'},
{_id: '3'}
];
var db = new PouchDB(dbs.name);
return db.bulkDocs(docs).then(function () {
return db.changes({
filter: '_doc_ids',
doc_ids: ['1', '3']
});
}).then(function (changes) {
var ids = changes.results.map(function (x) {
return x.id;
});
ids.sort().should.deep.equal(['1', '3']);
});
});
it('Changes to same doc are grouped', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
db.put(docs2[0], function (err, info) {
db.put(docs2[1], function (err, info) {
db.changes({
include_docs: true,
complete: function (err, changes) {
changes.results.length.should.equal(4);
changes.results[2].seq.should.equal(5);
changes.results[2].id.should.equal('2');
changes.results[2].changes.length.should.equal(1);
changes.results[2].doc.integer.should.equal(11);
done();
}
});
});
});
});
});
it('Changes with conflicts are handled correctly', function (testDone) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '2', integer: 11},
{_id: '3', integer: 12},
];
new PouchDB(dbs.name).then(function (localdb) {
var remotedb = new PouchDB(dbs.remote);
return localdb.bulkDocs({ docs: docs1 }).then(function (info) {
docs2[0]._rev = info[2].rev;
docs2[1]._rev = info[3].rev;
return localdb.put(docs2[0]).then(function (info) {
return localdb.put(docs2[1]).then(function (info) {
var rev2 = info.rev;
return PouchDB.replicate(localdb, remotedb).then(function (done) {
// update remote once, local twice, then replicate from
// remote to local so the remote losing conflict is later in
// the tree
return localdb.put({
_id: '3',
_rev: rev2,
integer: 20
}).then(function (resp) {
var rev3Doc = {
_id: '3',
_rev: resp.rev,
integer: 30
};
return localdb.put(rev3Doc).then(function (resp) {
var rev4local = resp.rev;
var rev4Doc = {
_id: '3',
_rev: rev2,
integer: 100
};
return remotedb.put(rev4Doc).then(function (resp) {
var remoterev = resp.rev;
return PouchDB.replicate(remotedb, localdb).then(
function (done) {
return localdb.changes({
include_docs: true,
style: 'all_docs',
conflicts: true
}).on('error', testDone)
.then(function (changes) {
changes.results.length.should.equal(4);
var ch = changes.results[3];
ch.id.should.equal('3');
ch.changes.length.should.equal(2);
ch.doc.integer.should.equal(30);
ch.doc._rev.should.equal(rev4local);
ch.changes.should.deep.equal([
{ rev: rev4local },
{ rev: remoterev }
]);
ch.doc.should.have.property('_conflicts');
ch.doc._conflicts.length.should.equal(1);
ch.doc._conflicts[0].should.equal(remoterev);
});
});
});
});
});
});
});
});
}).then(function () {
testDone();
}, testDone);
});
});
it('Change entry for a deleted doc', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3}
];
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
var rev = info[3].rev;
db.remove({
_id: '3',
_rev: rev
}, function (err, info) {
db.changes({
include_docs: true,
complete: function (err, changes) {
changes.results.length.should.equal(4);
var ch = changes.results[3];
ch.id.should.equal('3');
ch.seq.should.equal(5);
ch.deleted.should.equal(true);
done();
}
});
});
});
});
it('changes large number of docs', function (done) {
var docs = [];
var num = 30;
for (var i = 0; i < num; i++) {
docs.push({
_id: 'doc_' + i,
foo: 'bar_' + i
});
}
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs }, function (err, info) {
db.changes({
complete: function (err, res) {
res.results.length.should.equal(num);
done();
}
});
});
});
it('Calling db.changes({since: \'now\'})', function (done) {
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: [{ foo: 'bar' }] }, function (err, data) {
db.info(function (err, info) {
var api = db.changes({
since: 'now',
complete: function (err, res) {
should.not.exist(err);
res.last_seq.should.equal(info.update_seq);
done();
}
});
api.should.be.an('object');
api.cancel.should.be.an('function');
});
});
});
//Duplicate to make sure both api options work.
it('Calling db.changes({since: \'latest\'})', function (done) {
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: [{ foo: 'bar' }] }, function (err, data) {
db.info(function (err, info) {
var api = db.changes({
since: 'latest',
complete: function (err, res) {
should.not.exist(err);
res.last_seq.should.equal(info.update_seq);
done();
}
});
api.should.be.an('object');
api.cancel.should.be.an('function');
});
});
});
it('Closing db does not cause a crash if changes cancelled',
function (done) {
var db = new PouchDB(dbs.name);
var called = 0;
function checkDone() {
called++;
if (called === 2) {
done();
}
}
db.bulkDocs({ docs: [{ foo: 'bar' }] }, function (err, data) {
var changes = db.changes({
live: true,
onChange: function () { },
complete: function (err, result) {
result.status.should.equal('cancelled');
checkDone();
}
});
should.exist(changes);
changes.cancel.should.be.a('function');
changes.cancel();
db.close(function (error) {
should.not.exist(error);
checkDone();
});
});
});
it('fire-complete-on-cancel', function (done) {
var db = new PouchDB(dbs.name);
var cancelled = false;
var changes = db.changes({
live: true,
complete: function (err, result) {
cancelled.should.equal(true);
should.not.exist(err);
should.exist(result);
if (result) {
result.status.should.equal('cancelled');
}
done();
}
});
should.exist(changes);
changes.cancel.should.be.a('function');
setTimeout(function () {
cancelled = true;
changes.cancel();
}, 100);
});
it('changes are not duplicated', function (done) {
var db = new PouchDB(dbs.name);
var called = 0;
var changes = db.changes({
live: true,
onChange: function () {
called++;
if (called === 1) {
setTimeout(function () {
changes.cancel();
}, 1000);
}
},
complete: function (err) {
called.should.equal(1);
done();
}
});
db.post({key: 'value'});
});
function waitASec(fun, time) {
return new PouchDB.utils.Promise(function (fulfill) {
setTimeout(function () {
fulfill(fun());
}, time);
});
}
it('CRUD events are handled correclty', function (done) {
var db = new PouchDB(dbs.name);
var changes = db.changes({
live: true,
style: 'all_docs'
});
var deleted = 0;
var updated = 0;
var created = 0;
function chuckDone() {
if ((deleted + updated + created) === 6) {
changes.cancel();
}
}
changes.on('cancel', function () {
setTimeout(function () {
deleted.should.equal(1, 'correct number of deleted');
created.should.equal(2, 'create number of created');
updated.should.equal(3, 'correct number of updates');
done();
}, 100);
}).on('delete', function (change) {
deleted++;
chuckDone();
}).on('create', function (change) {
created++;
chuckDone();
}).on('update', function (change) {
updated++;
chuckDone();
}).on('error', function (err) {
done(err);
});
var rev1, rev2;
db.put({
title: 'Holding On For Life'
}, 'currentSong').then(function (resp) {
rev1 = resp.rev;
return waitASec(function () {
return db.put({
title: 'Sushi'
}, 'nextSong');
}, 100);
}).then(function (resp) {
rev2 = resp.rev;
return waitASec(function () {
return db.put({
title: 'Holding On For Life',
artist: 'Broken Bells'
}, 'currentSong', rev1);
}, 100);
}).then(function (resp) {
rev1 = resp.rev;
return waitASec(function () {
return db.put({
title: 'Sushi',
artist: 'Kyle Andrews'
}, 'nextSong', rev2);
}, 100);
}).then(function (resp) {
rev2 = resp.rev;
return waitASec(function () {
return db.remove({
_id: 'currentSong',
_rev: rev1
});
}, 100);
}).then(function (resp) {
return db.put({
title: 'Sushi',
artist: 'Kyle Andrews',
album: 'Real Blasty'
}, 'nextSong', rev2);
});
});
it('supports returnDocs=false', function (done) {
var db = new PouchDB(dbs.name);
var docs = [];
var num = 10;
for (var i = 0; i < num; i++) {
docs.push({ _id: 'doc_' + i, });
}
var changes = 0;
db.bulkDocs({ docs: docs }, function (err, info) {
if (err) {
return done(err);
}
db.changes({
descending: true,
returnDocs : false
}).on('change', function (change) {
changes++;
}).on('complete', function (results) {
results.results.should.have.length(0, '0 results returned');
changes.should.equal(num, 'correct number of changes');
done();
}).on('error', function (err) {
done(err);
});
});
});
it('should respects limit', function (done) {
var docs1 = [
{_id: '_local/foo'},
{_id: 'a', integer: 0},
{_id: 'b', integer: 1},
{_id: 'c', integer: 2},
{_id: 'd', integer: 3}
];
var called = 0;
var db = new PouchDB(dbs.name);
db.bulkDocs({ docs: docs1 }, function (err, info) {
db.changes({
limit: 1
}).on('change', function (ch) {
(called++).should.equal(0);
}).on('complete', function () {
setTimeout(function () {
done();
}, 50);
});
});
});
it.skip('should respects limit with live replication', function (done) {
var docs1 = [
{_id: '_local/foo'},
{_id: 'a', integer: 0},
{_id: 'b', integer: 1},
{_id: 'c', integer: 2},
{_id: 'd', integer: 3}
];
var called = 0;
var doneCalled = 0;
function calldone() {
doneCalled++;
if (doneCalled === 2) {
done();
}
}
var db = new PouchDB(dbs.name);
db.changes({
limit: 1,
live: true
}).on('change', function (ch) {
ch.id.should.equal('a');
(called++).should.equal(0);
}).on('complete', function () {
calldone();
});
db.bulkDocs({ docs: docs1 }).then(calldone);
});
it('doesn\'t throw if opts.complete is undefined', function (done) {
var db = new PouchDB(dbs.name);
db.put({_id: 'foo'}).then(function () {
db.changes().on('change', function () {
done();
}).on('error', function (err) {
done(err);
});
}, done);
});
it('it handles a bunch of individual changes in live replication',
function (done) {
var db = new PouchDB(dbs.name);
var len = 80;
var called = 0;
var changesDone = false;
var changesWritten = 0;
var changes = db.changes({live: true});
changes.on('change', function () {
called++;
if (called === len) {
changes.cancel();
}
}).on('error', done).on('complete', function () {
changesDone = true;
maybeDone();
});
var i = -1;
function maybeDone() {
if (changesDone && changesWritten === len) {
done();
}
}
function after() {
changesWritten++;
db.listeners('destroyed').should.have.length.lessThan(5);
maybeDone();
}
while (++i < len) {
db.post({}).then(after).catch(done);
}
});
it('changes-filter without filter', function (done) {
var docs1 = [
{_id: '0', integer: 0},
{_id: '1', integer: 1},
{_id: '2', integer: 2},
{_id: '3', integer: 3},
];
var docs2 = [
{_id: '4', integer: 4},
{_id: '5', integer: 5},
{_id: '6', integer: 6},
{_id: '7', integer: 7},
];
var db = new PouchDB(dbs.name);
var count = 0;
db.bulkDocs({ docs: docs1 }, function (err, info) {
var changes = db.changes({
complete: function (err, result) {
result.status.should.equal('cancelled');
done();
},
onChange: function (change) {
count += 1;
if (count === 8) {
changes.cancel();
}
},
live: true
});
db.bulkDocs({ docs: docs2 });
});
});
});
});
describe('changes-standalone', function () {
it('Changes reports errors', function (done) {
this.timeout(2000);
var db = new PouchDB('http://infiniterequest.com', { skipSetup: true });
db.changes({
timeout: 1000,
complete: function (err, changes) {
should.exist(err);
done();
}
});
});
});
| (#136) - Fix "changes since and limit old style" against CouchDB 2.0
Similar to previous fixes, we cannot assume incremental sequence numbers
in CouchDB 2.0, so ask the server for a valid sequence number and use that
as the since parameter.
| tests/integration/test.changes.js | (#136) - Fix "changes since and limit old style" against CouchDB 2.0 | <ide><path>ests/integration/test.changes.js
<ide> });
<ide> });
<ide>
<del> it('Changes Since and limit Old Style limit 1', function (done) {
<del> var docs = [
<add> it('Changes Since and limit Old Style liimt 1', function (done) {
<add> var docs1 = [
<ide> {_id: '0', integer: 0},
<ide> {_id: '1', integer: 1},
<del> {_id: '2', integer: 2},
<del> {_id: '3', integer: 3},
<del> ];
<del> var db = new PouchDB(dbs.name);
<del> db.bulkDocs({ docs: docs }, function (err, info) {
<del> db.changes({
<del> since: 2,
<del> limit: 1,
<del> complete: function (err, results) {
<del> results.results.length.should.equal(1);
<del> done();
<del> }
<add> {_id: '2', integer: 2}
<add> ];
<add> var db = new PouchDB(dbs.name);
<add> db.bulkDocs({ docs: docs1 }, function (err, info) {
<add> db.info(function (err, info) {
<add> var update_seq = info.update_seq;
<add>
<add> var docs2 = [
<add> {_id: '3', integer: 3},
<add> {_id: '4', integer: 4}
<add> ];
<add>
<add> db.bulkDocs({ docs: docs2 }, function (err, info) {
<add> db.changes({
<add> since: update_seq,
<add> limit: 1,
<add> complete: function (err, results) {
<add> results.results.length.should.equal(1);
<add> done();
<add> }
<add> });
<add> });
<ide> });
<ide> });
<ide> }); |
|
Java | apache-2.0 | c04f6c00a5d20a2ca91db5eb91fe2fbc9c69b60f | 0 | adiguzel/Shopr,UweTrottmann/Shopr |
package com.uwetrottmann.shopr.algorithm.model;
/**
* Holds a list of possible attributes of an item.
*/
public class Attributes {
public interface Attribute {
public String id();
public AttributeValue currentValue();
public double[] getValueWeights();
public String getValueWeightsString();
public String getReasonString();
}
public interface AttributeValue {
/**
* Returns the index of this value in the weights vector of the
* attribute.
*/
public int index();
/**
* Returns a {@link String} representation suitable for end-user
* representation.
*/
public String descriptor();
}
private ClothingType type;
private Color color;
private Label label;
public Attribute[] getAllAttributes() {
Attribute[] attrs = new Attribute[3];
attrs[0] = type();
attrs[1] = color();
attrs[2] = label();
return attrs;
}
public String getAllAttributesString() {
StringBuilder attrsStr = new StringBuilder("");
Attribute[] allAttributes = getAllAttributes();
for (int i = 0; i < allAttributes.length; i++) {
if (allAttributes[i] != null) {
attrsStr.append(allAttributes[i].getValueWeightsString());
} else {
attrsStr.append("[not set]");
}
if (i != allAttributes.length - 1) {
attrsStr.append(" ");
}
}
return attrsStr.toString();
}
/**
* Returns a string describing this query for an end-user, e.g.
* "no Red, mainly Blue, no Armani".
*/
public String getReasonString() {
StringBuilder reason = new StringBuilder();
Attribute[] allAttributes = getAllAttributes();
for (int i = 0; i < allAttributes.length; i++) {
if (allAttributes[i] == null) {
continue;
}
Attribute attribute = allAttributes[i];
String attrString = attribute.getReasonString();
if (attrString != null && attrString.length() != 0) {
if (reason.length() != 0) {
reason.append(", ");
}
reason.append(attrString);
}
}
return reason.toString();
}
public Color color() {
return color;
}
public Attributes color(Color color) {
this.color = color;
return this;
}
public ClothingType type() {
return type;
}
public Attributes type(ClothingType type) {
this.type = type;
return this;
}
public Label label() {
return label;
}
public Attributes label(Label label) {
this.label = label;
return this;
}
}
| Java/ShoprAlgorithm/src/com/uwetrottmann/shopr/algorithm/model/Attributes.java |
package com.uwetrottmann.shopr.algorithm.model;
/**
* Holds a list of possible attributes of an item.
*/
public class Attributes {
public interface Attribute {
public String id();
public AttributeValue currentValue();
public double[] getValueWeights();
public String getValueWeightsString();
public String getReasonString();
}
public interface AttributeValue {
/**
* Returns the index of this value in the weights vector of the
* attribute.
*/
public int index();
/**
* Returns a {@link String} representation suitable for end-user
* representation.
*/
public String descriptor();
}
private ClothingType type;
private Color color;
private Label label;
public Attribute[] getAllAttributes() {
Attribute[] attrs = new Attribute[3];
attrs[0] = type();
attrs[1] = color();
attrs[2] = label();
return attrs;
}
public String getAllAttributesString() {
StringBuilder attrsStr = new StringBuilder("");
Attribute[] allAttributes = getAllAttributes();
for (int i = 0; i < allAttributes.length; i++) {
if (allAttributes[i] != null) {
attrsStr.append(allAttributes[i].getValueWeightsString());
} else {
attrsStr.append("[not set]");
}
if (i != allAttributes.length - 1) {
attrsStr.append(" ");
}
}
return attrsStr.toString();
}
/**
* Returns a string describing this query for an end-user, e.g.
* "no Red, mainly Blue, no Armani".
*/
public String getReasonString() {
StringBuilder reason = new StringBuilder();
Attribute[] allAttributes = getAllAttributes();
for (int i = 0; i < allAttributes.length; i++) {
if (allAttributes[i] == null) {
continue;
}
Attribute attribute = allAttributes[i];
if (reason.length() != 0) {
reason.append(", ");
}
reason.append(attribute.getReasonString());
}
return reason.toString();
}
public Color color() {
return color;
}
public Attributes color(Color color) {
this.color = color;
return this;
}
public ClothingType type() {
return type;
}
public Attributes type(ClothingType type) {
this.type = type;
return this;
}
public Label label() {
return label;
}
public Attributes label(Label label) {
this.label = label;
return this;
}
}
| Fix potential partially empty reason string.
| Java/ShoprAlgorithm/src/com/uwetrottmann/shopr/algorithm/model/Attributes.java | Fix potential partially empty reason string. | <ide><path>ava/ShoprAlgorithm/src/com/uwetrottmann/shopr/algorithm/model/Attributes.java
<ide> }
<ide>
<ide> Attribute attribute = allAttributes[i];
<del> if (reason.length() != 0) {
<del> reason.append(", ");
<add> String attrString = attribute.getReasonString();
<add> if (attrString != null && attrString.length() != 0) {
<add> if (reason.length() != 0) {
<add> reason.append(", ");
<add> }
<add> reason.append(attrString);
<ide> }
<del> reason.append(attribute.getReasonString());
<ide> }
<ide>
<ide> return reason.toString(); |
|
Java | apache-2.0 | 82e82fe345455110ac1da567758ae5a2869d5a80 | 0 | napp-abledea/notbed-util | /**
*
*/
package com.notbed.util;
import java.io.Closeable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.logging.LogFactory;
import com.notbed.util.mass.VoidEvaluator;
/**
* @author Alexandru Bledea
* @since Sep 22, 2013
*/
public class UClose {
public static VoidEvaluator<Closeable> CLOSE_CLOSEABLE = new CloseEvaluator<Closeable>() {
/* (non-Javadoc)
* @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
*/
@Override
protected void close(Closeable object) throws Exception {
object.close();
}
};
public static VoidEvaluator<ResultSet> CLOSE_RESULT_SET = new CloseEvaluator<ResultSet>() {
/* (non-Javadoc)
* @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
*/
@Override
protected void close(ResultSet object) throws Exception {
if (!object.isClosed()) {
object.close();
}
}
};
public static VoidEvaluator<Statement> CLOSE_STATEMENT = new CloseEvaluator<Statement>() {
/* (non-Javadoc)
* @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
*/
@Override
protected void close(Statement object) throws Exception {
if (!object.isClosed()) {
object.close();
}
}
};
public static VoidEvaluator<Connection> CLOSE_CONNECTION = new CloseEvaluator<Connection>() {
/* (non-Javadoc)
* @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
*/
@Override
protected void close(Connection object) throws Exception {
if (!object.isClosed()) {
object.close();
}
}
};
/**
* @author Alexandru Bledea
* @since Sep 22, 2013
* @param <O>
*/
private static abstract class CloseEvaluator<O> extends VoidEvaluator<O> {
/* (non-Javadoc)
* @see com.notbed.util.VoidEvaluator#evaluateNoResult(java.lang.Object)
*/
@Override
public void evaluateNoResult(O obj) {
if (obj != null) {
try {
close(obj);
} catch (Throwable t) {
LogFactory.getLog(getClass()).error("Failed to close", t);
}
}
};
/**
* @param object
*/
protected abstract void close(O object) throws Exception;
}
}
| com.notbed.util/src/com/notbed/util/UClose.java | /**
*
*/
package com.notbed.util;
import java.io.Closeable;
import java.sql.Connection;
import org.apache.commons.logging.LogFactory;
import com.notbed.util.mass.VoidEvaluator;
/**
* @author Alexandru Bledea
* @since Sep 22, 2013
*/
public class UClose {
public static VoidEvaluator<Closeable> CLOSEABLE = new CloseEvaluator<Closeable>() {
/* (non-Javadoc)
* @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
*/
@Override
protected void close(Closeable object) throws Exception {
object.close();
}
};
public static VoidEvaluator<Connection> CONNECTION = new CloseEvaluator<Connection>() {
/* (non-Javadoc)
* @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
*/
@Override
protected void close(Connection object) throws Exception {
if (!object.isClosed()) {
object.close();
}
}
};
/**
* @author Alexandru Bledea
* @since Sep 22, 2013
* @param <O>
*/
private static abstract class CloseEvaluator<O> extends VoidEvaluator<O> {
/* (non-Javadoc)
* @see com.notbed.util.VoidEvaluator#evaluateNoResult(java.lang.Object)
*/
@Override
public void evaluateNoResult(O obj) {
if (obj != null) {
try {
close(obj);
} catch (Throwable t) {
LogFactory.getLog(getClass()).error("Failed to close", t);
}
}
};
/**
* @param object
*/
protected abstract void close(O object) throws Exception;
}
}
| evaluators to close stuff
| com.notbed.util/src/com/notbed/util/UClose.java | evaluators to close stuff | <ide><path>om.notbed.util/src/com/notbed/util/UClose.java
<ide>
<ide> import java.io.Closeable;
<ide> import java.sql.Connection;
<add>import java.sql.ResultSet;
<add>import java.sql.Statement;
<ide>
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> */
<ide> public class UClose {
<ide>
<del> public static VoidEvaluator<Closeable> CLOSEABLE = new CloseEvaluator<Closeable>() {
<add> public static VoidEvaluator<Closeable> CLOSE_CLOSEABLE = new CloseEvaluator<Closeable>() {
<ide>
<ide> /* (non-Javadoc)
<ide> * @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
<ide> }
<ide> };
<ide>
<del> public static VoidEvaluator<Connection> CONNECTION = new CloseEvaluator<Connection>() {
<add> public static VoidEvaluator<ResultSet> CLOSE_RESULT_SET = new CloseEvaluator<ResultSet>() {
<add>
<add> /* (non-Javadoc)
<add> * @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
<add> */
<add> @Override
<add> protected void close(ResultSet object) throws Exception {
<add> if (!object.isClosed()) {
<add> object.close();
<add> }
<add> }
<add> };
<add>
<add> public static VoidEvaluator<Statement> CLOSE_STATEMENT = new CloseEvaluator<Statement>() {
<add>
<add> /* (non-Javadoc)
<add> * @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object)
<add> */
<add> @Override
<add> protected void close(Statement object) throws Exception {
<add> if (!object.isClosed()) {
<add> object.close();
<add> }
<add> }
<add> };
<add>
<add> public static VoidEvaluator<Connection> CLOSE_CONNECTION = new CloseEvaluator<Connection>() {
<ide>
<ide> /* (non-Javadoc)
<ide> * @see com.notbed.util.UClose.CloseEvaluator#close(java.lang.Object) |
|
Java | apache-2.0 | fa77de170541edb6dc494a7b7b8a4708264b054d | 0 | CARENTA/CARENTA | import java.awt.Dimension;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
public class GUI {
private ArrayList<Vehicle> availableVehicles = new ArrayList<Vehicle>(); // These variables need to be accessed from different methods...
private ArrayList<Product> shoppingCart = new ArrayList<Product>();
private Vehicle selectedVehicle;
private String enteredDate;
private Accessory accessory;
private Vehicle vehicle;
private String searchMode = null; // Used for defining search mode when searching for orders...
private Order order;
public GUI() {
final Controller controller = new Controller(); // Initiates link with the controller!
final CardLayout cardLayout = new CardLayout(); // Sets current layout!
/* Creates the frame for the program which has the basic window features.*/
final JFrame frame = new JFrame("CARENTA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,650);
/* Creates a container that contains the panels. */
final Container contentPane = frame.getContentPane();
contentPane.setLayout(cardLayout);
contentPane.setPreferredSize(new Dimension(frame.getWidth(), frame.getHeight()));
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the MAIN panel! -------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel mainPanel = new JPanel(); // Panel...
mainPanel.setLayout(null); // Standard layout...
contentPane.add(mainPanel, "mainPanel"); // Adds the panel mainPanel to the container where "customerPanel" identifies it!
JButton btnCustomer = new JButton("Kund"); // Buttons...
btnCustomer.setBounds(200, 100, 300, 75); // Set locations and set sizes...
mainPanel.add(btnCustomer); // Add them to the panel...
JButton btnOrder = new JButton("Order");
btnOrder.setBounds(200, 225, 300, 75);
mainPanel.add(btnOrder);
JButton btnVehicle = new JButton("Fordon");
btnVehicle.setBounds(200, 350, 300, 75);
mainPanel.add(btnVehicle);
JButton btnAccessory = new JButton("Tillbehör");
btnAccessory.setBounds(200, 475, 300, 75);
mainPanel.add(btnAccessory);
btnCustomer.addActionListener(new ActionListener() { // When clicked, switch to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
btnOrder.addActionListener(new ActionListener() { // When clicked, switch to orderPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "orderPanel");
}
});
btnVehicle.addActionListener(new ActionListener() { // When clicked, switch to vehiclePanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
btnAccessory.addActionListener(new ActionListener() { // When clicked, switch to accessoryPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the CUSTOMER panel! ---------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel customerPanel = new JPanel();
customerPanel.setLayout(null);
contentPane.add(customerPanel, "customerPanel");
JButton btnSearchCustomer = new JButton("Sök kund");
btnSearchCustomer.setBounds(200, 225, 300, 75);
customerPanel.add(btnSearchCustomer);
JButton btnNewCustomer = new JButton("Registrera kund");
btnNewCustomer.setBounds(200, 350, 300, 75);
customerPanel.add(btnNewCustomer);
JButton btnBackCustomer = new JButton("Tillbaka");
btnBackCustomer.setBounds(10, 10, 150, 35);
customerPanel.add(btnBackCustomer);
btnSearchCustomer.addActionListener(new ActionListener() { // When clicked, go to customerSearchPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerSearchPanel");
}
});
btnNewCustomer.addActionListener(new ActionListener() { // When clicked, go to customerSearchPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "chooseCustomerPanel");
}
});
btnBackCustomer.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the EDIT CUSTOMER panel! ------------------------------------------ */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel editCustomerPanel = new JPanel();
editCustomerPanel.setLayout(null);
contentPane.add(editCustomerPanel, "editCustomerPanel");
JButton btnBackEditCustomer = new JButton("Tillbaka");
btnBackEditCustomer.setBounds(10, 10, 100, 25);
editCustomerPanel.add(btnBackEditCustomer);
final JTextField txtEditPersonalNumber; // Creates search field where you input the information about the customer...
txtEditPersonalNumber= new JTextField();
txtEditPersonalNumber.setText("");
txtEditPersonalNumber.setBounds(175, 150, 250, 30);
editCustomerPanel.add(txtEditPersonalNumber);
txtEditPersonalNumber.setColumns(10);
final JTextField txtEditFirstName; // Creates search field where you input the information about the customer...
txtEditFirstName = new JTextField();
txtEditFirstName.setText("");
txtEditFirstName.setBounds(175, 50, 250, 30);
editCustomerPanel.add(txtEditFirstName);
txtEditFirstName.setColumns(10);
final JTextField txtEditLastName; // Creates search field where you input the information about the customer...
txtEditLastName = new JTextField();
txtEditLastName.setText("");
txtEditLastName.setBounds(175, 100, 250, 30);
editCustomerPanel.add(txtEditLastName);
txtEditLastName.setColumns(10);
final JTextField txtEditAddress; // Creates search field where you input the information about the customer...
txtEditAddress = new JTextField();
txtEditAddress.setText("");
txtEditAddress.setBounds(175, 200, 250, 30);
editCustomerPanel.add(txtEditAddress);
txtEditFirstName.setColumns(10);
final JTextField txtEditCity; // Creates search field where you input the information about the customer...
txtEditCity = new JTextField();
txtEditCity.setText("");
txtEditCity.setBounds(175, 250, 250, 30);
editCustomerPanel.add(txtEditCity);
txtEditCity.setColumns(10);
final JTextField txtEditAreaCode; // Creates search field where you input the information about the customer...
txtEditAreaCode = new JTextField();
txtEditAreaCode.setText("");
txtEditAreaCode.setBounds(175, 300, 250, 30);
editCustomerPanel.add(txtEditAreaCode);
txtEditAreaCode.setColumns(10);
final JTextField txtEditPhoneNumber; // Creates search field where you input the information about the customer...
txtEditPhoneNumber = new JTextField();
txtEditPhoneNumber.setText("");
txtEditPhoneNumber.setBounds(175, 350, 250, 30);
editCustomerPanel.add(txtEditPhoneNumber);
txtEditPhoneNumber.setColumns(10);
final JTextField txtEditEMail; // Creates search field where you input the information about the customer...
txtEditEMail = new JTextField();
txtEditEMail.setText("");
txtEditEMail.setBounds(175, 400, 250, 30);
editCustomerPanel.add(txtEditEMail);
txtEditEMail.setColumns(10);
JTextArea txtrEditPersonalNbr = new JTextArea(); // Creates the text next to the input field.
txtrEditPersonalNbr.setBackground(SystemColor.menu);
txtrEditPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditPersonalNbr.setText("Personnummer");
txtrEditPersonalNbr.setBounds(75, 155, 100, 27);
editCustomerPanel.add(txtrEditPersonalNbr);
txtrEditPersonalNbr.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditFirstName = new JTextArea(); // Creates the text next to the input field.
txtrEditFirstName.setBackground(SystemColor.menu);
txtrEditFirstName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditFirstName.setText("Förnamn");
txtrEditFirstName.setBounds(75, 55, 100, 27);
editCustomerPanel.add(txtrEditFirstName);
txtrEditFirstName.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditLastName = new JTextArea(); // Creates the text next to the input field.
txtrEditLastName.setBackground(SystemColor.menu);
txtrEditLastName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditLastName.setText("Efternamn");
txtrEditLastName.setBounds(75, 105, 100, 27);
editCustomerPanel.add(txtrEditLastName);
txtrEditLastName.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditAddress = new JTextArea(); // Creates the text next to the input field.
txtrEditAddress.setBackground(SystemColor.menu);
txtrEditAddress.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditAddress.setText("Gatuadress");
txtrEditAddress.setBounds(75, 205, 100, 27);
editCustomerPanel.add(txtrEditAddress);
txtrEditAddress.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditCity = new JTextArea(); // Creates the text next to the input field.
txtrEditCity.setBackground(SystemColor.menu);
txtrEditCity.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditCity.setText("Stad");
txtrEditCity.setBounds(75, 255, 100, 27);
editCustomerPanel.add(txtrEditCity);
txtrEditCity.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditAreaCode = new JTextArea(); // Creates the text next to the input field.
txtrEditAreaCode.setBackground(SystemColor.menu);
txtrEditAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditAreaCode.setText("Postnummer");
txtrEditAreaCode.setBounds(75, 305, 100, 27);
editCustomerPanel.add(txtrEditAreaCode);
txtrEditAreaCode.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditPhoneNumber = new JTextArea(); // Creates the text next to the input field.
txtrEditPhoneNumber.setBackground(SystemColor.menu);
txtrEditPhoneNumber.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditPhoneNumber.setText("Telefonnummer");
txtrEditPhoneNumber.setBounds(75, 355, 100, 27);
editCustomerPanel.add(txtrEditPhoneNumber);
txtrEditPhoneNumber.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditEMail = new JTextArea(); // Creates the text next to the input field.
txtrEditEMail.setBackground(SystemColor.menu);
txtrEditEMail.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditEMail.setText("E-mail");
txtrEditEMail.setBounds(75, 405, 100, 27);
editCustomerPanel.add(txtrEditEMail);
txtrEditEMail.setEditable(false); //Set the JTextArea uneditable.
btnBackEditCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
txtEditPersonalNumber.setText("");
txtEditFirstName.setText("");
txtEditLastName.setText("");
txtEditAddress.setText("");
txtEditCity.setText("");
txtEditAreaCode.setText("");
txtEditPhoneNumber.setText("");
txtEditEMail.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the CUSTOMER SEARCH panel! --------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel customerSearchPanel = new JPanel();
customerSearchPanel.setLayout(null);
contentPane.add(customerSearchPanel, "customerSearchPanel");
JButton btnSearchForCustomer = new JButton("Sök kund");
btnSearchForCustomer.setBounds(200, 475, 300, 75);
customerSearchPanel.add(btnSearchForCustomer);
JButton btnBackSearchCustomer = new JButton("Tillbaka");
btnBackSearchCustomer.setBounds(10, 10, 150, 35);
customerSearchPanel.add(btnBackSearchCustomer);
JTextArea txtrPersonalNbr = new JTextArea();
txtrPersonalNbr.setBounds(75, 204, 110, 19);
txtrPersonalNbr.setText("Personnummer:");
txtrPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrPersonalNbr.setBackground(SystemColor.window);
txtrPersonalNbr.setEditable(false);
customerSearchPanel.add(txtrPersonalNbr);
JTextArea txtrCustomerNbr = new JTextArea();
txtrCustomerNbr.setBounds(93, 290, 110, 19);
txtrCustomerNbr.setText("Kundnummer:");
txtrCustomerNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrCustomerNbr.setBackground(SystemColor.window);
txtrCustomerNbr.setEditable(false);
customerSearchPanel.add(txtrCustomerNbr);
final JTextField txtEnterCustomerNbr;
txtEnterCustomerNbr = new JTextField();
txtEnterCustomerNbr.setText("");
txtEnterCustomerNbr.setBounds(200, 285, 300, 30);
customerSearchPanel.add(txtEnterCustomerNbr);
txtEnterCustomerNbr.setColumns(10);
final JTextField txtrEnterPersonalNbr;
txtrEnterPersonalNbr = new JTextField();
txtrEnterPersonalNbr.setText("");
txtrEnterPersonalNbr.setBounds(200, 200, 300, 30);
customerSearchPanel.add(txtrEnterPersonalNbr);
txtEnterCustomerNbr.setColumns(10);
btnSearchForCustomer.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
String enteredCustomerNbr = txtEnterCustomerNbr.getText(); // Get text from search field...
Customer customer = controller.findCustomer(enteredCustomerNbr);
txtEditPersonalNumber.setText("balle");
txtEditFirstName.setText("balle");
txtEditLastName.setText("bella");
txtEditAddress.setText(customer.getAdress());
txtEditCity.setText(customer.getCity());
txtEditAreaCode.setText(customer.getAreaCode());
txtEditPhoneNumber.setText(customer.getPhoneNbr());
txtEditEMail.setText(customer.getMailAdress());
cardLayout.show(contentPane, "editCustomerPanel");
txtEnterCustomerNbr.setText(""); // Resets the JTextField to be empty for the next registration.
}
});
btnBackSearchCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
txtEnterCustomerNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtrEnterPersonalNbr.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- ------*/
/* ----------------------------------------- Creates the CHOOSE WICH CUSTOMER panel! --------------------------------------- */
/* ------------------------------------------------------------------------------------------------------------------------ */
final JPanel chooseCustomerPanel = new JPanel();
chooseCustomerPanel.setLayout(null);
contentPane.add(chooseCustomerPanel, "chooseCustomerPanel");
JButton btnBackChooseCustomer = new JButton("Tillbaka");
btnBackChooseCustomer.setBounds(10, 10, 150, 35);
chooseCustomerPanel.add(btnBackChooseCustomer);
JButton btnPrivateCustomer = new JButton("Privatkund");
btnPrivateCustomer.setBounds(200, 225, 300, 75);
chooseCustomerPanel.add(btnPrivateCustomer);
JButton btnCompanyCustomer = new JButton("Företagskund");
btnCompanyCustomer.setBounds(200, 350, 300, 75);
chooseCustomerPanel.add(btnCompanyCustomer);
btnBackChooseCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
btnPrivateCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newPrivateCustomerPanel");
}
});
btnCompanyCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newCompanyCustomerPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the NEW PRIVATE CUSTOMER panel! ------------------------------------------ */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel newPrivateCustomerPanel = new JPanel();
contentPane.add(newPrivateCustomerPanel, "newPrivateCustomerPanel");
newPrivateCustomerPanel.setLayout(null);
JButton btnBackNewPrivateCustomer = new JButton("Tillbaka");
JButton btnRegisterPrivateNewCustomer = new JButton("Registrera kund");
newPrivateCustomerPanel.add(btnBackNewPrivateCustomer);
newPrivateCustomerPanel.add(btnRegisterPrivateNewCustomer);
btnBackNewPrivateCustomer.setBounds(10, 10, 150, 35);
btnRegisterPrivateNewCustomer.setBounds(200, 555, 300, 75);
JTextArea textPersonalNbr = new JTextArea(); // Creates the text next to the input field.
textPersonalNbr.setBackground(SystemColor.window);
textPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
textPersonalNbr.setText("Personnummer:");
textPersonalNbr.setBounds(90, 100, 113, 19);
newPrivateCustomerPanel.add(textPersonalNbr);
textPersonalNbr.setEditable(false);
JTextArea textFirstName = new JTextArea();
textFirstName.setText("Förnamn:");
textFirstName.setFont(new Font("Tahoma", Font.PLAIN, 15));
textFirstName.setEditable(false);
textFirstName.setBackground(SystemColor.window);
textFirstName.setBounds(132, 150, 71, 16);
newPrivateCustomerPanel.add(textFirstName);
JTextArea textLastName = new JTextArea();
textLastName.setText("Efternamn:");
textLastName.setFont(new Font("Tahoma", Font.PLAIN, 15));
textLastName.setEditable(false);
textLastName.setBackground(SystemColor.window);
textLastName.setBounds(122, 200, 81, 16);
newPrivateCustomerPanel.add(textLastName);
JTextArea textAdress = new JTextArea();
textAdress.setText("Adress:");
textAdress.setFont(new Font("Tahoma", Font.PLAIN, 15));
textAdress.setEditable(false);
textAdress.setBackground(SystemColor.window);
textAdress.setBounds(145, 250, 58, 16);
newPrivateCustomerPanel.add(textAdress);
JTextArea txtrCity = new JTextArea();
txtrCity.setText("Stad:");
txtrCity.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrCity.setEditable(false);
txtrCity.setBackground(SystemColor.window);
txtrCity.setBounds(158, 300, 45, 16);
newPrivateCustomerPanel.add(txtrCity);
JTextArea txtrAreaCode = new JTextArea();
txtrAreaCode.setText("Postkod:");
txtrAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrAreaCode.setEditable(false);
txtrAreaCode.setBackground(SystemColor.window);
txtrAreaCode.setBounds(137, 350, 66, 16);
newPrivateCustomerPanel.add(txtrAreaCode);
JTextArea txtrTelephoneNbr = new JTextArea();
txtrTelephoneNbr.setText("Telefonnummer:");
txtrTelephoneNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrTelephoneNbr.setEditable(false);
txtrTelephoneNbr.setBackground(SystemColor.window);
txtrTelephoneNbr.setBounds(82, 400, 121, 16);
newPrivateCustomerPanel.add(txtrTelephoneNbr);
JTextArea txtrMail = new JTextArea();
txtrMail.setText("E-mail-adress:");
txtrMail.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrMail.setEditable(false);
txtrMail.setBackground(SystemColor.window);
txtrMail.setBounds(90, 450, 113, 16);
newPrivateCustomerPanel.add(txtrMail);
JTextArea txtrDiscountLevel = new JTextArea();
txtrDiscountLevel.setText("Rabatt:");
txtrDiscountLevel.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrDiscountLevel.setEditable(false);
txtrDiscountLevel.setBackground(SystemColor.window);
txtrDiscountLevel.setBounds(137, 499, 66, 16);
newPrivateCustomerPanel.add(txtrDiscountLevel);
final JTextField txtEnterPersonalNbr;
txtEnterPersonalNbr = new JTextField();
txtEnterPersonalNbr.setText(txtEnterPersonalNbr.getText()); ;
txtEnterPersonalNbr.setBounds(200, 95, 300, 30);
newPrivateCustomerPanel.add(txtEnterPersonalNbr);
txtEnterPersonalNbr.setColumns(10);
final JTextField txtEnterFirstName;
txtEnterFirstName = new JTextField();
txtEnterFirstName.setText("");
txtEnterFirstName.setBounds(200, 145, 300, 30);
newPrivateCustomerPanel.add(txtEnterFirstName);
txtEnterFirstName.setColumns(10);
final JTextField txtEnterLastName;
txtEnterLastName= new JTextField();
txtEnterLastName.setText("");
txtEnterLastName.setBounds(200, 195, 300, 30);
newPrivateCustomerPanel.add(txtEnterLastName);
txtEnterLastName.setColumns(10);
final JTextField txtEnterAddress;
txtEnterAddress = new JTextField();
txtEnterAddress.setText("");
txtEnterAddress.setBounds(200, 245, 300, 30);
newPrivateCustomerPanel.add(txtEnterAddress);
txtEnterPersonalNbr.setColumns(10);
final JTextField txtEnterCity;
txtEnterCity = new JTextField();
txtEnterCity.setText("");
txtEnterCity.setBounds(200, 295, 300, 30);
newPrivateCustomerPanel.add(txtEnterCity);
txtEnterCity.setColumns(10);
final JTextField txtEnterAreaCode;
txtEnterAreaCode = new JTextField();
txtEnterAreaCode.setText("");
txtEnterAreaCode.setBounds(200, 345, 300, 30);
newPrivateCustomerPanel.add(txtEnterAreaCode);
txtEnterAreaCode.setColumns(10);
final JTextField txtEnterTelephoneNbr;
txtEnterTelephoneNbr = new JTextField();
txtEnterTelephoneNbr.setText("");
txtEnterTelephoneNbr.setBounds(200, 395, 300, 30);
newPrivateCustomerPanel.add(txtEnterTelephoneNbr);
txtEnterTelephoneNbr.setColumns(10);
final JTextField txtEnterMail;
txtEnterMail = new JTextField();
txtEnterMail.setText("");
txtEnterMail.setBounds(200, 445, 300, 30);
newPrivateCustomerPanel.add(txtEnterMail);
txtEnterMail.setColumns(10);
final JTextField txtEnterDiscountLevel;
txtEnterDiscountLevel = new JTextField();
txtEnterDiscountLevel.setText("");
txtEnterDiscountLevel.setBounds(200, 495, 300, 30);
newPrivateCustomerPanel.add(txtEnterDiscountLevel);
txtEnterDiscountLevel.setColumns(10);
btnBackNewPrivateCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "chooseCustomerPanel");
txtEnterPersonalNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtEnterFirstName.setText("");
txtEnterLastName.setText("");
txtEnterAddress.setText("");
txtEnterCity.setText("");
txtEnterAreaCode.setText("");
txtEnterTelephoneNbr.setText("");
txtEnterMail.setText("");
txtEnterDiscountLevel.setText("");
}
});
btnRegisterPrivateNewCustomer.addActionListener(new ActionListener() { // When clicked, new customer i registered!
public void actionPerformed(ActionEvent e) {
String txtEnteredPersonalNbr = txtEnterPersonalNbr.getText();
String txtEnteredFirstName = txtEnterFirstName.getText();
String txtEnteredLastName = txtEnterLastName.getText();
String txtEnteredAddress = txtEnterAddress.getText();
String txtEnteredCity = txtEnterCity.getText();
String txtEnteredAreaCode = txtEnterAreaCode.getText();
String txtEnteredTelephoneNbr = txtEnterTelephoneNbr.getText();
String txtEnteredMail = txtEnterMail.getText();
controller.createPrivateCustomer(txtEnteredPersonalNbr, txtEnteredFirstName, txtEnteredLastName,
txtEnteredAddress, txtEnteredCity, txtEnteredAreaCode, txtEnteredTelephoneNbr, txtEnteredMail);
cardLayout.show(contentPane, "customerPanel"); // ... and return to the customer menu!
JOptionPane.showMessageDialog(null, "Kunden är registrerad!"); // Tell the user that the customer has been registered!
txtEnterPersonalNbr.setText("");// Resets the JTextField to be empty for the next registration.
txtEnterFirstName.setText("");
txtEnterLastName.setText("");
txtEnterAddress.setText("");
txtEnterCity.setText("");
txtEnterAreaCode.setText("");
txtEnterTelephoneNbr.setText("");
txtEnterMail.setText("");
txtEnterDiscountLevel.setText("");
}
});
/* ---------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the NEW COMPANY CUSTOMER panel! ------------------------------------- */
/* ------------------------------------------------------------------------------------------------------------------------ */
final JPanel newCompanyCustomerPanel = new JPanel();
newCompanyCustomerPanel.setLayout(null);
contentPane.add(newCompanyCustomerPanel, "newCompanyCustomerPanel");
JButton btnBackNewCompanyCustomer = new JButton("Tillbaka");
btnBackNewCompanyCustomer.setBounds(10, 10, 150, 35);
newCompanyCustomerPanel.add(btnBackNewCompanyCustomer);
JButton btnRegisterNewCompanyCustomer = new JButton("Registrera kund");
btnRegisterNewCompanyCustomer.setBounds(200, 550, 300, 75);
newCompanyCustomerPanel.add(btnRegisterNewCompanyCustomer);
JTextArea textCompanyOrgNbr = new JTextArea();
textCompanyOrgNbr.setText("Organisationsnummer:");
textCompanyOrgNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyOrgNbr.setEditable(false);
textCompanyOrgNbr.setBackground(SystemColor.window);
textCompanyOrgNbr.setBounds(32, 100, 150, 16);
newCompanyCustomerPanel.add(textCompanyOrgNbr);
JTextArea textCompanyName = new JTextArea();
textCompanyName.setText("Företagsnamn:");
textCompanyName.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyName.setEditable(false);
textCompanyName.setBackground(SystemColor.window);
textCompanyName.setBounds(80, 150, 102, 16);
newCompanyCustomerPanel.add(textCompanyName);
JTextArea textCompanyAdress = new JTextArea();
textCompanyAdress.setText("Adress:");
textCompanyAdress.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyAdress.setEditable(false);
textCompanyAdress.setBackground(SystemColor.window);
textCompanyAdress.setBounds(129, 200, 53, 16);
newCompanyCustomerPanel.add(textCompanyAdress);
JTextArea textCompanyCity = new JTextArea();
textCompanyCity.setText("Stad:");
textCompanyCity.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyCity.setEditable(false);
textCompanyCity.setBackground(SystemColor.window);
textCompanyCity.setBounds(135, 250, 47, 16);
newCompanyCustomerPanel.add(textCompanyCity);
JTextArea textCompanyAreaCode = new JTextArea();
textCompanyAreaCode.setText("Postnummer:");
textCompanyAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyAreaCode.setEditable(false);
textCompanyAreaCode.setBackground(SystemColor.window);
textCompanyAreaCode.setBounds(90, 300, 92, 16);
newCompanyCustomerPanel.add(textCompanyAreaCode);
JTextArea textCompanyPhoneNbr = new JTextArea();
textCompanyPhoneNbr.setText("Telefonnummer:");
textCompanyPhoneNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyPhoneNbr.setEditable(false);
textCompanyPhoneNbr.setBackground(SystemColor.window);
textCompanyPhoneNbr.setBounds(69, 350, 113, 16);
newCompanyCustomerPanel.add(textCompanyPhoneNbr);
JTextArea textCompanyMailAdress = new JTextArea();
textCompanyMailAdress.setText("E-mail adress:");
textCompanyMailAdress.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyMailAdress.setEditable(false);
textCompanyMailAdress.setBackground(SystemColor.window);
textCompanyMailAdress.setBounds(80, 400, 102, 16);
newCompanyCustomerPanel.add(textCompanyMailAdress);
JTextArea textCompanyDiscountLevel = new JTextArea();
textCompanyDiscountLevel.setText("Rabatt:");
textCompanyDiscountLevel.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyDiscountLevel.setEditable(false);
textCompanyDiscountLevel.setBackground(SystemColor.window);
textCompanyDiscountLevel.setBounds(129, 450, 53, 16);
newCompanyCustomerPanel.add(textCompanyDiscountLevel);
final JTextField txtEnterCompanyOrgNbr;
txtEnterCompanyOrgNbr = new JTextField();
txtEnterCompanyOrgNbr.setText("");
txtEnterCompanyOrgNbr.setBounds(200, 95, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyOrgNbr);
txtEnterCompanyOrgNbr.setColumns(10);
final JTextField txtEnterCompanyName;
txtEnterCompanyName = new JTextField();
txtEnterCompanyName.setText("");
txtEnterCompanyName.setBounds(200, 145, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyName);
txtEnterCompanyName.setColumns(10);
final JTextField txtEnterCompanyAdress;
txtEnterCompanyAdress = new JTextField();
txtEnterCompanyAdress.setText("");
txtEnterCompanyAdress.setBounds(200, 195, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyAdress);
txtEnterCompanyAdress.setColumns(10);
final JTextField txtEnterCompanyCity;
txtEnterCompanyCity = new JTextField();
txtEnterCompanyCity.setText("");
txtEnterCompanyCity.setBounds(200, 245, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyCity);
txtEnterCompanyCity.setColumns(10);
final JTextField txtEnterCompanyAreaCode;
txtEnterCompanyAreaCode = new JTextField();
txtEnterCompanyAreaCode.setText("");
txtEnterCompanyAreaCode.setBounds(200, 295, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyAreaCode);
txtEnterCompanyAreaCode.setColumns(10);
final JTextField txtEnterCompanyPhoneNbr;
txtEnterCompanyPhoneNbr = new JTextField();
txtEnterCompanyPhoneNbr.setText("");
txtEnterCompanyPhoneNbr.setBounds(200, 345, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyPhoneNbr);
txtEnterCompanyPhoneNbr.setColumns(10);
final JTextField txtEnterCompanyMailAdress;
txtEnterCompanyMailAdress = new JTextField();
txtEnterCompanyMailAdress.setText("");
txtEnterCompanyMailAdress.setBounds(200, 395, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyMailAdress);
txtEnterCompanyMailAdress.setColumns(10);
final JTextField txtEnterCompanyDiscountLevel;
txtEnterCompanyDiscountLevel = new JTextField();
txtEnterCompanyDiscountLevel.setText("");
txtEnterCompanyDiscountLevel.setBounds(200, 445, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyDiscountLevel);
txtEnterCompanyDiscountLevel.setColumns(10);
btnRegisterNewCompanyCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
String txtEnteredCompanyOrgNbr = txtEnterCompanyOrgNbr.getText();
String txtEnteredCompanyName = txtEnterCompanyName.getText();
String txtEnteredCompanyAdress = txtEnterCompanyAdress.getText();
String txtEnteredCompanyCity = txtEnterCompanyCity.getText();
String txtEnteredCompanyAreaCode = txtEnterCompanyAreaCode.getText();
String txtEnteredCompanyPhoneNbr = txtEnterCompanyPhoneNbr.getText();
String txtEnteredCompanyMailAdress = txtEnterCompanyMailAdress.getText();
controller.createCompanyCustomer(txtEnteredCompanyOrgNbr, txtEnteredCompanyName, txtEnteredCompanyAdress, txtEnteredCompanyCity,
txtEnteredCompanyAreaCode, txtEnteredCompanyPhoneNbr, txtEnteredCompanyMailAdress);
cardLayout.show(contentPane, "customerPanel");
JOptionPane.showMessageDialog(null, "Kunden är registrerad!"); // Tell the user that the customer has been registered!
txtEnterCompanyOrgNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtEnterCompanyName.setText("");
txtEnterCompanyAdress.setText("");
txtEnterCompanyCity.setText("");
txtEnterCompanyAreaCode.setText("");
txtEnterCompanyPhoneNbr.setText("");
txtEnterCompanyMailAdress.setText("");
txtEnterCompanyDiscountLevel.setText("");
}
});
btnBackNewCompanyCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "chooseCustomerPanel");
txtEnterCompanyOrgNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtEnterCompanyName.setText("");
txtEnterCompanyAdress.setText("");
txtEnterCompanyCity.setText("");
txtEnterCompanyAreaCode.setText("");
txtEnterCompanyPhoneNbr.setText("");
txtEnterCompanyMailAdress.setText("");
txtEnterCompanyDiscountLevel.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the ORDER panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel orderPanel = new JPanel();
orderPanel.setLayout(null);
contentPane.add(orderPanel, "orderPanel");
JButton btnSearchOrder = new JButton("Sök order");
btnSearchOrder.setBounds(200, 225, 300, 75);
orderPanel.add(btnSearchOrder);
JButton btnNewOrder = new JButton("Registrera order");
btnNewOrder.setBounds(200, 350, 300, 75);
orderPanel.add(btnNewOrder);
JButton btnBackOrder = new JButton("Tillbaka");
btnBackOrder.setBounds(10, 10, 150, 35);
orderPanel.add(btnBackOrder);
btnNewOrder.addActionListener(new ActionListener() { // When clicked, go back to new order panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newOrderPanel");
}
});
btnSearchOrder.addActionListener(new ActionListener() { // When clicked, go to search order panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "searchOrderPanel");
}
});
btnBackOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- Creates the SEARCH ORDER panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel searchOrderPanel = new JPanel();
searchOrderPanel.setLayout(null);
contentPane.add(searchOrderPanel, "searchOrderPanel");
/* ---- Buttons... ---- */
final JButton btnSearchSpecificOrder = new JButton("Sök specifik order"); // Buttons...
btnSearchSpecificOrder.setBounds(200, 100, 300, 75); // Set locations and set sizes...
searchOrderPanel.add(btnSearchSpecificOrder); // Add them to the panel...
final JButton btnSearchDatesOrders = new JButton("Sök ordrar utförda ett visst datum");
btnSearchDatesOrders.setBounds(200, 225, 300, 75);
searchOrderPanel.add(btnSearchDatesOrders);
final JButton btnSearchCustomerOrders = new JButton("Sök ordrar utförda av specifik kund");
btnSearchCustomerOrders.setBounds(200, 475, 300, 75);
searchOrderPanel.add(btnSearchCustomerOrders);
final JButton btnSearchProductOrders = new JButton("Sök ordrar innehållandes en viss produkt");
btnSearchProductOrders.setBounds(200, 350, 300, 75);
searchOrderPanel.add(btnSearchProductOrders);
final JButton btnCommitSearch = new JButton("Sök"); // Button used for the actual search!
btnCommitSearch.setBounds(200, 451, 300, 75);
searchOrderPanel.add(btnCommitSearch);
btnCommitSearch.setVisible(false);
final JButton btnRemoveOrder = new JButton("Ta bort order"); // Button used for the actual search!
btnRemoveOrder.setBounds(200, 539, 300, 75);
searchOrderPanel.add(btnRemoveOrder);
btnRemoveOrder.setVisible(false);
final JButton btnBackSearchOrder = new JButton("Tillbaka");
btnBackSearchOrder.setBounds(10, 10, 150, 35);
searchOrderPanel.add(btnBackSearchOrder);
/* ----- TextField... ------ */
final JTextField inputSearchData;
inputSearchData = new JTextField();
inputSearchData.setText("");
inputSearchData.setBounds(200, 308, 300, 30);
searchOrderPanel.add(inputSearchData);
inputSearchData.setColumns(10);
inputSearchData.setVisible(false);
inputSearchData.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
inputSearchData.setText("");
}
});
/* ----- Tabulars... ---- */
String searchColumn[] = {"Ordernummer", "Datum", "Kundnummer", "Totalt pris"};
final DefaultTableModel searchModel = new DefaultTableModel(searchColumn, 0);
final JTable searchTable = new JTable(searchModel);
searchTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchTable.setVisible(false);
final JScrollPane searchScrollPane = new JScrollPane();
searchScrollPane.setLocation(10, 55);
searchScrollPane.setSize(680, 365);
searchOrderPanel.add(searchScrollPane);
searchScrollPane.setVisible(false);
final JTextPane specificSearchPane = new JTextPane();
specificSearchPane.setBounds(10, 55, 680, 365);
searchOrderPanel.add(specificSearchPane);
specificSearchPane.setVisible(false);
/* ---- Action listeners... */
btnSearchSpecificOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "specific";
inputSearchData.setText("Ange ordernummer");
}
});
btnSearchDatesOrders.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "date";
inputSearchData.setText("Ange ett datum på formen YYYY/MM/DD");
}
});
btnSearchCustomerOrders.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "customer";
inputSearchData.setText("Ange kundnummer");
}
});
btnSearchProductOrders.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "product";
inputSearchData.setText("Ange produktnamn");
}
});
btnCommitSearch.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnRemoveOrder.setVisible(true);
Order order;
ArrayList<Order> orderRegistry = controller.orderRegistry.getOrders();
String searchVariable = inputSearchData.getText();
inputSearchData.setVisible(false);
if(searchMode == "specific") {
order = controller.orderRegistry.getOrder(Integer.parseInt(searchVariable));
specificSearchPane.setText("Ordernummer: " + order.getOrderNbr() + "\n \n" +
"Beställare (kundnummer): " + order.getCustomer().getCustomerNbr() + "\n \n" +
"Produkter: " + "\n \n" +
"Totalt pris:" + order.getTotalPrice() + "\n \n" +
"Datum då ordern utfärdades: " + order.getLatestUpdate());
specificSearchPane.setVisible(true);
}
if(searchMode == "date") {
for(int a = 0; a < orderRegistry.size(); a++) {
order = orderRegistry.get(a);
if(searchVariable.equals(order.getLatestUpdate())) {
searchModel.addRow(new Object[]{order.getOrderNbr(), order.getLatestUpdate(), order.getCustomer().getCustomerNbr(), order.getTotalPrice()});
}
}
searchScrollPane.setViewportView(searchTable);
searchScrollPane.setVisible(true);
searchTable.setVisible(true);
}
if(searchMode == "customer") {
for(int a = 0; a < orderRegistry.size(); a++) {
order = orderRegistry.get(a);
if(searchVariable.equals(order.getCustomer().toString())) {
searchModel.addRow(new Object[]{order.getOrderNbr(), order.getLatestUpdate(), order.getCustomer().getCustomerNbr(), order.getTotalPrice()});
}
}
searchScrollPane.setViewportView(searchTable);
searchScrollPane.setVisible(true);
searchTable.setVisible(true);
}
if(searchMode == "product") {
ArrayList<Product> products;
Product product;
for(int a = 0; a < orderRegistry.size(); a++) {
order = orderRegistry.get(a);
products = order.getProducts();
for(int b = 0; b < products.size(); b++ ) {
product = products.get(a);
if(searchVariable.equals(product.getProductName())) {
searchModel.addRow(new Object[]{order.getOrderNbr(), order.getLatestUpdate(), order.getCustomer().getCustomerNbr(), order.getTotalPrice()});
}
}
}
searchScrollPane.setViewportView(searchTable);
searchScrollPane.setVisible(true);
searchTable.setVisible(true);
}
}
});
btnRemoveOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
int goRemoveSelection = JOptionPane.showConfirmDialog(null, "Du håller på att ta bort ordern, vill du det?",
"Varning!", JOptionPane.YES_OPTION);
if(goRemoveSelection == 1) { // If the user doesn't want to cancel the order...
// ... do nothing!
}
else if(goRemoveSelection == 0) { // If the user wants to cancel the order...
controller.orderRegistry.removeOrder(order.getOrderNbr() - 1);
order = null;
btnCommitSearch.setVisible(false);
btnRemoveOrder.setVisible(false);
inputSearchData.setVisible(false);
searchTable.setVisible(false);
searchScrollPane.setVisible(false);
specificSearchPane.setVisible(false);
btnSearchSpecificOrder.setVisible(true);
btnSearchDatesOrders.setVisible(true);
btnSearchCustomerOrders.setVisible(true);
btnSearchProductOrders.setVisible(true);
searchMode = null;
specificSearchPane.setText("");
cardLayout.show(contentPane, "orderPanel");
}
}
});
btnBackSearchOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnCommitSearch.setVisible(false);
btnRemoveOrder.setVisible(false);
inputSearchData.setVisible(false);
searchTable.setVisible(false);
searchScrollPane.setVisible(false);
btnSearchSpecificOrder.setVisible(true);
btnSearchDatesOrders.setVisible(true);
btnSearchCustomerOrders.setVisible(true);
btnSearchProductOrders.setVisible(true);
cardLayout.show(contentPane, "orderPanel");
order = null;
searchMode = null;
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ------------------------------------------- Creates the NEW ORDER panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel newOrderPanel = new JPanel();
newOrderPanel.setLayout(null);
contentPane.add(newOrderPanel, "newOrderPanel");
/* ------- Buttons... ------- */
final JButton btnEnteredDate = new JButton("Gå vidare");
btnEnteredDate.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnEnteredDate);
final JButton btnChooseVehicle = new JButton("Välj bil");
btnChooseVehicle.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnChooseVehicle);
btnChooseVehicle.setVisible(false);
final JButton btnChooseAccessory = new JButton("Gå vidare");
btnChooseAccessory.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnChooseAccessory);
btnChooseAccessory.setVisible(false);
final JButton btnMoreAccessory = new JButton("Lägg till ytterligare tillbehör");
btnMoreAccessory.setBounds(200, 440, 300, 75);
newOrderPanel.add(btnMoreAccessory);
btnMoreAccessory.setVisible(false);
final JButton btnViewOrder = new JButton("Granska order");
btnViewOrder.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnViewOrder);
btnViewOrder.setVisible(false);
final JButton btnConfirmOrder = new JButton("Slutför order");
btnConfirmOrder.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnConfirmOrder);
btnConfirmOrder.setVisible(false);
final JButton btnBackNewOrder = new JButton("Tillbaka");
btnBackNewOrder.setBounds(10, 10, 150, 35);
newOrderPanel.add(btnBackNewOrder);
/* ------- Textfields... ------- */
final JTextField txtEnteredDate;
txtEnteredDate = new JTextField();
txtEnteredDate.setText("YYYY/MM/DD");
txtEnteredDate.setBounds(200, 178, 300, 30);
newOrderPanel.add(txtEnteredDate);
txtEnteredDate.setColumns(10);
txtEnteredDate.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
txtEnteredDate.setText("");
}
});
final JTextField txtEnteredCustomer;
txtEnteredCustomer = new JTextField();
txtEnteredCustomer.setText("");
txtEnteredCustomer.setBounds(200, 440, 300, 30);
newOrderPanel.add(txtEnteredCustomer);
txtEnteredCustomer.setColumns(10);
txtEnteredCustomer.setVisible(false);
/* ------- Comboboxes... ------- */
final JComboBox warehouseSelection = new JComboBox(new String[]{"Lund", "Linköping", "Göteborg"}); // Creates a combobox with selections...
warehouseSelection.setBounds(200, 278, 300, 30);
newOrderPanel.add(warehouseSelection);
final JComboBox typeSelection = new JComboBox(new String[]{"Personbil", "Minibuss", "Lastbil", "Släpvagn"});
typeSelection.setBounds(200, 378, 300, 30);
newOrderPanel.add(typeSelection);
final JComboBox employeeSelection = new JComboBox(new String[]{"Jonas", "Malin", "Swante"});
employeeSelection.setBounds(200, 485, 300, 30);
newOrderPanel.add(employeeSelection);
employeeSelection.setVisible(false);
/* ------- Textfields... ------- */
final JTextArea txtrDate = new JTextArea();
txtrDate.setText("Ange datum:");
txtrDate.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrDate.setEditable(false);
txtrDate.setBackground(SystemColor.window);
txtrDate.setBounds(109, 183, 94, 25);
newOrderPanel.add(txtrDate);
final JTextArea txtrWarehouse = new JTextArea();
txtrWarehouse.setText("Välj utlämningskontor:");
txtrWarehouse.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrWarehouse.setEditable(false);
txtrWarehouse.setBackground(SystemColor.window);
txtrWarehouse.setBounds(47, 282, 162, 26);
newOrderPanel.add(txtrWarehouse);
final JTextArea txtrType = new JTextArea();
txtrType.setText("Välj fordonstyp:");
txtrType.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrType.setEditable(false);
txtrType.setBackground(SystemColor.window);
txtrType.setBounds(88, 382, 140, 26);
newOrderPanel.add(txtrType);
final JTextArea txtrSelCustomerNbr = new JTextArea();
txtrSelCustomerNbr.setText("Ange kundnummer:");
txtrSelCustomerNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrSelCustomerNbr.setEditable(false);
txtrSelCustomerNbr.setBackground(SystemColor.window);
txtrSelCustomerNbr.setBounds(63, 445, 140, 19);
newOrderPanel.add(txtrSelCustomerNbr);
txtrSelCustomerNbr.setVisible(false);
final JTextArea txtrEmployee = new JTextArea();
txtrEmployee.setText("Ange handläggare:");
txtrEmployee.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrEmployee.setEditable(false);
txtrEmployee.setBackground(SystemColor.window);
txtrEmployee.setBounds(69, 491, 134, 19);
newOrderPanel.add(txtrEmployee);
txtrEmployee.setVisible(false);
/* ------- Tabulars... ------- */
String vehicleColumn[] = {"Modell","Körkortskrav","Pris","Har krok","Regnummer"};
final DefaultTableModel vehicleModel = new DefaultTableModel(vehicleColumn, 0);
final JTable vehicleTable = new JTable(vehicleModel);
vehicleTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
String accessoryColumn[] = {"Namn", "Information", "Pris", "Produktnummer"};
final DefaultTableModel accessoryModel = new DefaultTableModel(accessoryColumn, 0);
final JTable accessoryTable = new JTable(accessoryModel);
accessoryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
String productsColumn[] = {"Produkt", "Information", "Pris", "Identifikation"};
final DefaultTableModel productsModel = new DefaultTableModel(productsColumn, 0);
final JTable productsTable = new JTable(productsModel);
productsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
productsTable.setRowSelectionAllowed(false);
productsTable.setFocusable(false);
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setLocation(10, 55);
scrollPane.setSize(680, 365);
newOrderPanel.add(scrollPane);
scrollPane.setVisible(false);
/* --------- Action listeners... --------- */
btnEnteredDate.addActionListener(new ActionListener() { // When the date and other info has been entered (button clicked)...
public void actionPerformed(ActionEvent e) {
enteredDate = txtEnteredDate.getText(); // Retrieves data from the forms...
if(!enteredDate.equals("")) {
// Error message, wrong format or illegal date input...
String selectedWarehouse = warehouseSelection.getSelectedItem().toString();
String selectedType = typeSelection.getSelectedItem().toString();
availableVehicles = controller.calculateVehicleAvailability(enteredDate, selectedWarehouse, selectedType); // Calculates vehicle availability with input data...
if(availableVehicles.size() != 0) { // If there are available vehicles...
txtEnteredDate.setVisible(false); // Hides previous data forms...
txtrDate.setVisible(false);
txtrWarehouse.setVisible(false);
txtrType.setVisible(false);
warehouseSelection.setVisible(false);
typeSelection.setVisible(false);
btnEnteredDate.setVisible(false);
Vehicle vehicle; // Creates temporary variables in which to store information when rendering vehicle information...
String vehicleModelName;
String licenseReq;
int price;
String hasHook;
for(int a = 0; a < availableVehicles.size(); a++) { // For each vehicle in the list...
vehicle = availableVehicles.get(a); // Print the information...
vehicleModelName = vehicle.getProductName();
licenseReq = vehicle.getLicenseReq();
price = vehicle.getPrice();
/* We need to print the hasHook-argument in a more sensible way which is why we do this... */
if(vehicle.hasHook()) {
hasHook = "Ja";
}
else hasHook = "Nej";
vehicleModel.addRow(new Object[]{vehicleModelName, licenseReq, price, hasHook}); // Add everything to the row and then add the row itself!
}
scrollPane.setVisible(true);
scrollPane.setViewportView(vehicleTable); // Make sure that the scrollPane displays the correct table...
vehicleTable.setVisible(true); // Show the new data forms!
btnChooseVehicle.setVisible(true);
}
else { JOptionPane.showMessageDialog(null, "Inga tillgängliga bilar hittades!"); } // If there's no available vehicles...
}
else { JOptionPane.showMessageDialog(null, "Du måste ange ett giltigt datum!"); }
}
});
btnChooseVehicle.addActionListener(new ActionListener() { // When the vehicle is chosen (button clicked) ...
public void actionPerformed(ActionEvent e) {
int vehicleNumber = vehicleTable.getSelectedRow(); // Retrieve the vehicle in question...
if(vehicleNumber > -1) { // If there is a vehicle selected...
vehicleTable.setVisible(false);
btnChooseVehicle.setVisible(false);
selectedVehicle = availableVehicles.get(vehicleNumber); // Get it from the available vehicle list...
selectedVehicle.setBooked(enteredDate); // Set it as booked with the entered date!
shoppingCart.add(selectedVehicle); // Add it to the shopping cart...
Accessory accessory;
String name;
String info;
int price;
int accessoryNbr;
for(int a = 0; a < controller.accessoryRegistry.getAccessories().size(); a++) { // Generate available accessories...
accessory = controller.accessoryRegistry.getAccessory(a);
name = accessory.getProductName();
info = accessory.getInfoTxt();
price = accessory.getPrice();
accessoryNbr = accessory.getProductNbr();
accessoryModel.addRow(new Object[]{name, info, price, accessoryNbr});
}
btnMoreAccessory.setVisible(true);
scrollPane.setViewportView(accessoryTable);
accessoryTable.setVisible(true);
btnViewOrder.setVisible(true);
}
else { JOptionPane.showMessageDialog(null, "Du måste välja ett fordon!"); }
}
});
btnMoreAccessory.addActionListener(new ActionListener() { // In order to add more accessories to the purchase...
public void actionPerformed(ActionEvent e) {
int accessoryNumber = accessoryTable.getSelectedRow(); // Get which accessory is selected...
if(accessoryNumber > -1) {
Accessory accessory;
accessory = controller.accessoryRegistry.getAccessory(accessoryNumber); // Retrieve the accessory...
shoppingCart.add(accessory); // Add it to the current list!
accessoryTable.clearSelection();
}
else { JOptionPane.showMessageDialog(null, "Du måste välja ett tillbehör!"); }
}
});
btnViewOrder.addActionListener(new ActionListener() { // When clicked, let's see the whole order...
public void actionPerformed(ActionEvent e) {
int accessoryNumber = accessoryTable.getSelectedRow(); // Get which accessory is selected...
if(accessoryNumber > -1) {
Accessory accessory;
accessory = controller.accessoryRegistry.getAccessory(accessoryNumber); // Retrieve the accessory...
shoppingCart.add(accessory); // Add it to the current list!
}
btnMoreAccessory.setVisible(false);
accessoryTable.setVisible(false);
btnViewOrder.setVisible(false);
Product product = null;
String name = null;
String info = null;
int price = 0;
int accessoryNbr = 0;
for(int a = 0; a < shoppingCart.size(); a++) { // Add the accessories to the display table...
product = shoppingCart.get(a);
name = product.getProductName();
info = product.getInfoTxt();
price = product.getPrice();
productsModel.addRow(new Object[]{name, info, price, accessoryNbr});
}
productsTable.setVisible(true);
scrollPane.setViewportView(productsTable);
txtEnteredCustomer.setVisible(true);
employeeSelection.setVisible(true);
btnConfirmOrder.setVisible(true);
txtrSelCustomerNbr.setVisible(true);
txtrEmployee.setVisible(true);
}
});
btnConfirmOrder.addActionListener(new ActionListener() { // When clicked, create the order!
public void actionPerformed(ActionEvent e) {
int customerNbr = Integer.parseInt(txtEnteredCustomer.getText()); // Retrieve more data...
if(customerNbr < controller.customerRegistry.getCustomers().size() && customerNbr > -1) {
Customer customer = controller.customerRegistry.getCustomer(customerNbr);
productsTable.setVisible(false);
btnConfirmOrder.setVisible(false);
employeeSelection.setVisible(false);
txtEnteredCustomer.setVisible(false);
txtrSelCustomerNbr.setVisible(false);
txtrEmployee.setVisible(false);
String employeeName = employeeSelection.getSelectedItem().toString();
Employee employee;
Employee selectedEmployee = null;
for(int a = 0; a < controller.employeeRegistry.getEmployees().size(); a++) { // Find the employee...
employee = controller.employeeRegistry.getEmployee(a);
if(employeeName.equals(employee.getFirstName())) {
selectedEmployee = employee;
}
}
Controller.createOrder(customer, shoppingCart, selectedEmployee); // Call the controller and create the order...
txtEnteredDate.setText(""); // Reset what's supposed to show for the next order input...
txtEnteredDate.setVisible(true);
txtrDate.setVisible(true);
txtrWarehouse.setVisible(true);
txtrType.setVisible(true);
warehouseSelection.setVisible(true);
typeSelection.setVisible(true);
btnEnteredDate.setVisible(true);
enteredDate = null; // Reset data...
availableVehicles = null;
selectedVehicle = null;
shoppingCart.clear();
vehicleModel.setRowCount(0); // Clear tables!
accessoryModel.setRowCount(0);
productsModel.setRowCount(0);
scrollPane.setVisible(false);
cardLayout.show(contentPane, "orderPanel"); // ... and return to the order menu!
JOptionPane.showMessageDialog(null, "Ordern är utförd!"); // Tell the user that the order has been confirmed!
}
else { JOptionPane.showMessageDialog(null, "Du måste ange ett giltigt kundnummer!"); }
}
});
btnBackNewOrder.addActionListener(new ActionListener() { // When clicked...
public void actionPerformed(ActionEvent e) {
int goBackSelection = JOptionPane.showConfirmDialog(null, "Du håller på att avbryta beställningen, " // Warn the user of cancelation!
+ "ingen data kommer att sparas! \n \n Vill du avbryta?",
"Varning!", JOptionPane.YES_OPTION);
if(goBackSelection == 1) { // If the user doesn't want to cancel the order...
// ... do nothing!
}
else if(goBackSelection == 0) { // If the user wants to cancel the order...
cardLayout.show(contentPane, "orderPanel");
txtEnteredDate.setText(""); // RESET ALL DATA to prevent stupid data problems, if you fail at making an order you'll have to re-do it!
txtEnteredCustomer.setText("");
txtEnteredDate.setVisible(true);
txtrDate.setVisible(true);
txtrWarehouse.setVisible(true);
txtrType.setVisible(true);
warehouseSelection.setVisible(true);
typeSelection.setVisible(true);
btnEnteredDate.setVisible(true);
if(selectedVehicle != null) { // If there is a selected vehicle...
selectedVehicle.removeBooked(enteredDate); // Remove the booked date!
}
vehicleTable.setVisible(false);
accessoryTable.setVisible(false);
productsTable.setVisible(false);
txtEnteredDate.setText("YYYY/MM/DD");
txtEnteredCustomer.setVisible(false);
txtrSelCustomerNbr.setVisible(false);
txtrEmployee.setVisible(false);
employeeSelection.setVisible(false);
btnMoreAccessory.setVisible(false);
btnChooseAccessory.setVisible(false);
btnChooseVehicle.setVisible(false);
btnConfirmOrder.setVisible(false);
scrollPane.setVisible(false);
vehicleModel.setRowCount(0); // Clear tables!
accessoryModel.setRowCount(0);
productsModel.setRowCount(0);
enteredDate = null;
selectedVehicle = null;
availableVehicles = null;
shoppingCart.clear();
}
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the VEHICLE panel! ----------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel vehiclePanel = new JPanel();
vehiclePanel.setLayout(null);
contentPane.add(vehiclePanel, "vehiclePanel");
JButton btnSearchVehicle = new JButton("Sök fordon");
JButton btnNewVehicle = new JButton("Registrera fordon");
JButton btnBackVehicle = new JButton("Tillbaka");
btnSearchVehicle.setBounds(200, 225, 300, 75);
btnNewVehicle.setBounds(200, 350, 300, 75);
btnBackVehicle.setBounds(10, 10, 150, 35);
vehiclePanel.add(btnSearchVehicle);
vehiclePanel.add(btnNewVehicle);
vehiclePanel.add(btnBackVehicle);
btnBackVehicle.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
btnSearchVehicle.addActionListener(new ActionListener() { // To come in to the search button
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehicleSearchPanel");
}
});
btnNewVehicle.addActionListener(new ActionListener() { // To come in to the registerVehicle button
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "registerNewVehiclePanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- Creates the SEARCH VEHICLE panel! ----------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel vehicleSearchPanel = new JPanel();
vehicleSearchPanel.setLayout(null);
contentPane.add(vehicleSearchPanel, "vehicleSearchPanel");
JButton btnSearchForVehicle = new JButton("Sök fordon");
JButton btnBackSearchVehicle = new JButton("Tillbaka");
btnSearchForVehicle.setBounds(200, 485, 300, 75);
btnBackSearchVehicle.setBounds(10, 10, 100, 25);
vehicleSearchPanel.add(btnSearchForVehicle);
vehicleSearchPanel.add(btnBackSearchVehicle);
final JTextField txtEnterRegNbr; // Creates search field where you input the customer number...
txtEnterRegNbr = new JTextField();
txtEnterRegNbr.setText("");
txtEnterRegNbr.setBounds(200, 420, 300, 30);
vehicleSearchPanel.add(txtEnterRegNbr);
txtEnterRegNbr.setColumns(10);
final JTextPane paneVehicleResult = new JTextPane();
paneVehicleResult.setBounds(158, 55, 400, 335);
vehicleSearchPanel.add(paneVehicleResult);
btnSearchForVehicle.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
String enterdRegNbr = txtEnterRegNbr.getText() ; // Get text from search field...
String vehicleResult = controller.findVehicle(enterdRegNbr); // ... find the vehicle...
paneVehicleResult.setText(vehicleResult); // ... and print the text!
}
});
btnBackSearchVehicle.addActionListener(new ActionListener() { // When clicked, go back to vehiclePanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ------------------------------------------- Creates the NEW VEHICLE panel! ----------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel registerNewVehiclePanel = new JPanel();
contentPane.add(registerNewVehiclePanel, "registerNewVehiclePanel");
registerNewVehiclePanel.setLayout(null);
JButton btnBackRegisterNewVehicle = new JButton("Tillbaka");
JButton btnRegisterNewVehicle = new JButton("Registrera fordon");
btnBackRegisterNewVehicle.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
btnBackRegisterNewVehicle.setBounds(10, 10, 150, 35);
btnRegisterNewVehicle.setBounds(200, 485, 300, 75);
registerNewVehiclePanel.add(btnBackRegisterNewVehicle);
registerNewVehiclePanel.add(btnRegisterNewVehicle);
final JTextField txtEnterVehicleRegNbr; // Creates search field where you input the information about the vehicle...
txtEnterVehicleRegNbr = new JTextField();
txtEnterVehicleRegNbr.setText("");
txtEnterVehicleRegNbr.setBounds(225, 74, 250, 30);
registerNewVehiclePanel.add(txtEnterVehicleRegNbr);
txtEnterVehicleRegNbr.setColumns(10);
final JTextArea txtrVehicleRegNbr = new JTextArea();
txtrVehicleRegNbr.setEditable(false);
txtrVehicleRegNbr.setBackground(SystemColor.window);
txtrVehicleRegNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrVehicleRegNbr.setText("Registreringsnummer");
txtrVehicleRegNbr.setBounds(90, 81, 130, 27);
registerNewVehiclePanel.add(txtrVehicleRegNbr);
final JTextField txtEnterVehicleModel; // Creates search field where you input the information about the vehicle...
txtEnterVehicleModel = new JTextField();
txtEnterVehicleModel.setText("");
txtEnterVehicleModel.setBounds(225, 120, 250, 30);
registerNewVehiclePanel.add(txtEnterVehicleModel);
txtEnterVehicleModel.setColumns(10);
final JTextArea txtrVehicleModel = new JTextArea();
txtrVehicleModel.setEditable(false);
txtrVehicleModel.setBackground(SystemColor.window);
txtrVehicleModel.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrVehicleModel.setText("Modell");
txtrVehicleModel.setBounds(130, 123, 100, 27);
registerNewVehiclePanel.add(txtrVehicleModel);
final JTextField txtEnterVehicleType; // Creates search field where you input the information about the vehicle...
txtEnterVehicleType = new JTextField();
txtEnterVehicleType.setText("");
txtEnterVehicleType.setBounds(225, 166, 250, 30);
registerNewVehiclePanel.add(txtEnterVehicleType);
txtEnterVehicleType.setColumns(10);
final JTextArea txtrVehicleType = new JTextArea();
txtrVehicleType.setEditable(false);
txtrVehicleType.setBackground(SystemColor.window);
txtrVehicleType.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrVehicleType.setText("Fordonstyp");
txtrVehicleType.setBounds(130, 165, 100, 27);
registerNewVehiclePanel.add(txtrVehicleType);
final JTextField txtEnterNewVehicleLicenseReq; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleLicenseReq= new JTextField();
txtEnterNewVehicleLicenseReq.setText("");
txtEnterNewVehicleLicenseReq.setBounds(225, 212, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleLicenseReq);
txtEnterNewVehicleLicenseReq.setColumns(10);
final JTextArea txtrNewVehicleLicenseReq = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleLicenseReq.setEditable(false);
txtrNewVehicleLicenseReq.setBackground(SystemColor.window);
txtrNewVehicleLicenseReq.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleLicenseReq.setText("Körkortskrav");
txtrNewVehicleLicenseReq.setBounds(130, 207, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleLicenseReq);
final JTextField txtEnterNewVehiclePrice; // Creates search field where you input the information about the vehicle...
txtEnterNewVehiclePrice= new JTextField();
txtEnterNewVehiclePrice.setText("");
txtEnterNewVehiclePrice.setBounds(225, 258, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehiclePrice);
txtEnterNewVehiclePrice.setColumns(10);
final JTextArea txtrNewVehiclePrice = new JTextArea(); // Creates the text next to the input field.
txtrNewVehiclePrice.setEditable(false);
txtrNewVehiclePrice.setBackground(SystemColor.window);
txtrNewVehiclePrice.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehiclePrice.setText("Pris");
txtrNewVehiclePrice.setBounds(130, 249, 100, 27);
registerNewVehiclePanel.add(txtrNewVehiclePrice);
final JTextField txtEnterNewVehicleInfo; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleInfo= new JTextField();
txtEnterNewVehicleInfo.setText("");
txtEnterNewVehicleInfo.setBounds(225, 304, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleInfo);
txtEnterNewVehicleInfo.setColumns(10);
final JTextArea txtrNewVehicleInfo = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleInfo.setEditable(false);
txtrNewVehicleInfo.setBackground(SystemColor.window);
txtrNewVehicleInfo.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleInfo.setText("Beskrivning");
txtrNewVehicleInfo.setBounds(130, 291, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleInfo);
final JTextField txtEnterNewVehicleHasHook; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleHasHook= new JTextField();
txtEnterNewVehicleHasHook.setText("");
txtEnterNewVehicleHasHook.setBounds(225, 350, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleHasHook);
txtEnterNewVehicleHasHook.setColumns(10);
final JTextArea txtrNewVehicleHasHook = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleHasHook.setEditable(false);
txtrNewVehicleHasHook.setBackground(SystemColor.window);
txtrNewVehicleHasHook.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleHasHook.setText("Dragkrok");
txtrNewVehicleHasHook.setBounds(130, 333, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleHasHook);
final JTextField txtEnterNewVehicleExpiryDate; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleExpiryDate= new JTextField();
txtEnterNewVehicleExpiryDate.setText("");
txtEnterNewVehicleExpiryDate.setBounds(225, 396, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleExpiryDate);
txtEnterNewVehicleExpiryDate.setColumns(10);
final JTextArea txtrNewVehicleExpiryDate = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleExpiryDate.setEditable(false);
txtrNewVehicleExpiryDate.setBackground(SystemColor.window);
txtrNewVehicleExpiryDate.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleExpiryDate.setText("Utgångsdatum");
txtrNewVehicleExpiryDate.setBounds(130, 375, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleExpiryDate);
final JTextField txtEnterNewVehicleWarehouse; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleWarehouse= new JTextField();
txtEnterNewVehicleWarehouse.setText("");
txtEnterNewVehicleWarehouse.setBounds(225, 442, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleWarehouse);
txtEnterNewVehicleWarehouse.setColumns(10);
final JTextArea txtrNewVehicleWarehouse = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleWarehouse.setEditable(false);
txtrNewVehicleWarehouse.setBackground(SystemColor.window);
txtrNewVehicleWarehouse.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleWarehouse.setText("Filial/lager");
txtrNewVehicleWarehouse.setBounds(130, 417, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleWarehouse);
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------- Creates the ACCESSORY panel! ---------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel accessoryPanel = new JPanel();
accessoryPanel.setLayout(null);
contentPane.add(accessoryPanel, "accessoryPanel");
JButton btnSearchAccessory = new JButton("Sök tillbehör");
JButton btnNewAccessory = new JButton("Registrera tillbehör");
JButton btnBackAccessory = new JButton("Tillbaka");
btnSearchAccessory.setBounds(200, 225, 300, 75);
btnNewAccessory.setBounds(200, 350, 300, 75);
btnBackAccessory.setBounds(10, 10, 150, 35);
accessoryPanel.add(btnSearchAccessory);
accessoryPanel.add(btnNewAccessory);
accessoryPanel.add(btnBackAccessory);
btnBackAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
btnSearchAccessory.addActionListener(new ActionListener() { // When clicked, go to accessorySearchPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessorySearchPanel");
}
});
btnNewAccessory.addActionListener(new ActionListener() { // When clicked, go to registerNewAccessoryPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "registerNewAccessoryPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- Creates the SEARCH ACCESSORY panel! --------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel accessorySearchPanel = new JPanel();
accessorySearchPanel.setLayout(null);
contentPane.add(accessorySearchPanel, "accessorySearchPanel");
JButton btnSearchForAccessory = new JButton("Sök tillbehör");
JButton btnBackSearchAccessory = new JButton("Tillbaka");
final JButton btnChangeAccessory = new JButton("Ändra tillbehör");
btnChangeAccessory.setVisible(false);
btnSearchForAccessory.setBounds(200, 475, 300, 50);
btnBackSearchAccessory.setBounds(10, 10, 150, 35);
btnChangeAccessory.setBounds(200, 537, 300, 50);
accessorySearchPanel.add(btnSearchForAccessory);
accessorySearchPanel.add(btnBackSearchAccessory);
accessorySearchPanel.add(btnChangeAccessory);
final JTextField fieldEnterProductNbr = new JTextField();
fieldEnterProductNbr.setBounds(225, 421, 250, 30);
accessorySearchPanel.add(fieldEnterProductNbr);
final JTextField fieldSearchAccessoryInfo = new JTextField();
fieldSearchAccessoryInfo.setBounds(225, 283, 250, 50);
accessorySearchPanel.add(fieldSearchAccessoryInfo);
final JTextField fieldSearchAccessoryProductNbr = new JTextField();
fieldSearchAccessoryProductNbr.setBounds(225, 150, 250, 30);
fieldSearchAccessoryProductNbr.setEditable(false);
accessorySearchPanel.add(fieldSearchAccessoryProductNbr);
final JTextField fieldSearchAccessoryPrice = new JTextField();
fieldSearchAccessoryPrice.setBounds(225, 215, 250, 30);
accessorySearchPanel.add(fieldSearchAccessoryPrice);
final JTextField fieldSearchAccessoryName = new JTextField();
fieldSearchAccessoryName.setBounds(225, 83, 250, 30);
accessorySearchPanel.add(fieldSearchAccessoryName);
JTextArea txtrSearchAccessoryName = new JTextArea();
txtrSearchAccessoryName.setEditable(false);
txtrSearchAccessoryName.setText("Namn");
txtrSearchAccessoryName.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryName.setBackground(SystemColor.window);
txtrSearchAccessoryName.setBounds(100, 90, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryName);
JTextArea txtrSearchAccessoryProductNbr = new JTextArea();
txtrSearchAccessoryProductNbr.setText("Produktnummer");
txtrSearchAccessoryProductNbr.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryProductNbr.setEditable(false);
txtrSearchAccessoryProductNbr.setBackground(SystemColor.window);
txtrSearchAccessoryProductNbr.setBounds(100, 157, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryProductNbr);
JTextArea txtrSearchAccessoryPrice = new JTextArea();
txtrSearchAccessoryPrice.setText("Pris");
txtrSearchAccessoryPrice.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryPrice.setEditable(false);
txtrSearchAccessoryPrice.setBackground(SystemColor.window);
txtrSearchAccessoryPrice.setBounds(100, 222, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryPrice);
JTextArea txtrSearchAccessoryInfo = new JTextArea();
txtrSearchAccessoryInfo.setText("Beskrivning");
txtrSearchAccessoryInfo.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryInfo.setEditable(false);
txtrSearchAccessoryInfo.setBackground(SystemColor.window);
txtrSearchAccessoryInfo.setBounds(100, 283, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryInfo);
JTextArea txtrEnterProductNbr = new JTextArea();
txtrEnterProductNbr.setText("Ange produktnummer");
txtrEnterProductNbr.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrEnterProductNbr.setEditable(false);
txtrEnterProductNbr.setBackground(SystemColor.window);
txtrEnterProductNbr.setBounds(43, 428, 145, 23);
accessorySearchPanel.add(txtrEnterProductNbr);
final JButton btnDeleteAccessory = new JButton("Ta bort ");
btnDeleteAccessory.setBounds(200, 599, 300, 50);
accessorySearchPanel.add(btnDeleteAccessory);
btnDeleteAccessory.setVisible(false);
btnSearchForAccessory.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
btnChangeAccessory.setVisible(true);
btnDeleteAccessory.setVisible(true);
int enteredProductNbr = Integer.parseInt(fieldEnterProductNbr.getText()); // Get text from search field...
accessory = controller.findAccessory(enteredProductNbr); // ... find the accessory...
fieldSearchAccessoryName.setText(accessory.getProductName()); // ... and print the text
fieldSearchAccessoryProductNbr.setText(Integer.toString(accessory.getProductNbr())); // ... and print the text
fieldSearchAccessoryPrice.setText(Integer.toString(accessory.getPrice())); // ... and print the text
fieldSearchAccessoryInfo.setText(accessory.getInfoTxt()); // ... and print the text
}
});
btnChangeAccessory.addActionListener(new ActionListener() { // When change button is pressed...
public void actionPerformed(ActionEvent e){
accessory.setProductName(fieldSearchAccessoryName.getText()); // changes the name for an accessory
accessory.setPrice(Integer.parseInt(fieldSearchAccessoryPrice.getText()));//...price
accessory.setInfoTxt(fieldSearchAccessoryInfo.getText());//...info text
}
});
btnDeleteAccessory.addActionListener(new ActionListener() { // When delete button is pressed...
public void actionPerformed(ActionEvent e){
}
});
btnBackSearchAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel and clear fields...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
fieldSearchAccessoryName.setText("");
fieldSearchAccessoryProductNbr.setText("");
fieldSearchAccessoryPrice.setText("");
fieldSearchAccessoryInfo.setText("");
fieldEnterProductNbr.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* --------------------------------------- Creates the NEW ACCESSORY panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel registerNewAccessoryPanel = new JPanel();
contentPane.add(registerNewAccessoryPanel, "registerNewAccessoryPanel");
registerNewAccessoryPanel.setLayout(null);
JButton btnBackRegisterNewAccessory = new JButton("Tillbaka");
JButton btnRegisterNewAccessory = new JButton("Registrera tillbehör");
btnBackRegisterNewAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
btnBackRegisterNewAccessory.setBounds(10, 10, 150, 35);
btnRegisterNewAccessory.setBounds(200, 485, 300, 75);
registerNewAccessoryPanel.add(btnBackRegisterNewAccessory);
registerNewAccessoryPanel.add(btnRegisterNewAccessory);
final JTextField txtEnterAccessoryName; // Creates search field where you input the information about the customer...
txtEnterAccessoryName = new JTextField();
txtEnterAccessoryName.setText("");
txtEnterAccessoryName.setBounds(225, 74, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryName);
txtEnterAccessoryName.setColumns(10);
JTextArea txtrAccessoryName = new JTextArea();
txtrAccessoryName.setEditable(false);
txtrAccessoryName.setBackground(SystemColor.window);
txtrAccessoryName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryName.setText("Namn");
txtrAccessoryName.setBounds(130, 81, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryName);
final JTextField txtEnterAccessoryProductNbr; // Creates search field where you input the information about the customer...
txtEnterAccessoryProductNbr = new JTextField();
txtEnterAccessoryProductNbr.setText("");
txtEnterAccessoryProductNbr.setBounds(225, 144, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryProductNbr);
txtEnterAccessoryProductNbr.setColumns(10);
JTextArea txtrAccessoryProductNbr = new JTextArea();
txtrAccessoryProductNbr.setEditable(false);
txtrAccessoryProductNbr.setBackground(SystemColor.window);
txtrAccessoryProductNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryProductNbr.setText("Produktnummer");
txtrAccessoryProductNbr.setBounds(130, 151, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryProductNbr);
final JTextField txtEnterNewAccessoryPrice; // Creates search field where you input the information about the customer...
txtEnterNewAccessoryPrice= new JTextField();
txtEnterNewAccessoryPrice.setText("");
txtEnterNewAccessoryPrice.setBounds(225, 210, 250, 30);
registerNewAccessoryPanel.add(txtEnterNewAccessoryPrice);
txtEnterNewAccessoryPrice.setColumns(10);
JTextArea txtrNewAccessoryPrice = new JTextArea(); // Creates the text next to the input field.
txtrNewAccessoryPrice.setEditable(false);
txtrNewAccessoryPrice.setBackground(SystemColor.window);
txtrNewAccessoryPrice.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewAccessoryPrice.setText("Pris");
txtrNewAccessoryPrice.setBounds(130, 217, 100, 27);
registerNewAccessoryPanel.add(txtrNewAccessoryPrice);
final JTextField txtEnterAccessoryInfo; // Creates search field where you input the information about the customer...
txtEnterAccessoryInfo = new JTextField();
txtEnterAccessoryInfo.setText("");
txtEnterAccessoryInfo.setBounds(225, 276, 250, 85);
registerNewAccessoryPanel.add(txtEnterAccessoryInfo);
txtEnterAccessoryInfo.setColumns(10);
JTextArea txtrAccessoryInfo = new JTextArea(); // Creates the text next to the input field.
txtrAccessoryInfo.setEditable(false);
txtrAccessoryInfo.setBackground(SystemColor.window);
txtrAccessoryInfo.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryInfo.setText("Beskrivning");
txtrAccessoryInfo.setBounds(130, 283, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryInfo);
btnRegisterNewAccessory.addActionListener(new ActionListener() { // When register button is pressed...
public void actionPerformed(ActionEvent e){
String inputName = txtEnterAccessoryName.getText(); //gets the written name from fields
int inputProductNbr = Integer.parseInt(txtEnterAccessoryProductNbr.getText()); // product number
int inputPrice = Integer.parseInt(txtEnterNewAccessoryPrice.getText());// price
String inputInfo = txtEnterAccessoryInfo.getText(); // information
Controller.createAccessories(inputProductNbr, inputName, inputPrice, inputInfo );
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
/*Standard frame settings. */
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}
| Source-files/GUI.java | import java.awt.Dimension;
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
public class GUI {
private ArrayList<Vehicle> availableVehicles = new ArrayList<Vehicle>(); // These variables need to be accessed from different methods...
private ArrayList<Product> shoppingCart = new ArrayList<Product>();
private Vehicle selectedVehicle;
private String enteredDate;
private Accessory accessory;
private String searchMode = null; // Used for defining search mode when searching for orders...
private Order order;
public GUI() {
final Controller controller = new Controller(); // Initiates link with the controller!
final CardLayout cardLayout = new CardLayout(); // Sets current layout!
/* Creates the frame for the program which has the basic window features.*/
final JFrame frame = new JFrame("CARENTA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,650);
/* Creates a container that contains the panels. */
final Container contentPane = frame.getContentPane();
contentPane.setLayout(cardLayout);
contentPane.setPreferredSize(new Dimension(frame.getWidth(), frame.getHeight()));
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the MAIN panel! -------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel mainPanel = new JPanel(); // Panel...
mainPanel.setLayout(null); // Standard layout...
contentPane.add(mainPanel, "mainPanel"); // Adds the panel mainPanel to the container where "customerPanel" identifies it!
JButton btnCustomer = new JButton("Kund"); // Buttons...
btnCustomer.setBounds(200, 100, 300, 75); // Set locations and set sizes...
mainPanel.add(btnCustomer); // Add them to the panel...
JButton btnOrder = new JButton("Order");
btnOrder.setBounds(200, 225, 300, 75);
mainPanel.add(btnOrder);
JButton btnVehicle = new JButton("Fordon");
btnVehicle.setBounds(200, 350, 300, 75);
mainPanel.add(btnVehicle);
JButton btnAccessory = new JButton("Tillbehör");
btnAccessory.setBounds(200, 475, 300, 75);
mainPanel.add(btnAccessory);
btnCustomer.addActionListener(new ActionListener() { // When clicked, switch to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
btnOrder.addActionListener(new ActionListener() { // When clicked, switch to orderPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "orderPanel");
}
});
btnVehicle.addActionListener(new ActionListener() { // When clicked, switch to vehiclePanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
btnAccessory.addActionListener(new ActionListener() { // When clicked, switch to accessoryPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the CUSTOMER panel! ---------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel customerPanel = new JPanel();
customerPanel.setLayout(null);
contentPane.add(customerPanel, "customerPanel");
JButton btnSearchCustomer = new JButton("Sök kund");
btnSearchCustomer.setBounds(200, 225, 300, 75);
customerPanel.add(btnSearchCustomer);
JButton btnNewCustomer = new JButton("Registrera kund");
btnNewCustomer.setBounds(200, 350, 300, 75);
customerPanel.add(btnNewCustomer);
JButton btnBackCustomer = new JButton("Tillbaka");
btnBackCustomer.setBounds(10, 10, 150, 35);
customerPanel.add(btnBackCustomer);
btnSearchCustomer.addActionListener(new ActionListener() { // When clicked, go to customerSearchPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerSearchPanel");
}
});
btnNewCustomer.addActionListener(new ActionListener() { // When clicked, go to customerSearchPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "chooseCustomerPanel");
}
});
btnBackCustomer.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the EDIT CUSTOMER panel! ------------------------------------------ */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel editCustomerPanel = new JPanel();
editCustomerPanel.setLayout(null);
contentPane.add(editCustomerPanel, "editCustomerPanel");
JButton btnBackEditCustomer = new JButton("Tillbaka");
btnBackEditCustomer.setBounds(10, 10, 100, 25);
editCustomerPanel.add(btnBackEditCustomer);
final JTextField txtEditPersonalNumber; // Creates search field where you input the information about the customer...
txtEditPersonalNumber= new JTextField();
txtEditPersonalNumber.setText("");
txtEditPersonalNumber.setBounds(175, 150, 250, 30);
editCustomerPanel.add(txtEditPersonalNumber);
txtEditPersonalNumber.setColumns(10);
final JTextField txtEditFirstName; // Creates search field where you input the information about the customer...
txtEditFirstName = new JTextField();
txtEditFirstName.setText("");
txtEditFirstName.setBounds(175, 50, 250, 30);
editCustomerPanel.add(txtEditFirstName);
txtEditFirstName.setColumns(10);
final JTextField txtEditLastName; // Creates search field where you input the information about the customer...
txtEditLastName = new JTextField();
txtEditLastName.setText("");
txtEditLastName.setBounds(175, 100, 250, 30);
editCustomerPanel.add(txtEditLastName);
txtEditLastName.setColumns(10);
final JTextField txtEditAddress; // Creates search field where you input the information about the customer...
txtEditAddress = new JTextField();
txtEditAddress.setText("");
txtEditAddress.setBounds(175, 200, 250, 30);
editCustomerPanel.add(txtEditAddress);
txtEditFirstName.setColumns(10);
final JTextField txtEditCity; // Creates search field where you input the information about the customer...
txtEditCity = new JTextField();
txtEditCity.setText("");
txtEditCity.setBounds(175, 250, 250, 30);
editCustomerPanel.add(txtEditCity);
txtEditCity.setColumns(10);
final JTextField txtEditAreaCode; // Creates search field where you input the information about the customer...
txtEditAreaCode = new JTextField();
txtEditAreaCode.setText("");
txtEditAreaCode.setBounds(175, 300, 250, 30);
editCustomerPanel.add(txtEditAreaCode);
txtEditAreaCode.setColumns(10);
final JTextField txtEditPhoneNumber; // Creates search field where you input the information about the customer...
txtEditPhoneNumber = new JTextField();
txtEditPhoneNumber.setText("");
txtEditPhoneNumber.setBounds(175, 350, 250, 30);
editCustomerPanel.add(txtEditPhoneNumber);
txtEditPhoneNumber.setColumns(10);
final JTextField txtEditEMail; // Creates search field where you input the information about the customer...
txtEditEMail = new JTextField();
txtEditEMail.setText("");
txtEditEMail.setBounds(175, 400, 250, 30);
editCustomerPanel.add(txtEditEMail);
txtEditEMail.setColumns(10);
JTextArea txtrEditPersonalNbr = new JTextArea(); // Creates the text next to the input field.
txtrEditPersonalNbr.setBackground(SystemColor.menu);
txtrEditPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditPersonalNbr.setText("Personnummer");
txtrEditPersonalNbr.setBounds(75, 155, 100, 27);
editCustomerPanel.add(txtrEditPersonalNbr);
txtrEditPersonalNbr.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditFirstName = new JTextArea(); // Creates the text next to the input field.
txtrEditFirstName.setBackground(SystemColor.menu);
txtrEditFirstName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditFirstName.setText("Förnamn");
txtrEditFirstName.setBounds(75, 55, 100, 27);
editCustomerPanel.add(txtrEditFirstName);
txtrEditFirstName.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditLastName = new JTextArea(); // Creates the text next to the input field.
txtrEditLastName.setBackground(SystemColor.menu);
txtrEditLastName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditLastName.setText("Efternamn");
txtrEditLastName.setBounds(75, 105, 100, 27);
editCustomerPanel.add(txtrEditLastName);
txtrEditLastName.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditAddress = new JTextArea(); // Creates the text next to the input field.
txtrEditAddress.setBackground(SystemColor.menu);
txtrEditAddress.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditAddress.setText("Gatuadress");
txtrEditAddress.setBounds(75, 205, 100, 27);
editCustomerPanel.add(txtrEditAddress);
txtrEditAddress.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditCity = new JTextArea(); // Creates the text next to the input field.
txtrEditCity.setBackground(SystemColor.menu);
txtrEditCity.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditCity.setText("Stad");
txtrEditCity.setBounds(75, 255, 100, 27);
editCustomerPanel.add(txtrEditCity);
txtrEditCity.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditAreaCode = new JTextArea(); // Creates the text next to the input field.
txtrEditAreaCode.setBackground(SystemColor.menu);
txtrEditAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditAreaCode.setText("Postnummer");
txtrEditAreaCode.setBounds(75, 305, 100, 27);
editCustomerPanel.add(txtrEditAreaCode);
txtrEditAreaCode.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditPhoneNumber = new JTextArea(); // Creates the text next to the input field.
txtrEditPhoneNumber.setBackground(SystemColor.menu);
txtrEditPhoneNumber.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditPhoneNumber.setText("Telefonnummer");
txtrEditPhoneNumber.setBounds(75, 355, 100, 27);
editCustomerPanel.add(txtrEditPhoneNumber);
txtrEditPhoneNumber.setEditable(false); //Set the JTextArea uneditable.
JTextArea txtrEditEMail = new JTextArea(); // Creates the text next to the input field.
txtrEditEMail.setBackground(SystemColor.menu);
txtrEditEMail.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrEditEMail.setText("E-mail");
txtrEditEMail.setBounds(75, 405, 100, 27);
editCustomerPanel.add(txtrEditEMail);
txtrEditEMail.setEditable(false); //Set the JTextArea uneditable.
btnBackEditCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
txtEditPersonalNumber.setText("");
txtEditFirstName.setText("");
txtEditLastName.setText("");
txtEditAddress.setText("");
txtEditCity.setText("");
txtEditAreaCode.setText("");
txtEditPhoneNumber.setText("");
txtEditEMail.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the CUSTOMER SEARCH panel! --------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel customerSearchPanel = new JPanel();
customerSearchPanel.setLayout(null);
contentPane.add(customerSearchPanel, "customerSearchPanel");
JButton btnSearchForCustomer = new JButton("Sök kund");
btnSearchForCustomer.setBounds(200, 475, 300, 75);
customerSearchPanel.add(btnSearchForCustomer);
JButton btnBackSearchCustomer = new JButton("Tillbaka");
btnBackSearchCustomer.setBounds(10, 10, 150, 35);
customerSearchPanel.add(btnBackSearchCustomer);
JTextArea txtrPersonalNbr = new JTextArea();
txtrPersonalNbr.setBounds(75, 204, 110, 19);
txtrPersonalNbr.setText("Personnummer:");
txtrPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrPersonalNbr.setBackground(SystemColor.window);
txtrPersonalNbr.setEditable(false);
customerSearchPanel.add(txtrPersonalNbr);
JTextArea txtrCustomerNbr = new JTextArea();
txtrCustomerNbr.setBounds(93, 290, 110, 19);
txtrCustomerNbr.setText("Kundnummer:");
txtrCustomerNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrCustomerNbr.setBackground(SystemColor.window);
txtrCustomerNbr.setEditable(false);
customerSearchPanel.add(txtrCustomerNbr);
final JTextField txtEnterCustomerNbr;
txtEnterCustomerNbr = new JTextField();
txtEnterCustomerNbr.setText("");
txtEnterCustomerNbr.setBounds(200, 285, 300, 30);
customerSearchPanel.add(txtEnterCustomerNbr);
txtEnterCustomerNbr.setColumns(10);
final JTextField txtrEnterPersonalNbr;
txtrEnterPersonalNbr = new JTextField();
txtrEnterPersonalNbr.setText("");
txtrEnterPersonalNbr.setBounds(200, 200, 300, 30);
customerSearchPanel.add(txtrEnterPersonalNbr);
txtEnterCustomerNbr.setColumns(10);
btnSearchForCustomer.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
String enteredCustomerNbr = txtEnterCustomerNbr.getText(); // Get text from search field...
Customer customer = controller.findCustomer(enteredCustomerNbr);
txtEditPersonalNumber.setText("balle");
txtEditFirstName.setText("balle");
txtEditLastName.setText("bella");
txtEditAddress.setText(customer.getAdress());
txtEditCity.setText(customer.getCity());
txtEditAreaCode.setText(customer.getAreaCode());
txtEditPhoneNumber.setText(customer.getPhoneNbr());
txtEditEMail.setText(customer.getMailAdress());
cardLayout.show(contentPane, "editCustomerPanel");
txtEnterCustomerNbr.setText(""); // Resets the JTextField to be empty for the next registration.
}
});
btnBackSearchCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
txtEnterCustomerNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtrEnterPersonalNbr.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- ------*/
/* ----------------------------------------- Creates the CHOOSE WICH CUSTOMER panel! --------------------------------------- */
/* ------------------------------------------------------------------------------------------------------------------------ */
final JPanel chooseCustomerPanel = new JPanel();
chooseCustomerPanel.setLayout(null);
contentPane.add(chooseCustomerPanel, "chooseCustomerPanel");
JButton btnBackChooseCustomer = new JButton("Tillbaka");
btnBackChooseCustomer.setBounds(10, 10, 150, 35);
chooseCustomerPanel.add(btnBackChooseCustomer);
JButton btnPrivateCustomer = new JButton("Privatkund");
btnPrivateCustomer.setBounds(200, 225, 300, 75);
chooseCustomerPanel.add(btnPrivateCustomer);
JButton btnCompanyCustomer = new JButton("Företagskund");
btnCompanyCustomer.setBounds(200, 350, 300, 75);
chooseCustomerPanel.add(btnCompanyCustomer);
btnBackChooseCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "customerPanel");
}
});
btnPrivateCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newPrivateCustomerPanel");
}
});
btnCompanyCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newCompanyCustomerPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the NEW PRIVATE CUSTOMER panel! ------------------------------------------ */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel newPrivateCustomerPanel = new JPanel();
contentPane.add(newPrivateCustomerPanel, "newPrivateCustomerPanel");
newPrivateCustomerPanel.setLayout(null);
JButton btnBackNewPrivateCustomer = new JButton("Tillbaka");
JButton btnRegisterPrivateNewCustomer = new JButton("Registrera kund");
newPrivateCustomerPanel.add(btnBackNewPrivateCustomer);
newPrivateCustomerPanel.add(btnRegisterPrivateNewCustomer);
btnBackNewPrivateCustomer.setBounds(10, 10, 150, 35);
btnRegisterPrivateNewCustomer.setBounds(200, 555, 300, 75);
JTextArea textPersonalNbr = new JTextArea(); // Creates the text next to the input field.
textPersonalNbr.setBackground(SystemColor.window);
textPersonalNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
textPersonalNbr.setText("Personnummer:");
textPersonalNbr.setBounds(90, 100, 113, 19);
newPrivateCustomerPanel.add(textPersonalNbr);
textPersonalNbr.setEditable(false);
JTextArea textFirstName = new JTextArea();
textFirstName.setText("Förnamn:");
textFirstName.setFont(new Font("Tahoma", Font.PLAIN, 15));
textFirstName.setEditable(false);
textFirstName.setBackground(SystemColor.window);
textFirstName.setBounds(132, 150, 71, 16);
newPrivateCustomerPanel.add(textFirstName);
JTextArea textLastName = new JTextArea();
textLastName.setText("Efternamn:");
textLastName.setFont(new Font("Tahoma", Font.PLAIN, 15));
textLastName.setEditable(false);
textLastName.setBackground(SystemColor.window);
textLastName.setBounds(122, 200, 81, 16);
newPrivateCustomerPanel.add(textLastName);
JTextArea textAdress = new JTextArea();
textAdress.setText("Adress:");
textAdress.setFont(new Font("Tahoma", Font.PLAIN, 15));
textAdress.setEditable(false);
textAdress.setBackground(SystemColor.window);
textAdress.setBounds(145, 250, 58, 16);
newPrivateCustomerPanel.add(textAdress);
JTextArea txtrCity = new JTextArea();
txtrCity.setText("Stad:");
txtrCity.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrCity.setEditable(false);
txtrCity.setBackground(SystemColor.window);
txtrCity.setBounds(158, 300, 45, 16);
newPrivateCustomerPanel.add(txtrCity);
JTextArea txtrAreaCode = new JTextArea();
txtrAreaCode.setText("Postkod:");
txtrAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrAreaCode.setEditable(false);
txtrAreaCode.setBackground(SystemColor.window);
txtrAreaCode.setBounds(137, 350, 66, 16);
newPrivateCustomerPanel.add(txtrAreaCode);
JTextArea txtrTelephoneNbr = new JTextArea();
txtrTelephoneNbr.setText("Telefonnummer:");
txtrTelephoneNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrTelephoneNbr.setEditable(false);
txtrTelephoneNbr.setBackground(SystemColor.window);
txtrTelephoneNbr.setBounds(82, 400, 121, 16);
newPrivateCustomerPanel.add(txtrTelephoneNbr);
JTextArea txtrMail = new JTextArea();
txtrMail.setText("E-mail-adress:");
txtrMail.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrMail.setEditable(false);
txtrMail.setBackground(SystemColor.window);
txtrMail.setBounds(90, 450, 113, 16);
newPrivateCustomerPanel.add(txtrMail);
JTextArea txtrDiscountLevel = new JTextArea();
txtrDiscountLevel.setText("Rabatt:");
txtrDiscountLevel.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrDiscountLevel.setEditable(false);
txtrDiscountLevel.setBackground(SystemColor.window);
txtrDiscountLevel.setBounds(137, 499, 66, 16);
newPrivateCustomerPanel.add(txtrDiscountLevel);
final JTextField txtEnterPersonalNbr;
txtEnterPersonalNbr = new JTextField();
txtEnterPersonalNbr.setText(txtEnterPersonalNbr.getText()); ;
txtEnterPersonalNbr.setBounds(200, 95, 300, 30);
newPrivateCustomerPanel.add(txtEnterPersonalNbr);
txtEnterPersonalNbr.setColumns(10);
final JTextField txtEnterFirstName;
txtEnterFirstName = new JTextField();
txtEnterFirstName.setText("");
txtEnterFirstName.setBounds(200, 145, 300, 30);
newPrivateCustomerPanel.add(txtEnterFirstName);
txtEnterFirstName.setColumns(10);
final JTextField txtEnterLastName;
txtEnterLastName= new JTextField();
txtEnterLastName.setText("");
txtEnterLastName.setBounds(200, 195, 300, 30);
newPrivateCustomerPanel.add(txtEnterLastName);
txtEnterLastName.setColumns(10);
final JTextField txtEnterAddress;
txtEnterAddress = new JTextField();
txtEnterAddress.setText("");
txtEnterAddress.setBounds(200, 245, 300, 30);
newPrivateCustomerPanel.add(txtEnterAddress);
txtEnterPersonalNbr.setColumns(10);
final JTextField txtEnterCity;
txtEnterCity = new JTextField();
txtEnterCity.setText("");
txtEnterCity.setBounds(200, 295, 300, 30);
newPrivateCustomerPanel.add(txtEnterCity);
txtEnterCity.setColumns(10);
final JTextField txtEnterAreaCode;
txtEnterAreaCode = new JTextField();
txtEnterAreaCode.setText("");
txtEnterAreaCode.setBounds(200, 345, 300, 30);
newPrivateCustomerPanel.add(txtEnterAreaCode);
txtEnterAreaCode.setColumns(10);
final JTextField txtEnterTelephoneNbr;
txtEnterTelephoneNbr = new JTextField();
txtEnterTelephoneNbr.setText("");
txtEnterTelephoneNbr.setBounds(200, 395, 300, 30);
newPrivateCustomerPanel.add(txtEnterTelephoneNbr);
txtEnterTelephoneNbr.setColumns(10);
final JTextField txtEnterMail;
txtEnterMail = new JTextField();
txtEnterMail.setText("");
txtEnterMail.setBounds(200, 445, 300, 30);
newPrivateCustomerPanel.add(txtEnterMail);
txtEnterMail.setColumns(10);
final JTextField txtEnterDiscountLevel;
txtEnterDiscountLevel = new JTextField();
txtEnterDiscountLevel.setText("");
txtEnterDiscountLevel.setBounds(200, 495, 300, 30);
newPrivateCustomerPanel.add(txtEnterDiscountLevel);
txtEnterDiscountLevel.setColumns(10);
btnBackNewPrivateCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "chooseCustomerPanel");
txtEnterPersonalNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtEnterFirstName.setText("");
txtEnterLastName.setText("");
txtEnterAddress.setText("");
txtEnterCity.setText("");
txtEnterAreaCode.setText("");
txtEnterTelephoneNbr.setText("");
txtEnterMail.setText("");
txtEnterDiscountLevel.setText("");
}
});
btnRegisterPrivateNewCustomer.addActionListener(new ActionListener() { // When clicked, new customer i registered!
public void actionPerformed(ActionEvent e) {
String txtEnteredPersonalNbr = txtEnterPersonalNbr.getText();
String txtEnteredFirstName = txtEnterFirstName.getText();
String txtEnteredLastName = txtEnterLastName.getText();
String txtEnteredAddress = txtEnterAddress.getText();
String txtEnteredCity = txtEnterCity.getText();
String txtEnteredAreaCode = txtEnterAreaCode.getText();
String txtEnteredTelephoneNbr = txtEnterTelephoneNbr.getText();
String txtEnteredMail = txtEnterMail.getText();
controller.createPrivateCustomer(txtEnteredPersonalNbr, txtEnteredFirstName, txtEnteredLastName,
txtEnteredAddress, txtEnteredCity, txtEnteredAreaCode, txtEnteredTelephoneNbr, txtEnteredMail);
cardLayout.show(contentPane, "customerPanel"); // ... and return to the customer menu!
JOptionPane.showMessageDialog(null, "Kunden är registrerad!"); // Tell the user that the customer has been registered!
txtEnterPersonalNbr.setText("");// Resets the JTextField to be empty for the next registration.
txtEnterFirstName.setText("");
txtEnterLastName.setText("");
txtEnterAddress.setText("");
txtEnterCity.setText("");
txtEnterAreaCode.setText("");
txtEnterTelephoneNbr.setText("");
txtEnterMail.setText("");
txtEnterDiscountLevel.setText("");
}
});
/* ---------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------- Creates the NEW COMPANY CUSTOMER panel! ------------------------------------- */
/* ------------------------------------------------------------------------------------------------------------------------ */
final JPanel newCompanyCustomerPanel = new JPanel();
newCompanyCustomerPanel.setLayout(null);
contentPane.add(newCompanyCustomerPanel, "newCompanyCustomerPanel");
JButton btnBackNewCompanyCustomer = new JButton("Tillbaka");
btnBackNewCompanyCustomer.setBounds(10, 10, 150, 35);
newCompanyCustomerPanel.add(btnBackNewCompanyCustomer);
JButton btnRegisterNewCompanyCustomer = new JButton("Registrera kund");
btnRegisterNewCompanyCustomer.setBounds(200, 550, 300, 75);
newCompanyCustomerPanel.add(btnRegisterNewCompanyCustomer);
JTextArea textCompanyOrgNbr = new JTextArea();
textCompanyOrgNbr.setText("Organisationsnummer:");
textCompanyOrgNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyOrgNbr.setEditable(false);
textCompanyOrgNbr.setBackground(SystemColor.window);
textCompanyOrgNbr.setBounds(32, 100, 150, 16);
newCompanyCustomerPanel.add(textCompanyOrgNbr);
JTextArea textCompanyName = new JTextArea();
textCompanyName.setText("Företagsnamn:");
textCompanyName.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyName.setEditable(false);
textCompanyName.setBackground(SystemColor.window);
textCompanyName.setBounds(80, 150, 102, 16);
newCompanyCustomerPanel.add(textCompanyName);
JTextArea textCompanyAdress = new JTextArea();
textCompanyAdress.setText("Adress:");
textCompanyAdress.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyAdress.setEditable(false);
textCompanyAdress.setBackground(SystemColor.window);
textCompanyAdress.setBounds(129, 200, 53, 16);
newCompanyCustomerPanel.add(textCompanyAdress);
JTextArea textCompanyCity = new JTextArea();
textCompanyCity.setText("Stad:");
textCompanyCity.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyCity.setEditable(false);
textCompanyCity.setBackground(SystemColor.window);
textCompanyCity.setBounds(135, 250, 47, 16);
newCompanyCustomerPanel.add(textCompanyCity);
JTextArea textCompanyAreaCode = new JTextArea();
textCompanyAreaCode.setText("Postnummer:");
textCompanyAreaCode.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyAreaCode.setEditable(false);
textCompanyAreaCode.setBackground(SystemColor.window);
textCompanyAreaCode.setBounds(90, 300, 92, 16);
newCompanyCustomerPanel.add(textCompanyAreaCode);
JTextArea textCompanyPhoneNbr = new JTextArea();
textCompanyPhoneNbr.setText("Telefonnummer:");
textCompanyPhoneNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyPhoneNbr.setEditable(false);
textCompanyPhoneNbr.setBackground(SystemColor.window);
textCompanyPhoneNbr.setBounds(69, 350, 113, 16);
newCompanyCustomerPanel.add(textCompanyPhoneNbr);
JTextArea textCompanyMailAdress = new JTextArea();
textCompanyMailAdress.setText("E-mail adress:");
textCompanyMailAdress.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyMailAdress.setEditable(false);
textCompanyMailAdress.setBackground(SystemColor.window);
textCompanyMailAdress.setBounds(80, 400, 102, 16);
newCompanyCustomerPanel.add(textCompanyMailAdress);
JTextArea textCompanyDiscountLevel = new JTextArea();
textCompanyDiscountLevel.setText("Rabatt:");
textCompanyDiscountLevel.setFont(new Font("Tahoma", Font.PLAIN, 15));
textCompanyDiscountLevel.setEditable(false);
textCompanyDiscountLevel.setBackground(SystemColor.window);
textCompanyDiscountLevel.setBounds(129, 450, 53, 16);
newCompanyCustomerPanel.add(textCompanyDiscountLevel);
final JTextField txtEnterCompanyOrgNbr;
txtEnterCompanyOrgNbr = new JTextField();
txtEnterCompanyOrgNbr.setText("");
txtEnterCompanyOrgNbr.setBounds(200, 95, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyOrgNbr);
txtEnterCompanyOrgNbr.setColumns(10);
final JTextField txtEnterCompanyName;
txtEnterCompanyName = new JTextField();
txtEnterCompanyName.setText("");
txtEnterCompanyName.setBounds(200, 145, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyName);
txtEnterCompanyName.setColumns(10);
final JTextField txtEnterCompanyAdress;
txtEnterCompanyAdress = new JTextField();
txtEnterCompanyAdress.setText("");
txtEnterCompanyAdress.setBounds(200, 195, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyAdress);
txtEnterCompanyAdress.setColumns(10);
final JTextField txtEnterCompanyCity;
txtEnterCompanyCity = new JTextField();
txtEnterCompanyCity.setText("");
txtEnterCompanyCity.setBounds(200, 245, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyCity);
txtEnterCompanyCity.setColumns(10);
final JTextField txtEnterCompanyAreaCode;
txtEnterCompanyAreaCode = new JTextField();
txtEnterCompanyAreaCode.setText("");
txtEnterCompanyAreaCode.setBounds(200, 295, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyAreaCode);
txtEnterCompanyAreaCode.setColumns(10);
final JTextField txtEnterCompanyPhoneNbr;
txtEnterCompanyPhoneNbr = new JTextField();
txtEnterCompanyPhoneNbr.setText("");
txtEnterCompanyPhoneNbr.setBounds(200, 345, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyPhoneNbr);
txtEnterCompanyPhoneNbr.setColumns(10);
final JTextField txtEnterCompanyMailAdress;
txtEnterCompanyMailAdress = new JTextField();
txtEnterCompanyMailAdress.setText("");
txtEnterCompanyMailAdress.setBounds(200, 395, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyMailAdress);
txtEnterCompanyMailAdress.setColumns(10);
final JTextField txtEnterCompanyDiscountLevel;
txtEnterCompanyDiscountLevel = new JTextField();
txtEnterCompanyDiscountLevel.setText("");
txtEnterCompanyDiscountLevel.setBounds(200, 445, 300, 30);
newCompanyCustomerPanel.add(txtEnterCompanyDiscountLevel);
txtEnterCompanyDiscountLevel.setColumns(10);
btnRegisterNewCompanyCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
String txtEnteredCompanyOrgNbr = txtEnterCompanyOrgNbr.getText();
String txtEnteredCompanyName = txtEnterCompanyName.getText();
String txtEnteredCompanyAdress = txtEnterCompanyAdress.getText();
String txtEnteredCompanyCity = txtEnterCompanyCity.getText();
String txtEnteredCompanyAreaCode = txtEnterCompanyAreaCode.getText();
String txtEnteredCompanyPhoneNbr = txtEnterCompanyPhoneNbr.getText();
String txtEnteredCompanyMailAdress = txtEnterCompanyMailAdress.getText();
controller.createCompanyCustomer(txtEnteredCompanyOrgNbr, txtEnteredCompanyName, txtEnteredCompanyAdress, txtEnteredCompanyCity,
txtEnteredCompanyAreaCode, txtEnteredCompanyPhoneNbr, txtEnteredCompanyMailAdress);
cardLayout.show(contentPane, "customerPanel");
JOptionPane.showMessageDialog(null, "Kunden är registrerad!"); // Tell the user that the customer has been registered!
txtEnterCompanyOrgNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtEnterCompanyName.setText("");
txtEnterCompanyAdress.setText("");
txtEnterCompanyCity.setText("");
txtEnterCompanyAreaCode.setText("");
txtEnterCompanyPhoneNbr.setText("");
txtEnterCompanyMailAdress.setText("");
txtEnterCompanyDiscountLevel.setText("");
}
});
btnBackNewCompanyCustomer.addActionListener(new ActionListener() { // When clicked, go back to customerPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "chooseCustomerPanel");
txtEnterCompanyOrgNbr.setText(""); // Resets the JTextField to be empty for the next registration.
txtEnterCompanyName.setText("");
txtEnterCompanyAdress.setText("");
txtEnterCompanyCity.setText("");
txtEnterCompanyAreaCode.setText("");
txtEnterCompanyPhoneNbr.setText("");
txtEnterCompanyMailAdress.setText("");
txtEnterCompanyDiscountLevel.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the ORDER panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel orderPanel = new JPanel();
orderPanel.setLayout(null);
contentPane.add(orderPanel, "orderPanel");
JButton btnSearchOrder = new JButton("Sök order");
btnSearchOrder.setBounds(200, 225, 300, 75);
orderPanel.add(btnSearchOrder);
JButton btnNewOrder = new JButton("Registrera order");
btnNewOrder.setBounds(200, 350, 300, 75);
orderPanel.add(btnNewOrder);
JButton btnBackOrder = new JButton("Tillbaka");
btnBackOrder.setBounds(10, 10, 150, 35);
orderPanel.add(btnBackOrder);
btnNewOrder.addActionListener(new ActionListener() { // When clicked, go back to new order panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "newOrderPanel");
}
});
btnSearchOrder.addActionListener(new ActionListener() { // When clicked, go to search order panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "searchOrderPanel");
}
});
btnBackOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- Creates the SEARCH ORDER panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel searchOrderPanel = new JPanel();
searchOrderPanel.setLayout(null);
contentPane.add(searchOrderPanel, "searchOrderPanel");
/* ---- Buttons... ---- */
final JButton btnSearchSpecificOrder = new JButton("Sök specifik order"); // Buttons...
btnSearchSpecificOrder.setBounds(200, 100, 300, 75); // Set locations and set sizes...
searchOrderPanel.add(btnSearchSpecificOrder); // Add them to the panel...
final JButton btnSearchDatesOrders = new JButton("Sök ordrar utförda ett visst datum");
btnSearchDatesOrders.setBounds(200, 225, 300, 75);
searchOrderPanel.add(btnSearchDatesOrders);
final JButton btnSearchCustomerOrders = new JButton("Sök ordrar utförda av specifik kund");
btnSearchCustomerOrders.setBounds(200, 475, 300, 75);
searchOrderPanel.add(btnSearchCustomerOrders);
final JButton btnSearchProductOrders = new JButton("Sök ordrar innehållandes en viss produkt");
btnSearchProductOrders.setBounds(200, 350, 300, 75);
searchOrderPanel.add(btnSearchProductOrders);
final JButton btnCommitSearch = new JButton("Sök"); // Button used for the actual search!
btnCommitSearch.setBounds(200, 451, 300, 75);
searchOrderPanel.add(btnCommitSearch);
btnCommitSearch.setVisible(false);
final JButton btnRemoveOrder = new JButton("Ta bort order"); // Button used for the actual search!
btnRemoveOrder.setBounds(200, 539, 300, 75);
searchOrderPanel.add(btnRemoveOrder);
btnRemoveOrder.setVisible(false);
final JButton btnBackSearchOrder = new JButton("Tillbaka");
btnBackSearchOrder.setBounds(10, 10, 150, 35);
searchOrderPanel.add(btnBackSearchOrder);
/* ----- TextField... ------ */
final JTextField inputSearchData;
inputSearchData = new JTextField();
inputSearchData.setText("");
inputSearchData.setBounds(200, 308, 300, 30);
searchOrderPanel.add(inputSearchData);
inputSearchData.setColumns(10);
inputSearchData.setVisible(false);
inputSearchData.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
inputSearchData.setText("");
}
});
/* ----- Tabulars... ---- */
String searchColumn[] = {"Ordernummer", "Datum", "Kundnummer", "Totalt pris"};
final DefaultTableModel searchModel = new DefaultTableModel(searchColumn, 0);
final JTable searchTable = new JTable(searchModel);
searchTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchTable.setVisible(false);
final JScrollPane searchScrollPane = new JScrollPane();
searchScrollPane.setLocation(10, 55);
searchScrollPane.setSize(680, 365);
searchOrderPanel.add(searchScrollPane);
searchScrollPane.setVisible(false);
final JTextPane specificSearchPane = new JTextPane();
specificSearchPane.setBounds(10, 55, 680, 365);
searchOrderPanel.add(specificSearchPane);
specificSearchPane.setVisible(false);
/* ---- Action listeners... */
btnSearchSpecificOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "specific";
inputSearchData.setText("Ange ordernummer");
}
});
btnSearchDatesOrders.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "date";
inputSearchData.setText("Ange ett datum på formen YYYY/MM/DD");
}
});
btnSearchCustomerOrders.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "customer";
inputSearchData.setText("Ange kundnummer");
}
});
btnSearchProductOrders.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnSearchSpecificOrder.setVisible(false);
btnSearchDatesOrders.setVisible(false);
btnSearchCustomerOrders.setVisible(false);
btnSearchProductOrders.setVisible(false);
btnCommitSearch.setVisible(true);
inputSearchData.setVisible(true);
searchMode = "product";
inputSearchData.setText("Ange produktnamn");
}
});
btnCommitSearch.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnRemoveOrder.setVisible(true);
Order order;
ArrayList<Order> orderRegistry = controller.orderRegistry.getOrders();
String searchVariable = inputSearchData.getText();
inputSearchData.setVisible(false);
if(searchMode == "specific") {
order = controller.orderRegistry.getOrder(Integer.parseInt(searchVariable));
specificSearchPane.setText("Ordernummer: " + order.getOrderNbr() + "\n \n" +
"Beställare (kundnummer): " + order.getCustomer().getCustomerNbr() + "\n \n" +
"Produkter: " + "\n \n" +
"Totalt pris:" + order.getTotalPrice() + "\n \n" +
"Datum då ordern utfärdades: " + order.getLatestUpdate());
specificSearchPane.setVisible(true);
}
if(searchMode == "date") {
for(int a = 0; a < orderRegistry.size(); a++) {
order = orderRegistry.get(a);
if(searchVariable.equals(order.getLatestUpdate())) {
searchModel.addRow(new Object[]{order.getOrderNbr(), order.getLatestUpdate(), order.getCustomer().getCustomerNbr(), order.getTotalPrice()});
}
}
searchScrollPane.setViewportView(searchTable);
searchScrollPane.setVisible(true);
searchTable.setVisible(true);
}
if(searchMode == "customer") {
for(int a = 0; a < orderRegistry.size(); a++) {
order = orderRegistry.get(a);
if(searchVariable.equals(order.getCustomer().toString())) {
searchModel.addRow(new Object[]{order.getOrderNbr(), order.getLatestUpdate(), order.getCustomer().getCustomerNbr(), order.getTotalPrice()});
}
}
searchScrollPane.setViewportView(searchTable);
searchScrollPane.setVisible(true);
searchTable.setVisible(true);
}
if(searchMode == "product") {
ArrayList<Product> products;
Product product;
for(int a = 0; a < orderRegistry.size(); a++) {
order = orderRegistry.get(a);
products = order.getProducts();
for(int b = 0; b < products.size(); b++ ) {
product = products.get(a);
if(searchVariable.equals(product.getProductName())) {
searchModel.addRow(new Object[]{order.getOrderNbr(), order.getLatestUpdate(), order.getCustomer().getCustomerNbr(), order.getTotalPrice()});
}
}
}
searchScrollPane.setViewportView(searchTable);
searchScrollPane.setVisible(true);
searchTable.setVisible(true);
}
}
});
btnRemoveOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
int goRemoveSelection = JOptionPane.showConfirmDialog(null, "Du håller på att ta bort ordern, vill du det?",
"Varning!", JOptionPane.YES_OPTION);
if(goRemoveSelection == 1) { // If the user doesn't want to cancel the order...
// ... do nothing!
}
else if(goRemoveSelection == 0) { // If the user wants to cancel the order...
controller.orderRegistry.removeOrder(order.getOrderNbr() - 1);
order = null;
btnCommitSearch.setVisible(false);
btnRemoveOrder.setVisible(false);
inputSearchData.setVisible(false);
searchTable.setVisible(false);
searchScrollPane.setVisible(false);
specificSearchPane.setVisible(false);
btnSearchSpecificOrder.setVisible(true);
btnSearchDatesOrders.setVisible(true);
btnSearchCustomerOrders.setVisible(true);
btnSearchProductOrders.setVisible(true);
searchMode = null;
specificSearchPane.setText("");
cardLayout.show(contentPane, "orderPanel");
}
}
});
btnBackSearchOrder.addActionListener(new ActionListener() { // When clicked, go back to main panel...
public void actionPerformed(ActionEvent e) {
btnCommitSearch.setVisible(false);
btnRemoveOrder.setVisible(false);
inputSearchData.setVisible(false);
searchTable.setVisible(false);
searchScrollPane.setVisible(false);
btnSearchSpecificOrder.setVisible(true);
btnSearchDatesOrders.setVisible(true);
btnSearchCustomerOrders.setVisible(true);
btnSearchProductOrders.setVisible(true);
cardLayout.show(contentPane, "orderPanel");
order = null;
searchMode = null;
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ------------------------------------------- Creates the NEW ORDER panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel newOrderPanel = new JPanel();
newOrderPanel.setLayout(null);
contentPane.add(newOrderPanel, "newOrderPanel");
/* ------- Buttons... ------- */
final JButton btnEnteredDate = new JButton("Gå vidare");
btnEnteredDate.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnEnteredDate);
final JButton btnChooseVehicle = new JButton("Välj bil");
btnChooseVehicle.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnChooseVehicle);
btnChooseVehicle.setVisible(false);
final JButton btnChooseAccessory = new JButton("Gå vidare");
btnChooseAccessory.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnChooseAccessory);
btnChooseAccessory.setVisible(false);
final JButton btnMoreAccessory = new JButton("Lägg till ytterligare tillbehör");
btnMoreAccessory.setBounds(200, 440, 300, 75);
newOrderPanel.add(btnMoreAccessory);
btnMoreAccessory.setVisible(false);
final JButton btnViewOrder = new JButton("Granska order");
btnViewOrder.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnViewOrder);
btnViewOrder.setVisible(false);
final JButton btnConfirmOrder = new JButton("Slutför order");
btnConfirmOrder.setBounds(200, 540, 300, 75);
newOrderPanel.add(btnConfirmOrder);
btnConfirmOrder.setVisible(false);
final JButton btnBackNewOrder = new JButton("Tillbaka");
btnBackNewOrder.setBounds(10, 10, 150, 35);
newOrderPanel.add(btnBackNewOrder);
/* ------- Textfields... ------- */
final JTextField txtEnteredDate;
txtEnteredDate = new JTextField();
txtEnteredDate.setText("YYYY/MM/DD");
txtEnteredDate.setBounds(200, 178, 300, 30);
newOrderPanel.add(txtEnteredDate);
txtEnteredDate.setColumns(10);
txtEnteredDate.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
txtEnteredDate.setText("");
}
});
final JTextField txtEnteredCustomer;
txtEnteredCustomer = new JTextField();
txtEnteredCustomer.setText("");
txtEnteredCustomer.setBounds(200, 440, 300, 30);
newOrderPanel.add(txtEnteredCustomer);
txtEnteredCustomer.setColumns(10);
txtEnteredCustomer.setVisible(false);
/* ------- Comboboxes... ------- */
final JComboBox warehouseSelection = new JComboBox(new String[]{"Lund", "Linköping", "Göteborg"}); // Creates a combobox with selections...
warehouseSelection.setBounds(200, 278, 300, 30);
newOrderPanel.add(warehouseSelection);
final JComboBox typeSelection = new JComboBox(new String[]{"Personbil", "Minibuss", "Lastbil", "Släpvagn"});
typeSelection.setBounds(200, 378, 300, 30);
newOrderPanel.add(typeSelection);
final JComboBox employeeSelection = new JComboBox(new String[]{"Jonas", "Malin", "Swante"});
employeeSelection.setBounds(200, 485, 300, 30);
newOrderPanel.add(employeeSelection);
employeeSelection.setVisible(false);
/* ------- Textfields... ------- */
final JTextArea txtrDate = new JTextArea();
txtrDate.setText("Ange datum:");
txtrDate.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrDate.setEditable(false);
txtrDate.setBackground(SystemColor.window);
txtrDate.setBounds(109, 183, 94, 25);
newOrderPanel.add(txtrDate);
final JTextArea txtrWarehouse = new JTextArea();
txtrWarehouse.setText("Välj utlämningskontor:");
txtrWarehouse.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrWarehouse.setEditable(false);
txtrWarehouse.setBackground(SystemColor.window);
txtrWarehouse.setBounds(47, 282, 162, 26);
newOrderPanel.add(txtrWarehouse);
final JTextArea txtrType = new JTextArea();
txtrType.setText("Välj fordonstyp:");
txtrType.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrType.setEditable(false);
txtrType.setBackground(SystemColor.window);
txtrType.setBounds(88, 382, 140, 26);
newOrderPanel.add(txtrType);
final JTextArea txtrSelCustomerNbr = new JTextArea();
txtrSelCustomerNbr.setText("Ange kundnummer:");
txtrSelCustomerNbr.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrSelCustomerNbr.setEditable(false);
txtrSelCustomerNbr.setBackground(SystemColor.window);
txtrSelCustomerNbr.setBounds(63, 445, 140, 19);
newOrderPanel.add(txtrSelCustomerNbr);
txtrSelCustomerNbr.setVisible(false);
final JTextArea txtrEmployee = new JTextArea();
txtrEmployee.setText("Ange handläggare:");
txtrEmployee.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtrEmployee.setEditable(false);
txtrEmployee.setBackground(SystemColor.window);
txtrEmployee.setBounds(69, 491, 134, 19);
newOrderPanel.add(txtrEmployee);
txtrEmployee.setVisible(false);
/* ------- Tabulars... ------- */
String vehicleColumn[] = {"Modell","Körkortskrav","Pris","Har krok","Regnummer"};
final DefaultTableModel vehicleModel = new DefaultTableModel(vehicleColumn, 0);
final JTable vehicleTable = new JTable(vehicleModel);
vehicleTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
String accessoryColumn[] = {"Namn", "Information", "Pris", "Produktnummer"};
final DefaultTableModel accessoryModel = new DefaultTableModel(accessoryColumn, 0);
final JTable accessoryTable = new JTable(accessoryModel);
accessoryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
String productsColumn[] = {"Produkt", "Information", "Pris", "Identifikation"};
final DefaultTableModel productsModel = new DefaultTableModel(productsColumn, 0);
final JTable productsTable = new JTable(productsModel);
productsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
productsTable.setRowSelectionAllowed(false);
productsTable.setFocusable(false);
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setLocation(10, 55);
scrollPane.setSize(680, 365);
newOrderPanel.add(scrollPane);
scrollPane.setVisible(false);
/* --------- Action listeners... --------- */
btnEnteredDate.addActionListener(new ActionListener() { // When the date and other info has been entered (button clicked)...
public void actionPerformed(ActionEvent e) {
enteredDate = txtEnteredDate.getText(); // Retrieves data from the forms...
if(!enteredDate.equals("")) {
// Error message, wrong format or illegal date input...
String selectedWarehouse = warehouseSelection.getSelectedItem().toString();
String selectedType = typeSelection.getSelectedItem().toString();
availableVehicles = controller.calculateVehicleAvailability(enteredDate, selectedWarehouse, selectedType); // Calculates vehicle availability with input data...
if(availableVehicles.size() != 0) { // If there are available vehicles...
txtEnteredDate.setVisible(false); // Hides previous data forms...
txtrDate.setVisible(false);
txtrWarehouse.setVisible(false);
txtrType.setVisible(false);
warehouseSelection.setVisible(false);
typeSelection.setVisible(false);
btnEnteredDate.setVisible(false);
Vehicle vehicle; // Creates temporary variables in which to store information when rendering vehicle information...
String vehicleModelName;
String licenseReq;
int price;
String hasHook;
for(int a = 0; a < availableVehicles.size(); a++) { // For each vehicle in the list...
vehicle = availableVehicles.get(a); // Print the information...
vehicleModelName = vehicle.getProductName();
licenseReq = vehicle.getLicenseReq();
price = vehicle.getPrice();
/* We need to print the hasHook-argument in a more sensible way which is why we do this... */
if(vehicle.hasHook()) {
hasHook = "Ja";
}
else hasHook = "Nej";
vehicleModel.addRow(new Object[]{vehicleModelName, licenseReq, price, hasHook}); // Add everything to the row and then add the row itself!
}
scrollPane.setVisible(true);
scrollPane.setViewportView(vehicleTable); // Make sure that the scrollPane displays the correct table...
vehicleTable.setVisible(true); // Show the new data forms!
btnChooseVehicle.setVisible(true);
}
else { JOptionPane.showMessageDialog(null, "Inga tillgängliga bilar hittades!"); } // If there's no available vehicles...
}
else { JOptionPane.showMessageDialog(null, "Du måste ange ett giltigt datum!"); }
}
});
btnChooseVehicle.addActionListener(new ActionListener() { // When the vehicle is chosen (button clicked) ...
public void actionPerformed(ActionEvent e) {
int vehicleNumber = vehicleTable.getSelectedRow(); // Retrieve the vehicle in question...
if(vehicleNumber > -1) { // If there is a vehicle selected...
vehicleTable.setVisible(false);
btnChooseVehicle.setVisible(false);
selectedVehicle = availableVehicles.get(vehicleNumber); // Get it from the available vehicle list...
selectedVehicle.setBooked(enteredDate); // Set it as booked with the entered date!
shoppingCart.add(selectedVehicle); // Add it to the shopping cart...
Accessory accessory;
String name;
String info;
int price;
int accessoryNbr;
for(int a = 0; a < controller.accessoryRegistry.getAccessories().size(); a++) { // Generate available accessories...
accessory = controller.accessoryRegistry.getAccessory(a);
name = accessory.getProductName();
info = accessory.getInfoTxt();
price = accessory.getPrice();
accessoryNbr = accessory.getProductNbr();
accessoryModel.addRow(new Object[]{name, info, price, accessoryNbr});
}
btnMoreAccessory.setVisible(true);
scrollPane.setViewportView(accessoryTable);
accessoryTable.setVisible(true);
btnViewOrder.setVisible(true);
}
else { JOptionPane.showMessageDialog(null, "Du måste välja ett fordon!"); }
}
});
btnMoreAccessory.addActionListener(new ActionListener() { // In order to add more accessories to the purchase...
public void actionPerformed(ActionEvent e) {
int accessoryNumber = accessoryTable.getSelectedRow(); // Get which accessory is selected...
if(accessoryNumber > -1) {
Accessory accessory;
accessory = controller.accessoryRegistry.getAccessory(accessoryNumber); // Retrieve the accessory...
shoppingCart.add(accessory); // Add it to the current list!
accessoryTable.clearSelection();
}
else { JOptionPane.showMessageDialog(null, "Du måste välja ett tillbehör!"); }
}
});
btnViewOrder.addActionListener(new ActionListener() { // When clicked, let's see the whole order...
public void actionPerformed(ActionEvent e) {
int accessoryNumber = accessoryTable.getSelectedRow(); // Get which accessory is selected...
if(accessoryNumber > -1) {
Accessory accessory;
accessory = controller.accessoryRegistry.getAccessory(accessoryNumber); // Retrieve the accessory...
shoppingCart.add(accessory); // Add it to the current list!
}
btnMoreAccessory.setVisible(false);
accessoryTable.setVisible(false);
btnViewOrder.setVisible(false);
Product product = null;
String name = null;
String info = null;
int price = 0;
int accessoryNbr = 0;
for(int a = 0; a < shoppingCart.size(); a++) { // Add the accessories to the display table...
product = shoppingCart.get(a);
name = product.getProductName();
info = product.getInfoTxt();
price = product.getPrice();
productsModel.addRow(new Object[]{name, info, price, accessoryNbr});
}
productsTable.setVisible(true);
scrollPane.setViewportView(productsTable);
txtEnteredCustomer.setVisible(true);
employeeSelection.setVisible(true);
btnConfirmOrder.setVisible(true);
txtrSelCustomerNbr.setVisible(true);
txtrEmployee.setVisible(true);
}
});
btnConfirmOrder.addActionListener(new ActionListener() { // When clicked, create the order!
public void actionPerformed(ActionEvent e) {
int customerNbr = Integer.parseInt(txtEnteredCustomer.getText()); // Retrieve more data...
if(customerNbr < controller.customerRegistry.getCustomers().size() && customerNbr > -1) {
Customer customer = controller.customerRegistry.getCustomer(customerNbr);
productsTable.setVisible(false);
btnConfirmOrder.setVisible(false);
employeeSelection.setVisible(false);
txtEnteredCustomer.setVisible(false);
txtrSelCustomerNbr.setVisible(false);
txtrEmployee.setVisible(false);
String employeeName = employeeSelection.getSelectedItem().toString();
Employee employee;
Employee selectedEmployee = null;
for(int a = 0; a < controller.employeeRegistry.getEmployees().size(); a++) { // Find the employee...
employee = controller.employeeRegistry.getEmployee(a);
if(employeeName.equals(employee.getFirstName())) {
selectedEmployee = employee;
}
}
Controller.createOrder(customer, shoppingCart, selectedEmployee); // Call the controller and create the order...
txtEnteredDate.setText(""); // Reset what's supposed to show for the next order input...
txtEnteredDate.setVisible(true);
txtrDate.setVisible(true);
txtrWarehouse.setVisible(true);
txtrType.setVisible(true);
warehouseSelection.setVisible(true);
typeSelection.setVisible(true);
btnEnteredDate.setVisible(true);
enteredDate = null; // Reset data...
availableVehicles = null;
selectedVehicle = null;
shoppingCart.clear();
vehicleModel.setRowCount(0); // Clear tables!
accessoryModel.setRowCount(0);
productsModel.setRowCount(0);
scrollPane.setVisible(false);
cardLayout.show(contentPane, "orderPanel"); // ... and return to the order menu!
JOptionPane.showMessageDialog(null, "Ordern är utförd!"); // Tell the user that the order has been confirmed!
}
else { JOptionPane.showMessageDialog(null, "Du måste ange ett giltigt kundnummer!"); }
}
});
btnBackNewOrder.addActionListener(new ActionListener() { // When clicked...
public void actionPerformed(ActionEvent e) {
int goBackSelection = JOptionPane.showConfirmDialog(null, "Du håller på att avbryta beställningen, " // Warn the user of cancelation!
+ "ingen data kommer att sparas! \n \n Vill du avbryta?",
"Varning!", JOptionPane.YES_OPTION);
if(goBackSelection == 1) { // If the user doesn't want to cancel the order...
// ... do nothing!
}
else if(goBackSelection == 0) { // If the user wants to cancel the order...
cardLayout.show(contentPane, "orderPanel");
txtEnteredDate.setText(""); // RESET ALL DATA to prevent stupid data problems, if you fail at making an order you'll have to re-do it!
txtEnteredCustomer.setText("");
txtEnteredDate.setVisible(true);
txtrDate.setVisible(true);
txtrWarehouse.setVisible(true);
txtrType.setVisible(true);
warehouseSelection.setVisible(true);
typeSelection.setVisible(true);
btnEnteredDate.setVisible(true);
if(selectedVehicle != null) { // If there is a selected vehicle...
selectedVehicle.removeBooked(enteredDate); // Remove the booked date!
}
vehicleTable.setVisible(false);
accessoryTable.setVisible(false);
productsTable.setVisible(false);
txtEnteredDate.setText("YYYY/MM/DD");
txtEnteredCustomer.setVisible(false);
txtrSelCustomerNbr.setVisible(false);
txtrEmployee.setVisible(false);
employeeSelection.setVisible(false);
btnMoreAccessory.setVisible(false);
btnChooseAccessory.setVisible(false);
btnChooseVehicle.setVisible(false);
btnConfirmOrder.setVisible(false);
scrollPane.setVisible(false);
vehicleModel.setRowCount(0); // Clear tables!
accessoryModel.setRowCount(0);
productsModel.setRowCount(0);
enteredDate = null;
selectedVehicle = null;
availableVehicles = null;
shoppingCart.clear();
}
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ----------------------------------------------- Creates the VEHICLE panel! ----------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel vehiclePanel = new JPanel();
vehiclePanel.setLayout(null);
contentPane.add(vehiclePanel, "vehiclePanel");
JButton btnSearchVehicle = new JButton("Sök fordon");
JButton btnNewVehicle = new JButton("Registrera fordon");
JButton btnBackVehicle = new JButton("Tillbaka");
btnSearchVehicle.setBounds(200, 225, 300, 75);
btnNewVehicle.setBounds(200, 350, 300, 75);
btnBackVehicle.setBounds(10, 10, 150, 35);
vehiclePanel.add(btnSearchVehicle);
vehiclePanel.add(btnNewVehicle);
vehiclePanel.add(btnBackVehicle);
btnBackVehicle.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
btnSearchVehicle.addActionListener(new ActionListener() { // To come in to the search button
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehicleSearchPanel");
}
});
btnNewVehicle.addActionListener(new ActionListener() { // To come in to the registerVehicle button
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "registerNewVehiclePanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- Creates the SEARCH VEHICLE panel! ----------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel vehicleSearchPanel = new JPanel();
vehicleSearchPanel.setLayout(null);
contentPane.add(vehicleSearchPanel, "vehicleSearchPanel");
JButton btnSearchForVehicle = new JButton("Sök fordon");
JButton btnBackSearchVehicle = new JButton("Tillbaka");
btnSearchForVehicle.setBounds(200, 485, 300, 75);
btnBackSearchVehicle.setBounds(10, 10, 100, 25);
vehicleSearchPanel.add(btnSearchForVehicle);
vehicleSearchPanel.add(btnBackSearchVehicle);
final JTextField txtEnterRegNbr; // Creates search field where you input the customer number...
txtEnterRegNbr = new JTextField();
txtEnterRegNbr.setText("");
txtEnterRegNbr.setBounds(200, 420, 300, 30);
vehicleSearchPanel.add(txtEnterRegNbr);
txtEnterRegNbr.setColumns(10);
final JTextPane paneVehicleResult = new JTextPane();
paneVehicleResult.setBounds(158, 55, 400, 335);
vehicleSearchPanel.add(paneVehicleResult);
btnSearchForVehicle.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
String enterdRegNbr = txtEnterRegNbr.getText() ; // Get text from search field...
String vehicleResult = controller.findVehicle(enterdRegNbr); // ... find the vehicle...
paneVehicleResult.setText(vehicleResult); // ... and print the text!
}
});
btnBackSearchVehicle.addActionListener(new ActionListener() { // When clicked, go back to vehiclePanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ------------------------------------------- Creates the NEW VEHICLE panel! ----------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel registerNewVehiclePanel = new JPanel();
contentPane.add(registerNewVehiclePanel, "registerNewVehiclePanel");
registerNewVehiclePanel.setLayout(null);
JButton btnBackRegisterNewVehicle = new JButton("Tillbaka");
JButton btnRegisterNewVehicle = new JButton("Registrera fordon");
btnBackRegisterNewVehicle.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "vehiclePanel");
}
});
btnBackRegisterNewVehicle.setBounds(10, 10, 150, 35);
btnRegisterNewVehicle.setBounds(200, 485, 300, 75);
registerNewVehiclePanel.add(btnBackRegisterNewVehicle);
registerNewVehiclePanel.add(btnRegisterNewVehicle);
final JTextField txtEnterVehicleRegNbr; // Creates search field where you input the information about the vehicle...
txtEnterVehicleRegNbr = new JTextField();
txtEnterVehicleRegNbr.setText("");
txtEnterVehicleRegNbr.setBounds(225, 74, 250, 30);
registerNewVehiclePanel.add(txtEnterVehicleRegNbr);
txtEnterVehicleRegNbr.setColumns(10);
final JTextArea txtrVehicleRegNbr = new JTextArea();
txtrVehicleRegNbr.setEditable(false);
txtrVehicleRegNbr.setBackground(SystemColor.window);
txtrVehicleRegNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrVehicleRegNbr.setText("Registreringsnummer");
txtrVehicleRegNbr.setBounds(90, 81, 130, 27);
registerNewVehiclePanel.add(txtrVehicleRegNbr);
final JTextField txtEnterVehicleModel; // Creates search field where you input the information about the vehicle...
txtEnterVehicleModel = new JTextField();
txtEnterVehicleModel.setText("");
txtEnterVehicleModel.setBounds(225, 120, 250, 30);
registerNewVehiclePanel.add(txtEnterVehicleModel);
txtEnterVehicleModel.setColumns(10);
final JTextArea txtrVehicleModel = new JTextArea();
txtrVehicleModel.setEditable(false);
txtrVehicleModel.setBackground(SystemColor.window);
txtrVehicleModel.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrVehicleModel.setText("Modell");
txtrVehicleModel.setBounds(130, 123, 100, 27);
registerNewVehiclePanel.add(txtrVehicleModel);
final JTextField txtEnterVehicleType; // Creates search field where you input the information about the vehicle...
txtEnterVehicleType = new JTextField();
txtEnterVehicleType.setText("");
txtEnterVehicleType.setBounds(225, 166, 250, 30);
registerNewVehiclePanel.add(txtEnterVehicleType);
txtEnterVehicleType.setColumns(10);
final JTextArea txtrVehicleType = new JTextArea();
txtrVehicleType.setEditable(false);
txtrVehicleType.setBackground(SystemColor.window);
txtrVehicleType.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrVehicleType.setText("Fordonstyp");
txtrVehicleType.setBounds(130, 165, 100, 27);
registerNewVehiclePanel.add(txtrVehicleType);
final JTextField txtEnterNewVehicleLicenseReq; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleLicenseReq= new JTextField();
txtEnterNewVehicleLicenseReq.setText("");
txtEnterNewVehicleLicenseReq.setBounds(225, 212, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleLicenseReq);
txtEnterNewVehicleLicenseReq.setColumns(10);
final JTextArea txtrNewVehicleLicenseReq = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleLicenseReq.setEditable(false);
txtrNewVehicleLicenseReq.setBackground(SystemColor.window);
txtrNewVehicleLicenseReq.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleLicenseReq.setText("Körkortskrav");
txtrNewVehicleLicenseReq.setBounds(130, 207, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleLicenseReq);
final JTextField txtEnterNewVehiclePrice; // Creates search field where you input the information about the vehicle...
txtEnterNewVehiclePrice= new JTextField();
txtEnterNewVehiclePrice.setText("");
txtEnterNewVehiclePrice.setBounds(225, 258, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehiclePrice);
txtEnterNewVehiclePrice.setColumns(10);
final JTextArea txtrNewVehiclePrice = new JTextArea(); // Creates the text next to the input field.
txtrNewVehiclePrice.setEditable(false);
txtrNewVehiclePrice.setBackground(SystemColor.window);
txtrNewVehiclePrice.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehiclePrice.setText("Pris");
txtrNewVehiclePrice.setBounds(130, 249, 100, 27);
registerNewVehiclePanel.add(txtrNewVehiclePrice);
final JTextField txtEnterNewVehicleInfo; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleInfo= new JTextField();
txtEnterNewVehicleInfo.setText("");
txtEnterNewVehicleInfo.setBounds(225, 304, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleInfo);
txtEnterNewVehicleInfo.setColumns(10);
final JTextArea txtrNewVehicleInfo = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleInfo.setEditable(false);
txtrNewVehicleInfo.setBackground(SystemColor.window);
txtrNewVehicleInfo.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleInfo.setText("Beskrivning");
txtrNewVehicleInfo.setBounds(130, 291, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleInfo);
final JTextField txtEnterNewVehicleHasHook; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleHasHook= new JTextField();
txtEnterNewVehicleHasHook.setText("");
txtEnterNewVehicleHasHook.setBounds(225, 350, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleHasHook);
txtEnterNewVehicleHasHook.setColumns(10);
final JTextArea txtrNewVehicleHasHook = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleHasHook.setEditable(false);
txtrNewVehicleHasHook.setBackground(SystemColor.window);
txtrNewVehicleHasHook.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleHasHook.setText("Dragkrok");
txtrNewVehicleHasHook.setBounds(130, 333, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleHasHook);
final JTextField txtEnterNewVehicleExpiryDate; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleExpiryDate= new JTextField();
txtEnterNewVehicleExpiryDate.setText("");
txtEnterNewVehicleExpiryDate.setBounds(225, 396, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleExpiryDate);
txtEnterNewVehicleExpiryDate.setColumns(10);
final JTextArea txtrNewVehicleExpiryDate = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleExpiryDate.setEditable(false);
txtrNewVehicleExpiryDate.setBackground(SystemColor.window);
txtrNewVehicleExpiryDate.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleExpiryDate.setText("Utgångsdatum");
txtrNewVehicleExpiryDate.setBounds(130, 375, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleExpiryDate);
final JTextField txtEnterNewVehicleWarehouse; // Creates search field where you input the information about the vehicle...
txtEnterNewVehicleWarehouse= new JTextField();
txtEnterNewVehicleWarehouse.setText("");
txtEnterNewVehicleWarehouse.setBounds(225, 442, 250, 30);
registerNewVehiclePanel.add(txtEnterNewVehicleWarehouse);
txtEnterNewVehicleWarehouse.setColumns(10);
final JTextArea txtrNewVehicleWarehouse = new JTextArea(); // Creates the text next to the input field.
txtrNewVehicleWarehouse.setEditable(false);
txtrNewVehicleWarehouse.setBackground(SystemColor.window);
txtrNewVehicleWarehouse.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewVehicleWarehouse.setText("Filial/lager");
txtrNewVehicleWarehouse.setBounds(130, 417, 100, 27);
registerNewVehiclePanel.add(txtrNewVehicleWarehouse);
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------- Creates the ACCESSORY panel! ---------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel accessoryPanel = new JPanel();
accessoryPanel.setLayout(null);
contentPane.add(accessoryPanel, "accessoryPanel");
JButton btnSearchAccessory = new JButton("Sök tillbehör");
JButton btnNewAccessory = new JButton("Registrera tillbehör");
JButton btnBackAccessory = new JButton("Tillbaka");
btnSearchAccessory.setBounds(200, 225, 300, 75);
btnNewAccessory.setBounds(200, 350, 300, 75);
btnBackAccessory.setBounds(10, 10, 150, 35);
accessoryPanel.add(btnSearchAccessory);
accessoryPanel.add(btnNewAccessory);
accessoryPanel.add(btnBackAccessory);
btnBackAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "mainPanel");
}
});
btnSearchAccessory.addActionListener(new ActionListener() { // When clicked, go to accessorySearchPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessorySearchPanel");
}
});
btnNewAccessory.addActionListener(new ActionListener() { // When clicked, go to registerNewAccessoryPanel
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "registerNewAccessoryPanel");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- Creates the SEARCH ACCESSORY panel! --------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel accessorySearchPanel = new JPanel();
accessorySearchPanel.setLayout(null);
contentPane.add(accessorySearchPanel, "accessorySearchPanel");
JButton btnSearchForAccessory = new JButton("Sök tillbehör");
JButton btnBackSearchAccessory = new JButton("Tillbaka");
final JButton btnChangeAccessory = new JButton("Ändra tillbehör");
btnChangeAccessory.setVisible(false);
btnSearchForAccessory.setBounds(200, 475, 300, 50);
btnBackSearchAccessory.setBounds(10, 10, 150, 35);
btnChangeAccessory.setBounds(200, 537, 300, 50);
accessorySearchPanel.add(btnSearchForAccessory);
accessorySearchPanel.add(btnBackSearchAccessory);
accessorySearchPanel.add(btnChangeAccessory);
final JTextField fieldEnterProductNbr = new JTextField();
fieldEnterProductNbr.setBounds(225, 421, 250, 30);
accessorySearchPanel.add(fieldEnterProductNbr);
final JTextField fieldSearchAccessoryInfo = new JTextField();
fieldSearchAccessoryInfo.setBounds(225, 283, 250, 50);
accessorySearchPanel.add(fieldSearchAccessoryInfo);
final JTextField fieldSearchAccessoryProductNbr = new JTextField();
fieldSearchAccessoryProductNbr.setBounds(225, 150, 250, 30);
fieldSearchAccessoryProductNbr.setEditable(false);
accessorySearchPanel.add(fieldSearchAccessoryProductNbr);
final JTextField fieldSearchAccessoryPrice = new JTextField();
fieldSearchAccessoryPrice.setBounds(225, 215, 250, 30);
accessorySearchPanel.add(fieldSearchAccessoryPrice);
final JTextField fieldSearchAccessoryName = new JTextField();
fieldSearchAccessoryName.setBounds(225, 83, 250, 30);
accessorySearchPanel.add(fieldSearchAccessoryName);
JTextArea txtrSearchAccessoryName = new JTextArea();
txtrSearchAccessoryName.setEditable(false);
txtrSearchAccessoryName.setText("Namn");
txtrSearchAccessoryName.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryName.setBackground(SystemColor.window);
txtrSearchAccessoryName.setBounds(100, 90, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryName);
JTextArea txtrSearchAccessoryProductNbr = new JTextArea();
txtrSearchAccessoryProductNbr.setText("Produktnummer");
txtrSearchAccessoryProductNbr.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryProductNbr.setEditable(false);
txtrSearchAccessoryProductNbr.setBackground(SystemColor.window);
txtrSearchAccessoryProductNbr.setBounds(100, 157, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryProductNbr);
JTextArea txtrSearchAccessoryPrice = new JTextArea();
txtrSearchAccessoryPrice.setText("Pris");
txtrSearchAccessoryPrice.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryPrice.setEditable(false);
txtrSearchAccessoryPrice.setBackground(SystemColor.window);
txtrSearchAccessoryPrice.setBounds(100, 222, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryPrice);
JTextArea txtrSearchAccessoryInfo = new JTextArea();
txtrSearchAccessoryInfo.setText("Beskrivning");
txtrSearchAccessoryInfo.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrSearchAccessoryInfo.setEditable(false);
txtrSearchAccessoryInfo.setBackground(SystemColor.window);
txtrSearchAccessoryInfo.setBounds(100, 283, 113, 23);
accessorySearchPanel.add(txtrSearchAccessoryInfo);
JTextArea txtrEnterProductNbr = new JTextArea();
txtrEnterProductNbr.setText("Ange produktnummer");
txtrEnterProductNbr.setFont(new Font("Lucida Grande", Font.PLAIN, 13));
txtrEnterProductNbr.setEditable(false);
txtrEnterProductNbr.setBackground(SystemColor.window);
txtrEnterProductNbr.setBounds(43, 428, 145, 23);
accessorySearchPanel.add(txtrEnterProductNbr);
final JButton btnDeleteAccessory = new JButton("Ta bort ");
btnDeleteAccessory.setBounds(200, 599, 300, 50);
accessorySearchPanel.add(btnDeleteAccessory);
btnDeleteAccessory.setVisible(false);
btnSearchForAccessory.addActionListener(new ActionListener() { // When search button is pressed...
public void actionPerformed(ActionEvent e) {
btnChangeAccessory.setVisible(true);
btnDeleteAccessory.setVisible(true);
int enteredProductNbr = Integer.parseInt(fieldEnterProductNbr.getText()); // Get text from search field...
accessory = controller.findAccessory(enteredProductNbr); // ... find the accessory...
fieldSearchAccessoryName.setText(accessory.getProductName()); // ... and print the text
fieldSearchAccessoryProductNbr.setText(Integer.toString(accessory.getProductNbr())); // ... and print the text
fieldSearchAccessoryPrice.setText(Integer.toString(accessory.getPrice())); // ... and print the text
fieldSearchAccessoryInfo.setText(accessory.getInfoTxt()); // ... and print the text
}
});
btnChangeAccessory.addActionListener(new ActionListener() { // When change button is pressed...
public void actionPerformed(ActionEvent e){
accessory.setProductName(fieldSearchAccessoryName.getText()); // changes the name for an accessory
accessory.setPrice(Integer.parseInt(fieldSearchAccessoryPrice.getText()));//...price
accessory.setInfoTxt(fieldSearchAccessoryInfo.getText());//...info text
}
});
btnDeleteAccessory.addActionListener(new ActionListener() { // When delete button is pressed...
public void actionPerformed(ActionEvent e){
}
});
btnBackSearchAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel and clear fields...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
fieldSearchAccessoryName.setText("");
fieldSearchAccessoryProductNbr.setText("");
fieldSearchAccessoryPrice.setText("");
fieldSearchAccessoryInfo.setText("");
fieldEnterProductNbr.setText("");
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* --------------------------------------- Creates the NEW ACCESSORY panel! ------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
final JPanel registerNewAccessoryPanel = new JPanel();
contentPane.add(registerNewAccessoryPanel, "registerNewAccessoryPanel");
registerNewAccessoryPanel.setLayout(null);
JButton btnBackRegisterNewAccessory = new JButton("Tillbaka");
JButton btnRegisterNewAccessory = new JButton("Registrera tillbehör");
btnBackRegisterNewAccessory.addActionListener(new ActionListener() { // When clicked, go back to mainPanel...
public void actionPerformed(ActionEvent e) {
cardLayout.show(contentPane, "accessoryPanel");
}
});
btnBackRegisterNewAccessory.setBounds(10, 10, 150, 35);
btnRegisterNewAccessory.setBounds(200, 485, 300, 75);
registerNewAccessoryPanel.add(btnBackRegisterNewAccessory);
registerNewAccessoryPanel.add(btnRegisterNewAccessory);
final JTextField txtEnterAccessoryName; // Creates search field where you input the information about the customer...
txtEnterAccessoryName = new JTextField();
txtEnterAccessoryName.setText("");
txtEnterAccessoryName.setBounds(225, 74, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryName);
txtEnterAccessoryName.setColumns(10);
JTextArea txtrAccessoryName = new JTextArea();
txtrAccessoryName.setEditable(false);
txtrAccessoryName.setBackground(SystemColor.window);
txtrAccessoryName.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryName.setText("Namn");
txtrAccessoryName.setBounds(130, 81, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryName);
final JTextField txtEnterAccessoryProductNbr; // Creates search field where you input the information about the customer...
txtEnterAccessoryProductNbr = new JTextField();
txtEnterAccessoryProductNbr.setText("");
txtEnterAccessoryProductNbr.setBounds(225, 144, 250, 30);
registerNewAccessoryPanel.add(txtEnterAccessoryProductNbr);
txtEnterAccessoryProductNbr.setColumns(10);
JTextArea txtrAccessoryProductNbr = new JTextArea();
txtrAccessoryProductNbr.setEditable(false);
txtrAccessoryProductNbr.setBackground(SystemColor.window);
txtrAccessoryProductNbr.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryProductNbr.setText("Produktnummer");
txtrAccessoryProductNbr.setBounds(130, 151, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryProductNbr);
final JTextField txtEnterNewAccessoryPrice; // Creates search field where you input the information about the customer...
txtEnterNewAccessoryPrice= new JTextField();
txtEnterNewAccessoryPrice.setText("");
txtEnterNewAccessoryPrice.setBounds(225, 210, 250, 30);
registerNewAccessoryPanel.add(txtEnterNewAccessoryPrice);
txtEnterNewAccessoryPrice.setColumns(10);
JTextArea txtrNewAccessoryPrice = new JTextArea(); // Creates the text next to the input field.
txtrNewAccessoryPrice.setEditable(false);
txtrNewAccessoryPrice.setBackground(SystemColor.window);
txtrNewAccessoryPrice.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrNewAccessoryPrice.setText("Pris");
txtrNewAccessoryPrice.setBounds(130, 217, 100, 27);
registerNewAccessoryPanel.add(txtrNewAccessoryPrice);
final JTextField txtEnterAccessoryInfo; // Creates search field where you input the information about the customer...
txtEnterAccessoryInfo = new JTextField();
txtEnterAccessoryInfo.setText("");
txtEnterAccessoryInfo.setBounds(225, 276, 250, 85);
registerNewAccessoryPanel.add(txtEnterAccessoryInfo);
txtEnterAccessoryInfo.setColumns(10);
JTextArea txtrAccessoryInfo = new JTextArea(); // Creates the text next to the input field.
txtrAccessoryInfo.setEditable(false);
txtrAccessoryInfo.setBackground(SystemColor.window);
txtrAccessoryInfo.setFont(new Font("Tahoma", Font.PLAIN, 13));
txtrAccessoryInfo.setText("Beskrivning");
txtrAccessoryInfo.setBounds(130, 283, 100, 27);
registerNewAccessoryPanel.add(txtrAccessoryInfo);
btnRegisterNewAccessory.addActionListener(new ActionListener() { // When register button is pressed...
public void actionPerformed(ActionEvent e){
String inputName = txtEnterAccessoryName.getText(); //gets the written name from fields
int inputProductNbr = Integer.parseInt(txtEnterAccessoryProductNbr.getText()); // product number
int inputPrice = Integer.parseInt(txtEnterNewAccessoryPrice.getText());// price
String inputInfo = txtEnterAccessoryInfo.getText(); // information
Controller.createAccessories(inputProductNbr, inputName, inputPrice, inputInfo );
}
});
/* -------------------------------------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------------------------------------------- */
/*Standard frame settings. */
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}
| Update GUI.java | Source-files/GUI.java | Update GUI.java | <ide><path>ource-files/GUI.java
<ide> private Vehicle selectedVehicle;
<ide> private String enteredDate;
<ide> private Accessory accessory;
<add> private Vehicle vehicle;
<ide>
<ide> private String searchMode = null; // Used for defining search mode when searching for orders...
<ide> private Order order; |
|
Java | apache-2.0 | 11e1a9faebd2bb0aa844e9da108638b18ae6c6f3 | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.flow.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.util.Assert;
import org.springframework.validation.Errors;
import org.springframework.web.flow.FlowExecution;
import org.springframework.web.flow.FlowLocator;
import org.springframework.web.flow.action.AbstractAction;
import org.springframework.web.flow.config.BeanFactoryFlowServiceLocator;
import org.springframework.web.flow.support.HttpFlowExecutionManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.struts.BindingActionForm;
import org.springframework.web.struts.TemplateAction;
import org.springframework.web.util.WebUtils;
/**
* Struts Action that acts a front controller entry point into the web flow
* system. Typically, a FlowAction exists per top-level (root) flow definition
* in the application. Alternatively, a single FlowAction may manage all flow
* executions by parameterization with the appropriate <code>flowId</code> in
* views that start new flow executions.
* <p>
* Requests are managed by and delegated to a {@link HttpFlowExecutionManager},
* allowing reuse of common front flow controller logic in other environments.
* Consult the JavaDoc of that class for more information on how requests are
* processed.
* <p>
* This class also is aware of the <code>BindingActionForm</code> adapter,
* which adapts Spring's data binding infrastructure (based on POJO binding, a
* standard Errors interface, and property editor type conversion) to the Struts
* action form model. This gives backend web-tier developers full support for
* POJO-based binding with minimal hassel, while still providing consistency
* to view developers who already have a lot of experience with Struts for markup
* and request dispatching.
* <p>
* Below is an example <code>struts-config.xml</code> configuration for a
* Flow-action that fronts a single top-level flow:
*
* <pre>
*
* <action path="/userRegistration"
* type="org.springframework.web.flow.struts.FlowAction"
* name="bindingActionForm" scope="request"
* className="org.springframework.web.flow.struts.FlowActionMapping">
* <set-property property="flowId" value="user.Registration" />
* </action>
*
* </pre>
*
* This example associates the logical request URL
* <code>/userRegistration.do</code> with the <code>Flow</code> indentified
* by the id <code>user.Registration</code>. Alternatively, the
* <code>flowId</code> could have been left blank and provided in dynamic
* fashion by the views (allowing a single <code>FlowAction</code> to manage
* any number of flow executions). A binding action form instance is set in
* request scope, acting as an adapter enabling POJO-based binding and
* validation with Spring.
* <p>
* Other notes regarding Struts web-flow integration:
* <ul>
* <li>Logical view names returned when <code>ViewStates</code> and
* <code>EndStates</code> are entered are mapped to physical view templates
* using standard Struts action forwards (typically global forwards).
* <li>Use of the BindingActionForm requires some minor setup in
* <code>struts-config.xml</code>. Specifically:
* <ol>
* <li>A custom BindingActionForm-aware request processor is needed, to defer
* form population:<br>
*
* <tt>
* <controller processorClass="org.springframework.web.struts.BindingRequestProcessor"/>
* </tt>
*
* <li>A <code>BindingPlugin</code> is needed, to plugin a Errors-aware
* <code>jakarta-commons-beanutils</code> adapter:<br>
*
* <tt>
* <plug-in className="org.springframework.web.struts.BindingPlugin"/>
* </tt>
*
* </ol>
* </ul>
* The benefits here are substantial--developers now have a powerful webflow
* capability integrated with Struts, with a consistent-approach to
* POJO-based binding and validation that addresses the proliferation of
* <code>ActionForm</code> classes found in traditional Struts-based apps.
*
* @see org.springframework.web.flow.support.HttpFlowExecutionManager
* @see org.springframework.web.struts.BindingActionForm
* @author Keith Donald
* @author Erwin Vervaet
*/
public class FlowAction extends TemplateAction {
/**
* Get the flow execution from given model and view. Subclasses
* should override this if the flow execution is not available in
* it's standard place, where it is put by the
* {@link org.springframework.web.flow.FlowExecutionStack}.
*/
protected FlowExecution getFlowExecution(ModelAndView modelAndView) {
//TODO: this is not extremely clean (pulling a attribute from hard
//coded name that is configurable elsewhere)
return (FlowExecution)modelAndView.getModel().get(FlowExecution.ATTRIBUTE_NAME);
}
protected ActionForward doExecuteAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
FlowLocator locator = new BeanFactoryFlowServiceLocator(getWebApplicationContext());
HttpFlowExecutionManager executionManager = new HttpFlowExecutionManager(getFlowId(mapping), locator);
ModelAndView modelAndView = executionManager.handleRequest(request, response);
FlowExecution flowExecution = getFlowExecution(modelAndView);
if (flowExecution != null && flowExecution.isActive()) {
if (form instanceof BindingActionForm) {
BindingActionForm bindingForm = (BindingActionForm)form;
bindingForm.setErrors((Errors)flowExecution.getAttribute(AbstractAction.FORM_OBJECT_ERRORS_ATTRIBUTE,
Errors.class));
bindingForm.setRequest(request);
}
}
return createForwardFromModelAndView(modelAndView, mapping, request);
}
/**
* Get the flow id from given action mapping, which should be of type
* <code>FlowActionMapping</code>.
*/
private String getFlowId(ActionMapping mapping) {
Assert.isInstanceOf(FlowActionMapping.class, mapping);
return ((FlowActionMapping)mapping).getFlowId();
}
/**
* Return a Struts ActionForward given a ModelAndView. We need to add all
* attributes from the ModelAndView as request attributes.
*/
private ActionForward createForwardFromModelAndView(ModelAndView modelAndView, ActionMapping mapping,
HttpServletRequest request) {
if (modelAndView != null) {
WebUtils.exposeRequestAttributes(request, modelAndView.getModel());
ActionForward forward = mapping.findForward(modelAndView.getViewName());
if (forward == null) {
forward = new ActionForward(modelAndView.getViewName());
}
return forward;
}
else {
if (logger.isInfoEnabled()) {
logger.info("No model and view; returning a [null] forward");
}
return null;
}
}
} | sandbox/src/org/springframework/web/flow/struts/FlowAction.java | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.flow.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.util.Assert;
import org.springframework.validation.Errors;
import org.springframework.web.flow.FlowExecution;
import org.springframework.web.flow.FlowLocator;
import org.springframework.web.flow.action.AbstractAction;
import org.springframework.web.flow.config.BeanFactoryFlowServiceLocator;
import org.springframework.web.flow.support.HttpFlowExecutionManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.struts.BindingActionForm;
import org.springframework.web.struts.TemplateAction;
import org.springframework.web.util.WebUtils;
/**
* Struts Action that acts a front controller entry point into the web flow
* system. Typically, a FlowAction exists per top-level (root) flow definition
* in the application. Alternatively, a single FlowAction may manage all flow
* executions by parameterization with the appropriate <code>flowId</code> in
* views that start new flow executions.
* <p>
* Requests are managed by and delegated to a {@link HttpFlowExecutionManager},
* allowing reuse of common front flow controller logic in other environments.
* Consult the JavaDoc of that class for more information on how requests are
* processed.
* <p>
* This class also is aware of the <code>BindingActionForm</code> adapter,
* which adapts Spring's data binding infrastructure (based on POJO binding, a
* standard Errors interface, and property editor type conversion) to the Struts
* action form model. This gives backend web-tier developers full support for
* POJO-based binding with minimal hassel, while still providing consistency
* to view developers who already have a lot of experience with Struts for markup
* and request dispatching.
* <p>
* Below is an example <code>struts-config.xml</code> configuration for a
* Flow-action that fronts a single top-level flow:
*
* <pre>
*
* <action path="/userRegistration"
* type="org.springframework.web.flow.struts.FlowAction"
* name="bindingActionForm" scope="request"
* className="org.springframework.web.flow.struts.FlowActionMapping">
* <set-property property="flowId" value="user.Registration" />
* </action>
*
* </pre>
*
* This example associates the logical request URL
* <code>/userRegistration.do</code> with the <code>Flow</code> indentified
* by the id <code>user.Registration</code>. Alternatively, the
* <code>flowId</code> could have been left blank and provided in dynamic
* fashion by the views (allowing a single <code>FlowAction</code> to manage
* any number of flow executions). A binding action form instance is set in
* request scope, acting as an adapter enabling POJO-based binding and
* validation with Spring.
* <p>
* Other notes regarding Struts web-flow integration:
* <ul>
* <li>Logical view names returned when <code>ViewStates</code> and
* <code>EndStates</code> are entered are mapped to physical view templates
* using standard Struts action forwards (typically global forwards).
* <li>Use of the BindingActionForm requires some minor setup in
* <code>struts-config.xml</code>. Specifically:
* <ol>
* <li>A custom BindingActionForm-aware request processor is needed, to defer
* form population:<br>
*
* <tt>
* <controller processorClass="org.springframework.web.struts.BindingRequestProcessor"/>
* </tt>
*
* <li>A <code>BindingPlugin</code> is needed, to plugin a Errors-aware
* <code>jakarta-commons-beanutils</code> adapter:<br>
*
* <tt>
* <plug-in className="org.springframework.web.struts.BindingPlugin"/>
* </tt>
*
* </ol>
* </ul>
* The benefits here are substantial--developers now have a powerful webflow
* capability integrated with Struts, with a consistent-approach to
* POJO-based binding and validation that addresses the proliferation of
* <code>ActionForm</code> classes found in traditional Struts-based apps.
*
* @see org.springframework.web.flow.support.HttpFlowExecutionManager
* @see org.springframework.web.struts.BindingActionForm
* @author Keith Donald
* @author Erwin Vervaet
*/
public class FlowAction extends TemplateAction {
protected ActionForward doExecuteAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
FlowLocator locator = new BeanFactoryFlowServiceLocator(getWebApplicationContext());
HttpFlowExecutionManager executionManager = new HttpFlowExecutionManager(getFlowId(mapping), locator);
ModelAndView modelAndView = executionManager.handleRequest(request, response);
//TODO: this is not extremely clean (pulling a attribute from hard
// coded name that is configurable elsewhere)
FlowExecution flowExecution = (FlowExecution)modelAndView.getModel().get(FlowExecution.ATTRIBUTE_NAME);
if (flowExecution != null && flowExecution.isActive()) {
if (form instanceof BindingActionForm) {
BindingActionForm bindingForm = (BindingActionForm)form;
bindingForm.setErrors((Errors)flowExecution.getAttribute(AbstractAction.FORM_OBJECT_ERRORS_ATTRIBUTE,
Errors.class));
bindingForm.setRequest(request);
}
}
return createForwardFromModelAndView(modelAndView, mapping, request);
}
/**
* Get the flow id from given action mapping, which should be of type
* <code>FlowActionMapping</code>.
*/
private String getFlowId(ActionMapping mapping) {
Assert.isInstanceOf(FlowActionMapping.class, mapping);
return ((FlowActionMapping)mapping).getFlowId();
}
/**
* Return a Struts ActionForward given a ModelAndView. We need to add all
* attributes from the ModelAndView as request attributes.
*/
private ActionForward createForwardFromModelAndView(ModelAndView modelAndView, ActionMapping mapping,
HttpServletRequest request) {
if (modelAndView != null) {
WebUtils.exposeRequestAttributes(request, modelAndView.getModel());
ActionForward forward = mapping.findForward(modelAndView.getViewName());
if (forward == null) {
forward = new ActionForward(modelAndView.getViewName());
}
return forward;
}
else {
if (logger.isInfoEnabled()) {
logger.info("No model and view; returning a [null] forward");
}
return null;
}
}
} | Cleanup.
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@5627 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| sandbox/src/org/springframework/web/flow/struts/FlowAction.java | Cleanup. | <ide><path>andbox/src/org/springframework/web/flow/struts/FlowAction.java
<ide> * @author Erwin Vervaet
<ide> */
<ide> public class FlowAction extends TemplateAction {
<add>
<add> /**
<add> * Get the flow execution from given model and view. Subclasses
<add> * should override this if the flow execution is not available in
<add> * it's standard place, where it is put by the
<add> * {@link org.springframework.web.flow.FlowExecutionStack}.
<add> */
<add> protected FlowExecution getFlowExecution(ModelAndView modelAndView) {
<add> //TODO: this is not extremely clean (pulling a attribute from hard
<add> //coded name that is configurable elsewhere)
<add> return (FlowExecution)modelAndView.getModel().get(FlowExecution.ATTRIBUTE_NAME);
<add> }
<ide>
<ide> protected ActionForward doExecuteAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
<ide> HttpServletResponse response) throws Exception {
<ide> FlowLocator locator = new BeanFactoryFlowServiceLocator(getWebApplicationContext());
<ide> HttpFlowExecutionManager executionManager = new HttpFlowExecutionManager(getFlowId(mapping), locator);
<ide> ModelAndView modelAndView = executionManager.handleRequest(request, response);
<del> //TODO: this is not extremely clean (pulling a attribute from hard
<del> // coded name that is configurable elsewhere)
<del> FlowExecution flowExecution = (FlowExecution)modelAndView.getModel().get(FlowExecution.ATTRIBUTE_NAME);
<add> FlowExecution flowExecution = getFlowExecution(modelAndView);
<ide> if (flowExecution != null && flowExecution.isActive()) {
<ide> if (form instanceof BindingActionForm) {
<ide> BindingActionForm bindingForm = (BindingActionForm)form; |
|
JavaScript | apache-2.0 | 3c14744e8684810fed3c70d57726f3c2014223a5 | 0 | SpiderOak/so_client_html5,SpiderOak/so_client_html5 | /* SpiderOak html5 client Main app.
* Works with:
* - jquery.mobile-1.0.1.css
* - jquery-1.6.4.js
* - jquery.mobile-1.0.1.js
* - misc.js - b32encode_trim(), blather(), error_alert()
*/
/*
This machinery intercepts navigation to content repository URLs and
it intervenes by means of binding handle_content_visit to jQuery mobile
"pagebeforechange" event.
*/
SO_DEBUGGING = true; // for misc.js:blather()
$(document).ready(function () {
spideroak.init();
$('.nav_login_storage form').submit(function () {
var username = $('input[name=username]', this).val();
var password = $('input[name=password]', this).val();
spideroak.remote_login({username: username, password: password});
return false;
});
});
/* Modular singleton pattern: */
var spideroak = function () {
/* private: */
var defaults = {
// API v1.
// XXX starting_host_url may vary according to brand package.
starting_host_url: "https://spideroak.com",
storage_login_path: "/browse/login",
storage_path: "/storage/",
share_path: "/share/",
storage_root_page_id: "storage-root",
devices_query_string: '?device_info=yes',
}
var my = {
starting_host_url: null,
storage_path: null,
username: null,
storage_web_url: null, // Location of storage web UI for user.
// Accumulate content_url_roots on access to various content repos
// - the storage repo root, various share rooms.
content_url_roots: [], // Observed prefixes for user's content URLs.
}
function set_account(username, domain, storage_path, storage_web_url) {
/* Register user-specific storage details, returning storage root URL.
*/
my.username = username;
my.storage_domain = domain;
my.storage_root_path = storage_path + b32encode_trim(username) + "/";
my.storage_root_url = domain + my.storage_root_path;
// content_url_roots are for discerning URLs of contained items.
my.content_url_roots.push(my.storage_root_url);
my.storage_web_url = storage_web_url;
return my.storage_root_url;
}
/* Various content node types - the root, devices, directories, and
files - are implemented based on a generic ContentNode object.
Departures from the basic functionality are implemented as distinct
prototype functions defined immediately after the generic ones.
The generic functions are for the more prevalent container-style nodes.
*/
function ContentNode(path, parent) {
/* Basis for representing collections of remote content items.
- 'path' is relative to the collection's root (top) node.
All paths should start with '/'.
- 'parent' is containing node. The root's parent is null.
See 'Device storage node example json data' below for example JSON.
*/
if ( !(this instanceof ContentNode) ) // Coding failsafe.
throw new Error("Constructor called as a function");
if (path) { // Skip if we're in prototype assignment.
this.path = path;
this.root_path = parent ? parent.root_path : path;
this.parent_path = parent ? parent.path : null;
this.is_container = true;
this.subdirs = []; // Paths of contained devices, directories.
this.files = []; // Paths of contained files.
this.set_page_id();
this.lastfetched = false;
}
}
function StorageNode(path, parent) {
ContentNode.call(this, path, parent);
// All but the root storage nodes are contained within a device.
// The DeviceStorageNode sets the device path, which will trickle
// down to all its contents.
this.device_path = parent ? parent.device_path : null;
}
StorageNode.prototype = new ContentNode();
function ShareNode(path, parent) {
ContentNode.call(this, path, parent);
if (! parent) {
// This is a share room, which is the root of the collection.
this.root_path = path; }
else {
this.root_path = parent.root_path; }
}
ShareNode.prototype = new ContentNode();
function RootStorageNode(path, parent) {
StorageNode.call(this, path, parent);
this.stats = null;
delete this.files; }
RootStorageNode.prototype = new StorageNode();
function RootShareNode(path, parent) {
ShareNode.call(this, path, parent); }
RootShareNode.prototype = new ShareNode();
function DeviceStorageNode(path, parent) {
StorageNode.call(this, path, parent);
this.device_path = path; }
DeviceStorageNode.prototype = new StorageNode();
function DirectoryStorageNode(path, parent) {
StorageNode.call(this, path, parent); }
function DirectoryShareNode(path, parent) {
ShareNode.call(this, path, parent); }
DirectoryShareNode.prototype = new ShareNode();
function FileStorageNode(path, parent) {
StorageNode.call(this, path, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileStorageNode.prototype = new StorageNode();
function FileShareNode(path, parent) {
ShareNode.call(this, path, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileShareNode.prototype = new ShareNode();
ContentNode.prototype.visit = function () {
/* Get up-to-date with remote copy and show. */
if (! this.up_to_date()) {
// We use 'this_node' because 'this' gets overridden when
// success_handler is actually running, so we another
// lexically scoped var.
var this_node = this;
var success_handler = function (data, when) {
this_node.provision(data, when);
this_node.show();
}
this.fetch_and_dispatch(success_handler,
this_node.handle_failed_visit);
} else {
this.show();
}
}
ContentNode.prototype.handle_failed_visit = function (xhr) {
/* Do error handling failed visit with 'xhr' XMLHttpResponse report. */
// TODO: Proper error handling.
error_alert("Failure reaching " + this.path, xhr.status);
}
ContentNode.prototype.provision = function (data, when) {
/* Populate node with JSON 'data'. 'when' is the data's current-ness.
'when' should be no more recent than the XMLHttpRequest.
*/
this.provision_preliminaries(data, when);
this.provision_populate(data, when);
}
ContentNode.prototype.provision_preliminaries = function (data, when) {
/* Do provisioning stuff generally useful for derived types. */
if (! when) {
throw new Error("Node provisioning without reliable time stamp.");
}
this.up_to_date(when);
}
ContentNode.prototype.provision_populate = function (data, when) {
/* Stub, must be overridden by type-specific provisionings. */
throw new Error("Type-specific provisioning implementation missing.")
}
RootStorageNode.prototype.provision_populate = function (data, when) {
/* Embody the root content item with 'data'. */
var mgr = content_node_manager
var dev, devdata;
mgr.stats = data["stats"]; // TODO: We'll cook stats when UI is ready.
for (var i in data.devices) {
devdata = data.devices[i];
path = my.storage_root_path + devdata["encoded"]
dev = mgr.get(path, this)
dev.name = devdata["name"];
dev.lastlogin = devdata["lastlogin"];
dev.lastcommit = devdata["lastcommit"];
if (! ($.inArray(path, this.subdirs) >= 0)) {
this.subdirs.push(path);
}
}
this.lastfetched = when;
}
ContentNode.prototype.show = function () {
/* Present self in the UI. */
var page_id = this.get_page_id();
var page = $("#" + page_id);
// >>>
blather(this + ".show() " + " on page " + page_id);
}
ContentNode.prototype.is_storage_root = function () {
/* True if the node is a storage root item. */
return (this.path === my.storage_root_path);
}
ContentNode.prototype.set_page_id = function () {
/* Set the UI page id, acording to stored characteristics. */
// TODO: Actually allocate and manage pages per node.
this.page_id = (this.parent
? this.parent.get_page_id()
: defaults.storage_root_page_id);
}
ContentNode.prototype.get_page_id = function () {
/* Return the UI page id. */
return this.page_id;
}
ContentNode.prototype.up_to_date = function (when) {
/* True if provisioned data is current.
Optional 'when' specifies (new) time we were fetched. */
if (when) {this.lastfetched = when;}
if (! this.lastfetched) { return false; }
// XXX: Currently, never up to date! Must actually test against the
// device lastcommit time.
else { return (this.lastfetched >= new Date().getTime()); }
}
ContentNode.prototype.fetch_and_dispatch = function (success_callback,
failure_callback) {
/* Retrieve this node's data and conduct specified actions accordingly.
- On success, 'success_callback' gets retrived data and Date() just
prior to the retrieval.
- Otherwise, 'failure_callback' invoked with XMLHttpResponse object.
*/
var storage_url = my.storage_domain + this.path;
var when = new Date();
if (this.is_storage_root()) {
storage_url += defaults.devices_query_string; }
$.ajax({url: storage_url,
type: 'GET',
dataType: 'json',
success: function (data) {
success_callback(data, when);
},
error: function (xhr) {
failure_callback(xhr)
},
})
};
ContentNode.prototype.toString = function () {
return "<Content node " + this.path + ">";
}
var content_node_manager = function () {
/* A singleton utility for getting and removing content node objects.
"Getting" means finding existing ones or else allocating new ones.
*/
// Type of newly minted nodes are according to get parameters.
// TODO: Delete node when ascending above them.
// TODO Probably:
// - prefetch offspring layer and defer release til 2 layers above.
// - make fetch of multiple items contingent to device lastcommit time.
var by_path = {};
var root;
return {
get: function (path, parent) {
/* Retrieve a node, according to 'path' and 'parent'.
This is where nodes are minted, when first encountered.
*/
got = by_path[path];
if (! got) {
if (path === my.storage_root_path) {
got = new RootStorageNode(path, parent);
root = got; }
else if (!root) {
// Shouldn't happen.
throw new Error("content_node_manager.get:"
+ " Content visit before root"
+ " established"); }
else if (parent === root) {
got = new DeviceStorageNode(path, parent); }
else if (path[path.length-1] !== "/") {
// No trailing slash.
got = new FileStorageNode(path, parent); }
else {
got = new DirectoryStorageNode(path, parent); }
by_path[path] = got;
}
return got;
},
delete: function (node) {
/* Remove a content node object, eliminating references
that could be circular and prevent GC. */
delete by_path[node.path];
delete node;
}
}
}()
function is_content_visit(url) {
/* True if url within content locations recognized in this session. */
for (var i in my.content_url_roots) {
var prospect = my.content_url_roots[i];
if (url.slice(0, prospect.length) === prospect) { return true; }}
return false; }
function handle_content_visit(e, data) {
/* Handler to intervene in visit:path UI clicks. */
if (typeof data.toPage === "string" && is_content_visit(data.toPage)) {
var parsed = $.mobile.path.parseUrl(data.toPage);
e.preventDefault();
blather("handle_content_visit visit detected: " + parsed.pathname);
content_node_manager.get(parsed.pathname).visit();
}
}
/* public: */
return {
init: function () {
/* Establish event handlers, etc. */
blather("spideroak object init...");
$(document).bind("pagebeforechange", handle_content_visit);
},
toString: function () {
var user = (my.username ? my.username : "-");
var fetched = (Object.keys(content_node_manager).length || "-");
return ("SpiderOak instance for "
+ user + ", " + fetched + " items fetched");
},
/* Login and account/identity. */
remote_login: function (login_info, url) {
/* Login to storage account and commence browsing at the devices.
We provide for redirection to specific alternative servers
by recursive calls. See:
https://spideroak.com/apis/partners/web_storage_api#Loggingin
*/
var parsed = $.mobile.path.parseUrl(url);
var login_url;
var server_host_url;
if (url && $.inArray(parsed.protocol, ["http:", "https:"])) {
server_host_url = parsed.domain;
login_url = url;
} else {
server_host_url = defaults.starting_host_url;
login_url = (server_host_url + defaults.storage_login_path);
}
$.ajax({
url: login_url,
type: 'POST',
dataType: 'text',
data: login_info,
success: function (data) {
var match = data.match(/^(login|location):(.+)$/m);
if (!match) {
error_alert('Temporary server failure. Please'
+ ' try again in a few minutes.');
} else if (match[1] === 'login') {
if (match[2].charAt(0) === "/") {
login_url = server_host_url + match[2];
} else {
login_url = match[2];
}
spideroak.remote_login(login_info, login_url);
} else {
// Browser haz auth cookies, we haz relative location.
// Go there, and machinery will intervene to handle it.
$.mobile.changePage(set_account(login_info['username'],
server_host_url,
defaults.storage_path,
match[2]));
}
},
error: function (xhr) {
error_alert("SpiderOak Login", xhr.status);
}
});
},
}
}();
/* Handy notes. */
/* API v1: per https://spideroak.com/apis/partners/web_storage_api */
/* Proposed API v2: https://spideroak.com/pandora/wiki/NewJsonObjectApi */
/* Device storage node example json data:
{"stats": {"firstname": "ken", "lastname": "manheimer",
"devices": 2, "backupsize": "1.784 GB",
"billing_url": "https://spideroak.com/user/validate?hmac=69...",
"size": 3},
"devices": [{"encoded": "Some%20Laptop%20Computer/",
"name": "Some Laptop Computer",
"lastlogin": 1335452245, "lastcommit": 1335464711},
{"encoded": "Server%20%2F%20Colorful/",
"name": " Server / Colorful",
"lastlogin": 1335464648, "lastcommit": 1335464699}]}
*/
| SpiderOak.js | /* SpiderOak html5 client Main app.
* Works with:
* - jquery.mobile-1.0.1.css
* - jquery-1.6.4.js
* - jquery.mobile-1.0.1.js
* - misc.js - b32encode_trim(), blather(), error_alert()
*/
/*
This machinery intercepts navigation to content repository URLs and
it intervenes by means of binding handle_content_visit to jQuery mobile
"pagebeforechange" event.
*/
SO_DEBUGGING = true; // for misc.js:blather()
$(document).ready(function () {
spideroak.init();
$('.nav_login_storage form').submit(function () {
var username = $('input[name=username]', this).val();
var password = $('input[name=password]', this).val();
spideroak.remote_login({username: username, password: password});
return false;
});
});
/* Modular singleton pattern: */
var spideroak = function () {
/* private: */
var defaults = {
// API v1.
// XXX host_url may need variability according to brand package.
host_url: "https://spideroak.com",
storage_login_path: "/browse/login",
storage_path: "/storage/",
share_path: "/share/",
storage_root_page_id: "storage-root",
devices_query_string: '?device_info=yes',
}
var my = {
host_url: null,
storage_path: null,
username: null,
storage_web_url: null, // Location of storage web UI for user.
// Accumulate content_url_stems on access to various content repos.
content_url_stems: [], // Observed prefixes for user's content URLs.
}
function set_account(username, domain, storage_path, storage_web_url) {
/* Register user-specific storage details, returning storage root URL.
*/
my.username = username;
my.storage_domain = domain;
my.storage_root_path = storage_path + b32encode_trim(username) + "/";
my.storage_root_url = domain + my.storage_root_path;
my.content_url_stems.push(my.storage_root_url);
my.storage_web_url = storage_web_url;
return my.storage_root_url;
}
/* Various content node types - the root, devices, directories, and
files - are implemented based on a generic ContentNode object.
Departures from the basic functionality are implemented as distinct
prototype functions defined immediately after the generic ones.
The generic functions are for the more prevalent container-style nodes.
*/
function ContentNode(path, parent) {
/* Basis for representing collections of remote content items.
- 'path' is relative to the collection's root (top) node.
All paths should start with '/'.
- 'parent' is containing node. The root's parent is null.
See 'Device storage node example json data' below for example JSON.
*/
if ( !(this instanceof ContentNode) ) // Coding failsafe.
throw new Error("Constructor called as a function");
if (path) { // Skip if we're in prototype assignment.
this.path = path;
this.root_path = parent ? parent.root_path : path;
this.parent_path = parent ? parent.path : null;
this.is_container = true;
this.subdirs = []; // Paths of contained devices, directories.
this.files = []; // Paths of contained files.
this.set_page_id();
this.lastfetched = false;
}
}
function StorageNode(path, parent) {
ContentNode.call(this, path, parent);
// All but the root storage nodes are contained within a device.
// The DeviceStorageNode sets the device path, which will trickle
// down to all its contents.
this.device_path = parent ? parent.device_path : null;
}
StorageNode.prototype = new ContentNode();
function ShareNode(path, parent) {
ContentNode.call(this, path, parent);
if (! parent) {
// This is a share room, which is the root of the collection.
this.root_path = path; }
else {
this.root_path = parent.root_path; }
}
ShareNode.prototype = new ContentNode();
function RootStorageNode(path, parent) {
StorageNode.call(this, path, parent);
this.stats = null;
delete this.files; }
RootStorageNode.prototype = new StorageNode();
function RootShareNode(path, parent) {
ShareNode.call(this, path, parent); }
RootShareNode.prototype = new ShareNode();
function DeviceStorageNode(path, parent) {
StorageNode.call(this, path, parent);
this.device_path = path; }
DeviceStorageNode.prototype = new StorageNode();
function DirectoryStorageNode(path, parent) {
StorageNode.call(this, path, parent); }
function DirectoryShareNode(path, parent) {
ShareNode.call(this, path, parent); }
DirectoryShareNode.prototype = new ShareNode();
function FileStorageNode(path, parent) {
StorageNode.call(this, path, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileStorageNode.prototype = new StorageNode();
function FileShareNode(path, parent) {
ShareNode.call(this, path, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileShareNode.prototype = new ShareNode();
ContentNode.prototype.visit = function () {
/* Get up-to-date with remote copy and show. */
if (! this.up_to_date()) {
// We use 'this_node' because 'this' gets overridden when
// success_handler is actually running, so we another
// lexically scoped var.
var this_node = this;
var success_handler = function (data, when) {
this_node.provision(data, when);
this_node.show();
}
this.fetch_and_dispatch(success_handler,
this_node.handle_failed_visit);
} else {
this.show();
}
}
ContentNode.prototype.handle_failed_visit = function (xhr) {
/* Do error handling failed visit with 'xhr' XMLHttpResponse report. */
// TODO: Proper error handling.
error_alert("Failure reaching " + this.path, xhr.status);
}
ContentNode.prototype.provision = function (data, when) {
/* Populate node with JSON 'data'. 'when' is the data's current-ness.
'when' should be no more recent than the XMLHttpRequest.
*/
this.provision_preliminaries(data, when);
this.provision_populate(data, when);
}
ContentNode.prototype.provision_preliminaries = function (data, when) {
/* Do provisioning stuff generally useful for derived types. */
if (! when) {
throw new Error("Node provisioning without reliable time stamp.");
}
this.up_to_date(when);
}
ContentNode.prototype.provision_populate = function (data, when) {
/* Stub, must be overridden by type-specific provisionings. */
throw new Error("Type-specific provisioning implementation missing.")
}
RootStorageNode.prototype.provision_populate = function (data, when) {
/* Embody the root content item with 'data'. */
var mgr = content_node_manager
var dev, devdata;
mgr.stats = data["stats"]; // TODO: We'll cook stats when UI is ready.
for (var i in data.devices) {
devdata = data.devices[i];
path = my.storage_root_path + devdata["encoded"]
dev = mgr.get(path, this)
dev.name = devdata["name"];
dev.lastlogin = devdata["lastlogin"];
dev.lastcommit = devdata["lastcommit"];
if (! ($.inArray(path, this.sub) >= 0)) {
this.sub.push(path);
}
}
this.lastfetched = when;
}
ContentNode.prototype.show = function () {
/* Present self in the UI. */
var page_id = this.get_page_id();
var page = $("#" + page_id);
// >>>
blather(this + ".show() " + " on page " + page_id);
}
ContentNode.prototype.is_storage_root = function () {
/* True if the node is a storage root item. */
return (this.path === my.storage_root_path);
}
ContentNode.prototype.set_page_id = function () {
/* Set the UI page id, acording to stored characteristics. */
// TODO: Actually allocate and manage pages per node.
this.page_id = (this.parent
? this.parent.get_page_id()
: defaults.storage_root_page_id);
}
ContentNode.prototype.get_page_id = function () {
/* Return the UI page id. */
return this.page_id;
}
ContentNode.prototype.up_to_date = function (when) {
/* True if provisioned data is current.
Optional 'when' specifies (new) time we were fetched. */
if (when) {this.lastfetched = when;}
if (! this.lastfetched) { return false; }
// XXX: Currently, never up to date! Must actually test against the
// device lastcommit time.
else { return (this.lastfetched >= new Date().getTime()); }
}
ContentNode.prototype.fetch_and_dispatch = function (success_callback,
failure_callback) {
/* Retrieve this node's data and conduct specified actions accordingly.
- On success, 'success_callback' gets retrived data and Date() just
prior to the retrieval.
- Otherwise, 'failure_callback' invoked with XMLHttpResponse object.
*/
var storage_url = my.storage_domain + this.path;
var when = new Date();
if (this.is_storage_root()) {
storage_url += defaults.devices_query_string; }
$.ajax({url: storage_url,
type: 'GET',
dataType: 'json',
success: function (data) {
success_callback(data, when);
},
error: function (xhr) {
failure_callback(xhr)
},
})
};
ContentNode.prototype.toString = function () {
return "<Content node " + this.path + ">";
}
var content_node_manager = function () {
/* A singleton utility for getting and removing content node objects.
"Getting" means finding existing ones or else allocating new ones.
*/
// Type of newly minted nodes are according to get parameters.
// TODO: Delete node when ascending above them.
// TODO Probably:
// - prefetch offspring layer and defer release til 2 layers above.
// - make fetch of multiple items contingent to device lastcommit time.
var by_path = {};
var root;
return {
get: function (path, parent) {
/* Retrieve a node, according to 'path' and 'parent'.
This is where nodes are minted, when first encountered.
*/
got = by_path[path];
if (! got) {
if (path === my.storage_root_path) {
got = new RootStorageNode(path, parent);
root = got; }
else if (!root) {
// Shouldn't happen.
throw new Error("content_node_manager.get:"
+ " Content visit before root"
+ " established"); }
else if (parent === root) {
got = new DeviceStorageNode(path, parent); }
else if (path[path.length-1] !== "/") {
// No trailing slash.
got = new FileStorageNode(path, parent); }
else {
got = new DirectoryStorageNode(path, parent); }
by_path[path] = got;
}
return got;
},
delete: function (node) {
/* Remove a content node object, eliminating references
that could be circular and prevent GC. */
delete by_path[node.path];
delete node;
}
}
}()
function is_content_visit(url) {
/* True if url within content locations recognized in this session. */
for (var i in my.content_url_stems) {
var prospect = my.content_url_stems[i];
if (url.slice(0, prospect.length) === prospect) { return true; }}
return false; }
function handle_content_visit(e, data) {
/* Handler to intervene in visit:path UI clicks. */
if (typeof data.toPage === "string" && is_content_visit(data.toPage)) {
var parsed = $.mobile.path.parseUrl(data.toPage);
e.preventDefault();
blather("handle_content_visit visit detected: " + parsed.pathname);
content_node_manager.get(parsed.pathname).visit();
}
}
/* public: */
return {
init: function () {
/* Establish event handlers, etc. */
blather("spideroak object init...");
$(document).bind("pagebeforechange", handle_content_visit);
},
toString: function () {
var user = (my.username ? my.username : "-");
var fetched = (Object.keys(content_node_manager).length || "-");
return ("SpiderOak instance for "
+ user + ", " + fetched + " items fetched");
},
/* Login and account/identity. */
remote_login: function (login_info, url) {
/* Login to storage account and commence browsing at the devices.
We provide for redirection to specific alternative servers
by recursive calls. See:
https://spideroak.com/apis/partners/web_storage_api#Loggingin
*/
var parsed = $.mobile.path.parseUrl(url);
var login_url;
var server_host_url;
if (url && $.inArray(parsed.protocol, ["http:", "https:"])) {
server_host_url = parsed.domain;
login_url = url;
} else {
server_host_url = defaults.host_url;
login_url = (server_host_url + defaults.storage_login_path);
}
$.ajax({
url: login_url,
type: 'POST',
dataType: 'text',
data: login_info,
success: function (data) {
var match = data.match(/^(login|location):(.+)$/m);
if (!match) {
error_alert('Temporary server failure. Please'
+ ' try again in a few minutes.');
} else if (match[1] === 'login') {
if (match[2].charAt(0) === "/") {
login_url = server_host_url + match[2];
} else {
login_url = match[2];
}
spideroak.remote_login(login_info, login_url);
} else {
// Browser haz auth cookies, we haz relative location.
// Go there, and machinery will intervene to handle it.
$.mobile.changePage(set_account(login_info['username'],
server_host_url,
defaults.storage_path,
match[2]));
}
},
error: function (xhr) {
error_alert("SpiderOak Login", xhr.status);
}
});
},
}
}();
/* Handy notes. */
/* API v1: per https://spideroak.com/apis/partners/web_storage_api */
/* Proposed API v2: https://spideroak.com/pandora/wiki/NewJsonObjectApi */
/* Device storage node example json data:
{"stats": {"firstname": "ken", "lastname": "manheimer",
"devices": 2, "backupsize": "1.784 GB",
"billing_url": "https://spideroak.com/user/validate?hmac=69...",
"size": 3},
"devices": [{"encoded": "Some%20Laptop%20Computer/",
"name": "Some Laptop Computer",
"lastlogin": 1335452245, "lastcommit": 1335464711},
{"encoded": "Server%20%2F%20Colorful/",
"name": " Server / Colorful",
"lastlogin": 1335464648, "lastcommit": 1335464699}]}
*/
| More accurately illuminating names for some pervasive variables.
| SpiderOak.js | More accurately illuminating names for some pervasive variables. | <ide><path>piderOak.js
<ide> /* private: */
<ide> var defaults = {
<ide> // API v1.
<del> // XXX host_url may need variability according to brand package.
<del> host_url: "https://spideroak.com",
<add> // XXX starting_host_url may vary according to brand package.
<add> starting_host_url: "https://spideroak.com",
<ide> storage_login_path: "/browse/login",
<ide> storage_path: "/storage/",
<ide> share_path: "/share/",
<ide> devices_query_string: '?device_info=yes',
<ide> }
<ide> var my = {
<del> host_url: null,
<add> starting_host_url: null,
<ide> storage_path: null,
<ide> username: null,
<ide> storage_web_url: null, // Location of storage web UI for user.
<del> // Accumulate content_url_stems on access to various content repos.
<del> content_url_stems: [], // Observed prefixes for user's content URLs.
<add> // Accumulate content_url_roots on access to various content repos
<add> // - the storage repo root, various share rooms.
<add> content_url_roots: [], // Observed prefixes for user's content URLs.
<ide> }
<ide>
<ide> function set_account(username, domain, storage_path, storage_web_url) {
<ide> my.storage_root_path = storage_path + b32encode_trim(username) + "/";
<ide> my.storage_root_url = domain + my.storage_root_path;
<ide>
<del> my.content_url_stems.push(my.storage_root_url);
<add> // content_url_roots are for discerning URLs of contained items.
<add> my.content_url_roots.push(my.storage_root_url);
<ide> my.storage_web_url = storage_web_url;
<ide> return my.storage_root_url;
<ide> }
<ide> dev.name = devdata["name"];
<ide> dev.lastlogin = devdata["lastlogin"];
<ide> dev.lastcommit = devdata["lastcommit"];
<del> if (! ($.inArray(path, this.sub) >= 0)) {
<del> this.sub.push(path);
<add> if (! ($.inArray(path, this.subdirs) >= 0)) {
<add> this.subdirs.push(path);
<ide> }
<ide> }
<ide> this.lastfetched = when;
<ide>
<ide> function is_content_visit(url) {
<ide> /* True if url within content locations recognized in this session. */
<del> for (var i in my.content_url_stems) {
<del> var prospect = my.content_url_stems[i];
<add> for (var i in my.content_url_roots) {
<add> var prospect = my.content_url_roots[i];
<ide> if (url.slice(0, prospect.length) === prospect) { return true; }}
<ide> return false; }
<ide> function handle_content_visit(e, data) {
<ide> server_host_url = parsed.domain;
<ide> login_url = url;
<ide> } else {
<del> server_host_url = defaults.host_url;
<add> server_host_url = defaults.starting_host_url;
<ide> login_url = (server_host_url + defaults.storage_login_path);
<ide> }
<ide> $.ajax({ |
|
Java | apache-2.0 | 4306257c42cd93e7defcaec73a30e1f08d3748ae | 0 | ptrd/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,ptrd/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins,Sausageo/jmeter-plugins | package kg.apc.jmeter.vizualizers;
import kg.apc.jmeter.util.TestJMeterUtils;
import org.apache.jmeter.samplers.SampleResult;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author undera
*/
public class AbstractOverTimeVisualizerTest {
public AbstractOverTimeVisualizerTest() {
}
@BeforeClass
public static void setUpClass() throws Exception
{
TestJMeterUtils.createJmeterEnv();
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of add method, of class AbstractOverTimeVisualizer.
*/
@Test
public void testAdd()
{
System.out.println("add");
SampleResult sample = new SampleResult();
AbstractOverTimeVisualizer instance = new AbstractOverTimeVisualizerImpl();
instance.add(sample);
}
public class AbstractOverTimeVisualizerImpl extends AbstractOverTimeVisualizer
{
@Override
protected JSettingsPanel getSettingsPanel()
{
return new JSettingsPanel(this, isStats, isStats, isStats, isStats, isStats);
}
public String getLabelResource()
{
return "";
}
@Override
public String getStaticLabel()
{
return "TEST";
}
}
@Test
public void testClearData()
{
System.out.println("clearData");
AbstractOverTimeVisualizer instance = new AbstractOverTimeVisualizerImpl();
instance.clearData();
fail("The test case is a prototype.");
}
} | test/kg/apc/jmeter/vizualizers/AbstractOverTimeVisualizerTest.java | package kg.apc.jmeter.vizualizers;
import kg.apc.jmeter.util.TestJMeterUtils;
import org.apache.jmeter.samplers.SampleResult;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author undera
*/
public class AbstractOverTimeVisualizerTest {
public AbstractOverTimeVisualizerTest() {
}
@BeforeClass
public static void setUpClass() throws Exception
{
TestJMeterUtils.createJmeterEnv();
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of add method, of class AbstractOverTimeVisualizer.
*/
@Test
public void testAdd()
{
System.out.println("add");
SampleResult sample = new SampleResult();
AbstractOverTimeVisualizer instance = new AbstractOverTimeVisualizerImpl();
instance.add(sample);
}
public class AbstractOverTimeVisualizerImpl extends AbstractOverTimeVisualizer
{
@Override
protected JSettingsPanel getSettingsPanel()
{
return new JSettingsPanel(this, isStats, isStats, isStats, isStats, isStats);
}
public String getLabelResource()
{
return "";
}
@Override
public String getStaticLabel()
{
return "TEST";
}
}
@Test
public void testClearData()
{
System.out.println("clearData");
AbstractOverTimeVisualizer instance = new AbstractOverTimeVisualizerImpl();
instance.clearData();
fail("The test case is a prototype.");
}
} | fixed missing import
| test/kg/apc/jmeter/vizualizers/AbstractOverTimeVisualizerTest.java | fixed missing import | <ide><path>est/kg/apc/jmeter/vizualizers/AbstractOverTimeVisualizerTest.java
<ide> import org.junit.Before;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.Test;
<add>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * |
|
Java | apache-2.0 | deb5146107f4b974c0140d393d25531caa3858c5 | 0 | nevzatekmekci/Android-Contact-App | package com.example.nevzat.semesterproject.activities;
import com.example.nevzat.semesterproject.PersonLab;
import com.example.nevzat.semesterproject.ProjectDbHelper;
import com.example.nevzat.semesterproject.R;
import com.example.nevzat.semesterproject.adapters.SerialAdapter;
import com.example.nevzat.semesterproject.models.Person;
import com.google.android.gms.maps.GoogleMap;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends FragmentActivity {
public GoogleMap googleM;
public ProjectDbHelper dbHelper;
public PersonLab personLab;
public SerialAdapter dataAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
dbHelper = new ProjectDbHelper(this);
personLab = new PersonLab(getApplicationContext());
//Clean all data
personLab.deleteAllContacts();
personLab.addContact(new Person("123", "Nevzat", null,"Ekmekçi", null, null));
personLab.addContact(new Person("234", "Nevzat", null,"Ekmekçi",null, null));
personLab.addContact(new Person("345", "Nevzat", null,"Ekmekçi",null, null));
personLab.addContact(new Person("456", "Nevzat", null,"Ekmekçi",null, null));
personLab.addContact(new Person("567", "Nevzat", null,"Ekmekçi",null, null));
ListView listView = (ListView) findViewById(R.id.listView);
List<Person> personList = personLab.getContacts();
dataAdapter = new SerialAdapter(MainActivity.this,personList);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String name =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
Toast.makeText(getApplicationContext(),
name, Toast.LENGTH_SHORT).show();
}
});
}
@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);
}
}
| SemesterProject/app/src/main/java/com/example/nevzat/semesterproject/activities/MainActivity.java | package com.example.nevzat.semesterproject.activities;
import com.example.nevzat.semesterproject.PersonLab;
import com.example.nevzat.semesterproject.ProjectDbHelper;
import com.example.nevzat.semesterproject.R;
import com.example.nevzat.semesterproject.adapters.SerialAdapter;
import com.example.nevzat.semesterproject.models.Person;
import com.google.*;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends FragmentActivity {
public GoogleMap googleM;
public ProjectDbHelper dbHelper;
public PersonLab personLab;
public SerialAdapter dataAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
dbHelper = new ProjectDbHelper(this);
personLab = new PersonLab(getApplicationContext());
//Clean all data
personLab.deleteAllContacts();
personLab.addContact(new Person("123", "Nevzat", null, "Ekmekçi", null, null));
personLab.addContact(new Person("234", "Nevzat", null,"Ekmekçi",null, null));
personLab.addContact(new Person("345", "Nevzat", null,"Ekmekçi",null, null));
personLab.addContact(new Person("456", "Nevzat", null,"Ekmekçi",null, null));
personLab.addContact(new Person("567", "Nevzat", null,"Ekmekçi",null, null));
ListView listView = (ListView) findViewById(R.id.listView);
List<Person> personList = personLab.getContacts();
dataAdapter = new SerialAdapter(MainActivity.this,personList);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String name =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
Toast.makeText(getApplicationContext(),
name, Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@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);
}
}
| Adapter and Main Activity modified.
| SemesterProject/app/src/main/java/com/example/nevzat/semesterproject/activities/MainActivity.java | Adapter and Main Activity modified. | <ide><path>emesterProject/app/src/main/java/com/example/nevzat/semesterproject/activities/MainActivity.java
<ide> import com.example.nevzat.semesterproject.R;
<ide> import com.example.nevzat.semesterproject.adapters.SerialAdapter;
<ide> import com.example.nevzat.semesterproject.models.Person;
<del>import com.google.*;
<del>import com.google.android.gms.maps.CameraUpdateFactory;
<ide> import com.google.android.gms.maps.GoogleMap;
<del>import com.google.android.gms.maps.SupportMapFragment;
<del>import com.google.android.gms.maps.model.LatLng;
<ide>
<ide> import android.database.Cursor;
<ide> import android.os.Bundle;
<ide> import android.support.design.widget.FloatingActionButton;
<ide> import android.support.design.widget.Snackbar;
<ide> import android.support.v4.app.FragmentActivity;
<del>import android.support.v7.app.AppCompatActivity;
<del>import android.support.v7.widget.Toolbar;
<ide> import android.view.View;
<ide> import android.view.Menu;
<ide> import android.view.MenuItem;
<ide> //Clean all data
<ide> personLab.deleteAllContacts();
<ide>
<del> personLab.addContact(new Person("123", "Nevzat", null, "Ekmekçi", null, null));
<add> personLab.addContact(new Person("123", "Nevzat", null,"Ekmekçi", null, null));
<ide> personLab.addContact(new Person("234", "Nevzat", null,"Ekmekçi",null, null));
<ide> personLab.addContact(new Person("345", "Nevzat", null,"Ekmekçi",null, null));
<ide> personLab.addContact(new Person("456", "Nevzat", null,"Ekmekçi",null, null));
<ide> }
<ide> });
<ide>
<del> FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
<del> fab.setOnClickListener(new View.OnClickListener() {
<del> @Override
<del> public void onClick(View view) {
<del> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
<del> .setAction("Action", null).show();
<del> }
<del> });
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | ecfaf557399074ce500529f22ad97da3ae7e45bd | 0 | bassages/homecontrol,bassages/home-server,bassages/homecontrol,bassages/home-server | package nl.homeserver.energie;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import nl.homeserver.DatePeriod;
import nl.homeserver.cache.CacheService;
@Service
public class MeterstandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MeterstandService.class);
private static final String CACHE_NAME_MEEST_RECENTE_METERSTAND_OP_DAG = "meestRecenteMeterstandOpDag";
private static final String TWO_AM = "0 0 2 * * *";
private static final int NR_OF_PAST_DAYS_TO_CLEANUP = 3;
public static final String TOPIC = "/topic/meterstand";
@Autowired
private MeterstandService meterstandServiceProxyWithEnabledCaching; // Needed to make use of use caching annotations
private final MeterstandRepository meterstandRepository;
private final CacheService cacheService;
private final Clock clock;
private final SimpMessagingTemplate messagingTemplate;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Optional<Meterstand> mostRecentlySavedMeterstand = Optional.empty();
public MeterstandService(MeterstandRepository meterstandRepository, CacheService cacheService, Clock clock, SimpMessagingTemplate messagingTemplate) {
this.meterstandRepository = meterstandRepository;
this.cacheService = cacheService;
this.clock = clock;
this.messagingTemplate = messagingTemplate;
}
public Meterstand save(Meterstand meterstand) {
Meterstand savedMeterStand = meterstandRepository.save(meterstand);
mostRecentlySavedMeterstand = Optional.of(savedMeterStand);
messagingTemplate.convertAndSend(TOPIC, meterstand);
return savedMeterStand;
}
@Scheduled(cron = TWO_AM)
public void dailyCleanup() {
LocalDate today = LocalDate.now(clock);
IntStream.rangeClosed(1, NR_OF_PAST_DAYS_TO_CLEANUP)
.forEach(i -> cleanup(today.minusDays(i)));
clearCachesThatUsesPossibleDeletedMeterstanden();
}
private void cleanup(LocalDate day) {
LocalDateTime start = day.atStartOfDay();
LocalDateTime end = start.plusDays(1).minusNanos(1);
List<Meterstand> meterstandenOnDay = meterstandRepository.findByDateTimeBetween(start, end);
Map<Integer, List<Meterstand>> meterstandenByHour = meterstandenOnDay.stream()
.collect(groupingBy(meterstand -> meterstand.getDateTime().getHour()));
meterstandenByHour.values().forEach(this::cleanupMeterStandenInOneHour);
}
private void clearCachesThatUsesPossibleDeletedMeterstanden() {
cacheService.clear(VerbruikKostenOverzichtService.CACHE_NAME_GAS_VERBRUIK_IN_PERIODE);
cacheService.clear(VerbruikKostenOverzichtService.CACHE_NAME_STROOM_VERBRUIK_IN_PERIODE);
}
private void cleanupMeterStandenInOneHour(List<Meterstand> meterstandenInOneHour) {
meterstandenInOneHour.sort(comparing(Meterstand::getDateTime));
if (meterstandenInOneHour.size() >= 2) {
Meterstand firstMeterstandInHour = meterstandenInOneHour.get(0);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Keep first: {} - {}", firstMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(firstMeterstandInHour, SHORT_PREFIX_STYLE));
}
meterstandenInOneHour.remove(firstMeterstandInHour);
Meterstand lastMeterstandInHour = meterstandenInOneHour.get(meterstandenInOneHour.size() - 1);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Keep last: {} - {}", lastMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(lastMeterstandInHour, SHORT_PREFIX_STYLE));
}
meterstandenInOneHour.remove(lastMeterstandInHour);
if (isNotEmpty(meterstandenInOneHour)) {
meterstandenInOneHour.forEach(meterstand -> LOGGER.info("Delete: {}", ReflectionToStringBuilder.toString(meterstand, SHORT_PREFIX_STYLE)));
meterstandRepository.deleteInBatch(meterstandenInOneHour);
}
}
}
public Meterstand getMostRecent() {
return mostRecentlySavedMeterstand.orElseGet(meterstandRepository::getMostRecent);
}
public Meterstand getOldest() {
return meterstandRepository.getOldest();
}
public Meterstand getOldestOfToday() {
LocalDate today = LocalDate.now(clock);
LocalDateTime van = today.atStartOfDay();
LocalDateTime totEnMet = today.atStartOfDay().plusDays(1).minusNanos(1);
Meterstand oudsteStroomStandOpDag = meterstandRepository.getOldestInPeriod(van, totEnMet);
if (oudsteStroomStandOpDag != null) {
// Gas is registered once every hour, in the hour AFTER it actually is used.
// Compensate for that hour
Meterstand oudsteGasStandOpDag = meterstandRepository.getOldestInPeriod(van.plusHours(1), totEnMet.plusHours(1));
if (oudsteGasStandOpDag != null) {
oudsteStroomStandOpDag.setGas(oudsteGasStandOpDag.getGas());
}
}
return oudsteStroomStandOpDag;
}
public List<MeterstandOpDag> getPerDag(DatePeriod period) {
return period.getDays().stream()
.map(this::getMeterstandOpDag)
.collect(toList());
}
private MeterstandOpDag getMeterstandOpDag(LocalDate day) {
return new MeterstandOpDag(day, getMeesteRecenteMeterstandOpDag(day));
}
private Meterstand getMeesteRecenteMeterstandOpDag(LocalDate day) {
LocalDate today = LocalDate.now(clock);
if (day.isAfter(today)) {
return null;
} else if (day.isEqual(today)) {
return getNonCachedMeestRecenteMeterstandOpDag(day);
} else {
return meterstandServiceProxyWithEnabledCaching.getPotentiallyCachedMeestRecenteMeterstandOpDag(day);
}
}
@Cacheable(cacheNames = CACHE_NAME_MEEST_RECENTE_METERSTAND_OP_DAG)
public Meterstand getPotentiallyCachedMeestRecenteMeterstandOpDag(LocalDate day) {
return getNonCachedMeestRecenteMeterstandOpDag(day);
}
private Meterstand getNonCachedMeestRecenteMeterstandOpDag(LocalDate day) {
LocalDateTime van = day.atStartOfDay();
LocalDateTime totEnMet = day.atStartOfDay().plusDays(1).minusNanos(1);
return meterstandRepository.getMostRecentInPeriod(van, totEnMet);
}
}
| src/main/java/nl/homeserver/energie/MeterstandService.java | package nl.homeserver.energie;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import nl.homeserver.DatePeriod;
import nl.homeserver.cache.CacheService;
@Service
public class MeterstandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MeterstandService.class);
private static final String CACHE_NAME_MEEST_RECENTE_METERSTAND_OP_DAG = "meestRecenteMeterstandOpDag";
private static final String TWO_AM = "0 0 2 * * *";
private static final int NR_OF_PAST_DAYS_TO_CLEANUP = 3;
public static final String TOPIC = "/topic/meterstand";
@Autowired
private MeterstandService meterstandServiceProxyWithEnabledCaching; // Needed to make use of use caching annotations
private final MeterstandRepository meterstandRepository;
private final CacheService cacheService;
private final Clock clock;
private final SimpMessagingTemplate messagingTemplate;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Optional<Meterstand> mostRecentlySavedMeterstand = Optional.empty();
public MeterstandService(MeterstandRepository meterstandRepository, CacheService cacheService, Clock clock, SimpMessagingTemplate messagingTemplate) {
this.meterstandRepository = meterstandRepository;
this.cacheService = cacheService;
this.clock = clock;
this.messagingTemplate = messagingTemplate;
}
public Meterstand save(Meterstand meterstand) {
Meterstand savedMeterStand = meterstandRepository.save(meterstand);
mostRecentlySavedMeterstand = Optional.of(savedMeterStand);
messagingTemplate.convertAndSend(TOPIC, meterstand);
return savedMeterStand;
}
@Scheduled(cron = TWO_AM)
public void dailyCleanup() {
LocalDate today = LocalDate.now(clock);
IntStream.rangeClosed(1, NR_OF_PAST_DAYS_TO_CLEANUP)
.forEach(i -> cleanup(today.minusDays(i)));
clearCachesThatUsesPossibleDeletedMeterstanden();
}
private void cleanup(LocalDate day) {
LocalDateTime start = day.atStartOfDay();
LocalDateTime end = start.plusDays(1).minusNanos(1);
List<Meterstand> meterstandenOnDay = meterstandRepository.findByDateTimeBetween(start, end);
Map<Integer, List<Meterstand>> meterstandenByHour = meterstandenOnDay.stream()
.collect(groupingBy(meterstand -> meterstand.getDateTime().getHour()));
meterstandenByHour.values().forEach(this::cleanupMeterStandenInOneHour);
}
private void clearCachesThatUsesPossibleDeletedMeterstanden() {
cacheService.clear(VerbruikKostenOverzichtService.CACHE_NAME_GAS_VERBRUIK_IN_PERIODE);
cacheService.clear(VerbruikKostenOverzichtService.CACHE_NAME_STROOM_VERBRUIK_IN_PERIODE);
}
private void cleanupMeterStandenInOneHour(List<Meterstand> meterstandenInOneHour) {
meterstandenInOneHour.sort(comparing(Meterstand::getDateTime));
if (meterstandenInOneHour.size() >= 2) {
Meterstand firstMeterstandInHour = meterstandenInOneHour.get(0);
LOGGER.info("Keep first: {} - {}", firstMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(firstMeterstandInHour, SHORT_PREFIX_STYLE));
meterstandenInOneHour.remove(firstMeterstandInHour);
Meterstand lastMeterstandInHour = meterstandenInOneHour.get(meterstandenInOneHour.size() - 1);
LOGGER.info("Keep last: {} - {}", lastMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(lastMeterstandInHour, SHORT_PREFIX_STYLE));
meterstandenInOneHour.remove(lastMeterstandInHour);
if (isNotEmpty(meterstandenInOneHour)) {
meterstandenInOneHour.forEach(meterstand -> LOGGER.info("Delete: {}", ReflectionToStringBuilder.toString(meterstand, SHORT_PREFIX_STYLE)));
meterstandRepository.deleteInBatch(meterstandenInOneHour);
}
}
}
public Meterstand getMostRecent() {
return mostRecentlySavedMeterstand.orElseGet(meterstandRepository::getMostRecent);
}
public Meterstand getOldest() {
return meterstandRepository.getOldest();
}
public Meterstand getOldestOfToday() {
LocalDate today = LocalDate.now(clock);
LocalDateTime van = today.atStartOfDay();
LocalDateTime totEnMet = today.atStartOfDay().plusDays(1).minusNanos(1);
Meterstand oudsteStroomStandOpDag = meterstandRepository.getOldestInPeriod(van, totEnMet);
if (oudsteStroomStandOpDag != null) {
// Gas is registered once every hour, in the hour AFTER it actually is used.
// Compensate for that hour
Meterstand oudsteGasStandOpDag = meterstandRepository.getOldestInPeriod(van.plusHours(1), totEnMet.plusHours(1));
if (oudsteGasStandOpDag != null) {
oudsteStroomStandOpDag.setGas(oudsteGasStandOpDag.getGas());
}
}
return oudsteStroomStandOpDag;
}
public List<MeterstandOpDag> getPerDag(DatePeriod period) {
return period.getDays().stream()
.map(this::getMeterstandOpDag)
.collect(toList());
}
private MeterstandOpDag getMeterstandOpDag(LocalDate day) {
return new MeterstandOpDag(day, getMeesteRecenteMeterstandOpDag(day));
}
private Meterstand getMeesteRecenteMeterstandOpDag(LocalDate day) {
LocalDate today = LocalDate.now(clock);
if (day.isAfter(today)) {
return null;
} else if (day.isEqual(today)) {
return getNonCachedMeestRecenteMeterstandOpDag(day);
} else {
return meterstandServiceProxyWithEnabledCaching.getPotentiallyCachedMeestRecenteMeterstandOpDag(day);
}
}
@Cacheable(cacheNames = CACHE_NAME_MEEST_RECENTE_METERSTAND_OP_DAG)
public Meterstand getPotentiallyCachedMeestRecenteMeterstandOpDag(LocalDate day) {
return getNonCachedMeestRecenteMeterstandOpDag(day);
}
private Meterstand getNonCachedMeestRecenteMeterstandOpDag(LocalDate day) {
LocalDateTime van = day.atStartOfDay();
LocalDateTime totEnMet = day.atStartOfDay().plusDays(1).minusNanos(1);
return meterstandRepository.getMostRecentInPeriod(van, totEnMet);
}
}
| Fix Sonar issue
| src/main/java/nl/homeserver/energie/MeterstandService.java | Fix Sonar issue | <ide><path>rc/main/java/nl/homeserver/energie/MeterstandService.java
<ide> if (meterstandenInOneHour.size() >= 2) {
<ide>
<ide> Meterstand firstMeterstandInHour = meterstandenInOneHour.get(0);
<del> LOGGER.info("Keep first: {} - {}", firstMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(firstMeterstandInHour, SHORT_PREFIX_STYLE));
<add> if (LOGGER.isInfoEnabled()) {
<add> LOGGER.info("Keep first: {} - {}", firstMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(firstMeterstandInHour, SHORT_PREFIX_STYLE));
<add> }
<ide> meterstandenInOneHour.remove(firstMeterstandInHour);
<ide>
<ide> Meterstand lastMeterstandInHour = meterstandenInOneHour.get(meterstandenInOneHour.size() - 1);
<del> LOGGER.info("Keep last: {} - {}", lastMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(lastMeterstandInHour, SHORT_PREFIX_STYLE));
<add> if (LOGGER.isInfoEnabled()) {
<add> LOGGER.info("Keep last: {} - {}", lastMeterstandInHour.getDateTime(), ReflectionToStringBuilder.toString(lastMeterstandInHour, SHORT_PREFIX_STYLE));
<add> }
<ide> meterstandenInOneHour.remove(lastMeterstandInHour);
<ide>
<ide> if (isNotEmpty(meterstandenInOneHour)) { |
|
Java | apache-2.0 | b914237a58054593612031a568bc5fc8e71cb79f | 0 | appium/java-client,appium/java-client | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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 io.appium.java_client.remote;
import org.openqa.selenium.remote.CapabilityType;
/**
* The list of Android-specific capabilities. <br>
* Read: <br>
* <a href="https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md#android-only">
* https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md#android-only</a>
*/
public interface AndroidMobileCapabilityType extends CapabilityType {
/**
* Activity name for the Android activity you want to launch from your package.
* This often needs to be preceded by a {@code .} (e.g., {@code .MainActivity}
* instead of {@code MainActivity}). By default this capability is received from the package
* manifest (action: android.intent.action.MAIN , category: android.intent.category.LAUNCHER)
*/
String APP_ACTIVITY = "appActivity";
/**
* Java package of the Android app you want to run. By default this capability is received
* from the package manifest ({@literal @}package attribute value)
*/
String APP_PACKAGE = "appPackage";
/**
* Activity name/names, comma separated, for the Android activity you want to wait for.
* By default the value of this capability is the same as for {@code appActivity}.
* You must set it to the very first focused application activity name in case it is different
* from the one which is set as {@code appActivity} if your capability has {@code appActivity}
* and {@code appPackage}. You can also use wildcards ({@code *}).
*/
String APP_WAIT_ACTIVITY = "appWaitActivity";
/**
* Java package of the Android app you want to wait for.
* By default the value of this capability is the same as for {@code appActivity}
*/
String APP_WAIT_PACKAGE = "appWaitPackage";
/**
* Timeout in milliseconds used to wait for the appWaitActivity to launch (default 20000).
* @since 1.6.0
*/
String APP_WAIT_DURATION = "appWaitDuration";
/**
* Timeout in seconds while waiting for device to become ready.
*/
String DEVICE_READY_TIMEOUT = "deviceReadyTimeout";
/**
* Allow to install a test package which has {@code android:testOnly="true"} in the manifest.
* {@code false} by default
*/
String ALLOW_TEST_PACKAGES = "allowTestPackages";
/**
* Fully qualified instrumentation class. Passed to -w in adb shell
* am instrument -e coverage true -w.
*/
String ANDROID_COVERAGE = "androidCoverage";
/**
* A broadcast action implemented by yourself which is used to dump coverage into file system.
* Passed to -a in adb shell am broadcast -a
*/
String ANDROID_COVERAGE_END_INTENT = "androidCoverageEndIntent";
/**
* (Chrome and webview only) Enable Chromedriver's performance logging (default false).
*
* @deprecated move to {@link MobileCapabilityType#ENABLE_PERFORMANCE_LOGGING}
*/
@Deprecated
String ENABLE_PERFORMANCE_LOGGING = "enablePerformanceLogging";
/**
* Timeout in seconds used to wait for a device to become ready after booting.
*/
String ANDROID_DEVICE_READY_TIMEOUT = "androidDeviceReadyTimeout";
/**
* Port used to connect to the ADB server (default 5037).
*/
String ADB_PORT = "adbPort";
/**
* Devtools socket name. Needed only when tested app is a Chromium embedding browser.
* The socket is open by the browser and Chromedriver connects to it as a devtools client.
*/
String ANDROID_DEVICE_SOCKET = "androidDeviceSocket";
/**
* Timeout in milliseconds used to wait for an apk to install to the device. Defaults to `90000`.
* @since 1.6.0
*/
String ANDROID_INSTALL_TIMEOUT = "androidInstallTimeout";
/**
* The name of the directory on the device in which the apk will be push before install.
* Defaults to {@code /data/local/tmp}
* @since 1.6.5
*/
String ANDROID_INSTALL_PATH = "androidInstallPath";
/**
* Name of avd to launch.
*/
String AVD = "avd";
/**
* How long to wait in milliseconds for an avd to launch and connect to
* ADB (default 120000).
* @since 0.18.0
*/
String AVD_LAUNCH_TIMEOUT = "avdLaunchTimeout";
/**
* How long to wait in milliseconds for an avd to finish its
* boot animations (default 120000).
* @since 0.18.0
*/
String AVD_READY_TIMEOUT = "avdReadyTimeout";
/**
* Additional emulator arguments used when launching an avd.
*/
String AVD_ARGS = "avdArgs";
/**
* Use a custom keystore to sign apks, default false.
*/
String USE_KEYSTORE = "useKeystore";
/**
* Path to custom keystore, default ~/.android/debug.keystore.
*/
String KEYSTORE_PATH = "keystorePath";
/**
* Password for custom keystore.
*/
String KEYSTORE_PASSWORD = "keystorePassword";
/**
* Alias for key.
*/
String KEY_ALIAS = "keyAlias";
/**
* Password for key.
*/
String KEY_PASSWORD = "keyPassword";
/**
* The absolute local path to webdriver executable (if Chromium embedder provides
* its own webdriver, it should be used instead of original chromedriver
* bundled with Appium).
*/
String CHROMEDRIVER_EXECUTABLE = "chromedriverExecutable";
/**
* An array of arguments to be passed to the chromedriver binary when it's run by Appium.
* By default no CLI args are added beyond what Appium uses internally (such as {@code --url-base}, {@code --port},
* {@code --adb-port}, and {@code --log-path}.
* @since 1.12.0
*/
String CHROMEDRIVER_ARGS = "chromedriverArgs";
/**
* The absolute path to a directory to look for Chromedriver executables in, for automatic discovery of compatible
* Chromedrivers. Ignored if {@code chromedriverUseSystemExecutable} is {@code true}
* @since 1.8.0
*/
String CHROMEDRIVER_EXECUTABLE_DIR = "chromedriverExecutableDir";
/**
* The absolute path to a file which maps Chromedriver versions to the minimum Chrome that it supports.
* Ignored if {@code chromedriverUseSystemExecutable} is {@code true}
* @since 1.8.0
*/
String CHROMEDRIVER_CHROME_MAPPING_FILE = "chromedriverChromeMappingFile";
/**
* If true, bypasses automatic Chromedriver configuration and uses the version that comes downloaded with Appium.
* Ignored if {@code chromedriverExecutable} is set. Defaults to {@code false}
* @since 1.9.0
*/
String CHROMEDRIVER_USE_SYSTEM_EXECUTABLE = "chromedriverUseSystemExecutable";
/**
* Numeric port to start Chromedriver on. Note that use of this capability is discouraged as it will cause undefined
* behavior in case there are multiple webviews present. By default Appium will find a free port.
*/
String CHROMEDRIVER_PORT = "chromedriverPort";
/**
* A list of valid ports for Appium to use for communication with Chromedrivers. This capability supports multiple
* webview scenarios. The form of this capability is an array of numeric ports, where array items can themselves be
* arrays of length 2, where the first element is the start of an inclusive range and the second is the end.
* By default, Appium will use any free port.
* @since 1.13.0
*/
String CHROMEDRIVER_PORTS = "chromedriverPorts";
/**
* Sets the chromedriver flag {@code --disable-build-check} for Chrome webview tests.
* @since 1.11.0
*/
String CHROMEDRIVER_DISABLE_BUILD_CHECK = "chromedriverDisableBuildCheck";
/**
* Amount of time to wait for Webview context to become active, in ms. Defaults to 2000.
* @since 1.5.2
*/
String AUTO_WEBVIEW_TIMEOUT = "autoWebviewTimeout";
/**
* Intent action which will be used to start activity
* (default android.intent.action.MAIN).
*/
String INTENT_ACTION = "intentAction";
/**
* Intent category which will be used to start
* activity (default android.intent.category.LAUNCHER).
*/
String INTENT_CATEGORY = "intentCategory";
/**
* Flags that will be used to start activity (default 0x10200000).
*/
String INTENT_FLAGS = "intentFlags";
/**
* Additional intent arguments that will be used to start activity. See
* <a href="https://developer.android.com/reference/android/content/Intent.html">
* Intent arguments</a>.
*/
String OPTIONAL_INTENT_ARGUMENTS = "optionalIntentArguments";
/**
* Doesn't stop the process of the app under test, before starting the app using adb.
* If the app under test is created by another anchor app, setting this false,
* allows the process of the anchor app to be still alive, during the start of
* the test app using adb. In other words, with dontStopAppOnReset set to true,
* we will not include the -S flag in the adb shell am start call.
* With this capability omitted or set to false, we include the -S flag. Default false
* @since 1.4.0
*/
String DONT_STOP_APP_ON_RESET = "dontStopAppOnReset";
/**
* Enable Unicode input, default false.
* @since 1.2.0
*/
String UNICODE_KEYBOARD = "unicodeKeyboard";
/**
* Reset keyboard to its original state, after running Unicode tests with
* unicodeKeyboard capability. Ignored if used alone. Default false
*/
String RESET_KEYBOARD = "resetKeyboard";
/**
* Skip checking and signing of app with debug keys, will work only with
* UiAutomator and not with selendroid, default false.
* @since 1.2.2
*/
String NO_SIGN = "noSign";
/**
* Calls the setCompressedLayoutHierarchy() uiautomator function.
* This capability can speed up test execution, since Accessibility commands will run
* faster ignoring some elements. The ignored elements will not be findable,
* which is why this capability has also been implemented as a toggle-able
* setting as well as a capability. Defaults to false.
*/
String IGNORE_UNIMPORTANT_VIEWS = "ignoreUnimportantViews";
/**
* Disables android watchers that watch for application not responding and application crash,
* this will reduce cpu usage on android device/emulator. This capability will work only with
* UiAutomator and not with selendroid, default false.
* @since 1.4.0
*/
String DISABLE_ANDROID_WATCHERS = "disableAndroidWatchers";
/**
* Allows passing chromeOptions capability for ChromeDriver.
* For more information see
* <a href="https://sites.google.com/a/chromium.org/chromedriver/capabilities">
* chromeOptions</a>.
*/
String CHROME_OPTIONS = "chromeOptions";
/**
* Kill ChromeDriver session when moving to a non-ChromeDriver webview.
* Defaults to false
*/
String RECREATE_CHROME_DRIVER_SESSIONS = "recreateChromeDriverSessions";
/**
* In a web context, use native (adb) method for taking a screenshot, rather than proxying
* to ChromeDriver, default false.
* @since 1.5.3
*/
String NATIVE_WEB_SCREENSHOT = "nativeWebScreenshot";
/**
* The name of the directory on the device in which the screenshot will be put.
* Defaults to /data/local/tmp.
* @since 1.6.0
*/
String ANDROID_SCREENSHOT_PATH = "androidScreenshotPath";
/**
* Set the network speed emulation. Specify the maximum network upload and download speeds. Defaults to {@code full}
*/
String NETWORK_SPEED = "networkSpeed";
/**
* Toggle gps location provider for emulators before starting the session. By default the emulator will have this
* option enabled or not according to how it has been provisioned.
*/
String GPS_ENABLED = "gpsEnabled";
/**
* Set this capability to {@code true} to run the Emulator headless when device display is not needed to be visible.
* {@code false} is the default value. isHeadless is also support for iOS, check XCUITest-specific capabilities.
*/
String IS_HEADLESS = "isHeadless";
/**
* Timeout in milliseconds used to wait for adb command execution. Defaults to {@code 20000}
*/
String ADB_EXEC_TIMEOUT = "adbExecTimeout";
/**
* Sets the locale <a href="https://developer.android.com/reference/java/util/Locale">script</a>.
* @since 1.10.0
*/
String LOCALE_SCRIPT = "localeScript";
/**
* Skip device initialization which includes i.a.: installation and running of Settings app or setting of
* permissions. Can be used to improve startup performance when the device was already used for automation and
* it's prepared for the next automation. Defaults to {@code false}
* @since 1.11.0
*/
String SKIP_DEVICE_INITIALIZATION = "skipDeviceInitialization";
/**
* Have Appium automatically determine which permissions your app requires and
* grant them to the app on install. Defaults to {@code false}. If noReset is {@code true}, this capability doesn't
* work.
*/
String AUTO_GRANT_PERMISSIONS = "autoGrantPermissions";
/**
* Allow for correct handling of orientation on landscape-oriented devices.
* Set to {@code true} to basically flip the meaning of {@code PORTRAIT} and {@code LANDSCAPE}.
* Defaults to {@code false}.
* @since 1.6.4
*/
String ANDROID_NATURAL_ORIENTATION = "androidNaturalOrientation";
/**
* {@code systemPort} used to connect to <a href="https://github.com/appium/appium-uiautomator2-server">
* appium-uiautomator2-server</a> or
* <a href="https://github.com/appium/appium-espresso-driver">appium-espresso-driver</a>.
* The default is {@code 8200} in general and selects one port from {@code 8200} to {@code 8299}
* for appium-uiautomator2-server, it is {@code 8300} from {@code 8300} to {@code 8399} for
* appium-espresso-driver. When you run tests in parallel, you must adjust the port to avoid conflicts. Read
* <a href="https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/parallel-tests.md#parallel-android-tests">
* Parallel Testing Setup Guide</a> for more details.
*/
String SYSTEM_PORT = "systemPort";
/**
* Optional remote ADB server host.
* @since 1.7.0
*/
String REMOTE_ADB_HOST = "remoteAdbHost";
/**
* Skips unlock during session creation. Defaults to {@code false}
*/
String SKIP_UNLOCK = "skipUnlock";
/**
* Unlock the target device with particular lock pattern instead of just waking up the device with a helper app.
* It works with {@code unlockKey} capability. Defaults to undefined. {@code fingerprint} is available only for
* Android 6.0+ and emulators.
* Read <a href="https://github.com/appium/appium-android-driver/blob/master/docs/UNLOCK.md">unlock doc</a> in
* android driver.
*/
String UNLOCK_TYPE = "unlockType";
/**
* A key pattern to unlock used by {@code unlockType}.
*/
String UNLOCK_KEY = "unlockKey";
/**
* Initializing the app under test automatically.
* Appium does not launch the app under test if this is {@code false}. Defaults to {@code true}
*/
String AUTO_LAUNCH = "autoLaunch";
/**
* Skips to start capturing logcat. It might improve performance such as network.
* Log related commands will not work. Defaults to {@code false}.
* @since 1.12.0
*/
String SKIP_LOGCAT_CAPTURE = "skipLogcatCapture";
/**
* A package, list of packages or * to uninstall package/s before installing apks for test.
* {@code '*'} uninstall all of thrid-party packages except for packages which is necessary for Appium to test such
* as {@code io.appium.settings} or {@code io.appium.uiautomator2.server} since Appium already contains the logic to
* manage them.
* @since 1.12.0
*/
String UNINSTALL_OTHER_PACKAGES = "uninstallOtherPackages";
/**
* Set device animation scale zero if the value is {@code true}. After session is complete, Appium restores the
* animation scale to it's original value. Defaults to {@code false}
* @since 1.9.0
*/
String DISABLE_WINDOW_ANIMATION = "disableWindowAnimation";
/**
* Specify the Android build-tools version to be something different than the default, which is to use the most
* recent version. It is helpful to use a non-default version if your environment uses alpha/beta build tools.
* @since 1.14.0
*/
String BUILD_TOOLS_VERSION = "buildToolsVersion";
/**
* By default application installation is skipped if newer or the same version of this app is already present on
* the device under test. Setting this option to {@code true} will enforce Appium to always install the current
* application build independently of the currently installed version of it. Defaults to {@code false}.
* @since 1.16.0
*/
String ENFORCE_APP_INSTALL = "enforceAppInstall";
/**
* Whether or not Appium should augment its webview detection with page detection, guaranteeing that any
* webview contexts which show up in the context list have active pages. This can prevent an error if a
* context is selected where Chromedriver cannot find any pages. Defaults to {@code false}.
* @since 1.15.0
*/
String ENSURE_WEBVIEWS_HAVE_PAGES = "ensureWebviewsHavePages";
/**
* To support the `ensureWebviewsHavePages` feature, it is necessary to open a TCP port for communication with
* the webview on the device under test. This capability allows overriding of the default port of {@code 9222},
* in case multiple sessions are running simultaneously (to avoid port clash), or in case the default port
* is not appropriate for your system.
* @since 1.15.0
*/
String WEBVIEW_DEVTOOLS_PORT = "webviewDevtoolsPort";
/**
* Set the maximum number of remote cached apks which are pushed to the device-under-test's
* local storage. Caching apks remotely speeds up the execution of sequential test cases, when using the
* same set of apks, by avoiding the need to be push an apk to the remote file system every time a
* reinstall is needed. Set this capability to {@code 0} to disable caching. Defaults to {@code 10}.
* @since 1.14.0
*/
String REMOTE_APPS_CACHE_LIMIT = "remoteAppsCacheLimit";
}
| src/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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 io.appium.java_client.remote;
import org.openqa.selenium.remote.CapabilityType;
/**
* The list of Android-specific capabilities. <br>
* Read: <br>
* <a href="https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md#android-only">
* https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md#android-only</a>
*/
public interface AndroidMobileCapabilityType extends CapabilityType {
/**
* Activity name for the Android activity you want to launch from your package.
* This often needs to be preceded by a {@code .} (e.g., {@code .MainActivity}
* instead of {@code MainActivity}). By default this capability is received from the package
* manifest (action: android.intent.action.MAIN , category: android.intent.category.LAUNCHER)
*/
String APP_ACTIVITY = "appActivity";
/**
* Java package of the Android app you want to run. By default this capability is received
* from the package manifest ({@literal @}package attribute value)
*/
String APP_PACKAGE = "appPackage";
/**
* Activity name/names, comma separated, for the Android activity you want to wait for.
* By default the value of this capability is the same as for {@code appActivity}.
* You must set it to the very first focused application activity name in case it is different
* from the one which is set as {@code appActivity} if your capability has {@code appActivity}
* and {@code appPackage}. You can also use wildcards ({@code *}).
*/
String APP_WAIT_ACTIVITY = "appWaitActivity";
/**
* Java package of the Android app you want to wait for.
* By default the value of this capability is the same as for {@code appActivity}
*/
String APP_WAIT_PACKAGE = "appWaitPackage";
/**
* Timeout in milliseconds used to wait for the appWaitActivity to launch (default 20000).
* @since 1.6.0
*/
String APP_WAIT_DURATION = "appWaitDuration";
/**
* Timeout in seconds while waiting for device to become ready.
*/
String DEVICE_READY_TIMEOUT = "deviceReadyTimeout";
/**
* Allow to install a test package which has {@code android:testOnly="true"} in the manifest.
* {@code false} by default
*/
String ALLOW_TEST_PACKAGES = "allowTestPackages";
/**
* Fully qualified instrumentation class. Passed to -w in adb shell
* am instrument -e coverage true -w.
*/
String ANDROID_COVERAGE = "androidCoverage";
/**
* A broadcast action implemented by yourself which is used to dump coverage into file system.
* Passed to -a in adb shell am broadcast -a
*/
String ANDROID_COVERAGE_END_INTENT = "androidCoverageEndIntent";
/**
* (Chrome and webview only) Enable Chromedriver's performance logging (default false).
*
* @deprecated move to {@link MobileCapabilityType#ENABLE_PERFORMANCE_LOGGING}
*/
@Deprecated
String ENABLE_PERFORMANCE_LOGGING = "enablePerformanceLogging";
/**
* Timeout in seconds used to wait for a device to become ready after booting.
*/
String ANDROID_DEVICE_READY_TIMEOUT = "androidDeviceReadyTimeout";
/**
* Port used to connect to the ADB server (default 5037).
*/
String ADB_PORT = "adbPort";
/**
* Devtools socket name. Needed only when tested app is a Chromium embedding browser.
* The socket is open by the browser and Chromedriver connects to it as a devtools client.
*/
String ANDROID_DEVICE_SOCKET = "androidDeviceSocket";
/**
* Timeout in milliseconds used to wait for an apk to install to the device. Defaults to `90000`.
* @since 1.6.0
*/
String ANDROID_INSTALL_TIMEOUT = "androidInstallTimeout";
/**
* The name of the directory on the device in which the apk will be push before install.
* Defaults to {@code /data/local/tmp}
* @since 1.6.5
*/
String ANDROID_INSTALL_PATH = "androidInstallPath";
/**
* Name of avd to launch.
*/
String AVD = "avd";
/**
* How long to wait in milliseconds for an avd to launch and connect to
* ADB (default 120000).
* @since 0.18.0
*/
String AVD_LAUNCH_TIMEOUT = "avdLaunchTimeout";
/**
* How long to wait in milliseconds for an avd to finish its
* boot animations (default 120000).
* @since 0.18.0
*/
String AVD_READY_TIMEOUT = "avdReadyTimeout";
/**
* Additional emulator arguments used when launching an avd.
*/
String AVD_ARGS = "avdArgs";
/**
* Use a custom keystore to sign apks, default false.
*/
String USE_KEYSTORE = "useKeystore";
/**
* Path to custom keystore, default ~/.android/debug.keystore.
*/
String KEYSTORE_PATH = "keystorePath";
/**
* Password for custom keystore.
*/
String KEYSTORE_PASSWORD = "keystorePassword";
/**
* Alias for key.
*/
String KEY_ALIAS = "keyAlias";
/**
* Password for key.
*/
String KEY_PASSWORD = "keyPassword";
/**
* The absolute local path to webdriver executable (if Chromium embedder provides
* its own webdriver, it should be used instead of original chromedriver
* bundled with Appium).
*/
String CHROMEDRIVER_EXECUTABLE = "chromedriverExecutable";
/**
* An array of arguments to be passed to the chromedriver binary when it's run by Appium.
* By default no CLI args are added beyond what Appium uses internally (such as {@code --url-base}, {@code --port},
* {@code --adb-port}, and {@code --log-path}.
* @since 1.12.0
*/
String CHROMEDRIVER_ARGS = "chromedriverArgs";
/**
* The absolute path to a directory to look for Chromedriver executables in, for automatic discovery of compatible
* Chromedrivers. Ignored if {@code chromedriverUseSystemExecutable} is {@code true}
* @since 1.8.0
*/
String CHROMEDRIVER_EXECUTABLE_DIR = "chromedriverExecutableDir";
/**
* The absolute path to a file which maps Chromedriver versions to the minimum Chrome that it supports.
* Ignored if {@code chromedriverUseSystemExecutable} is {@code true}
* @since 1.8.0
*/
String CHROMEDRIVER_CHROME_MAPPING_FILE = "chromedriverChromeMappingFile";
/**
* If true, bypasses automatic Chromedriver configuration and uses the version that comes downloaded with Appium.
* Ignored if {@code chromedriverExecutable} is set. Defaults to {@code false}
* @since 1.9.0
*/
String CHROMEDRIVER_USE_SYSTEM_EXECUTABLE = "chromedriverUseSystemExecutable";
/**
* Numeric port to start Chromedriver on. Note that use of this capability is discouraged as it will cause undefined
* behavior in case there are multiple webviews present. By default Appium will find a free port.
*/
String CHROMEDRIVER_PORT = "chromedriverPort";
/**
* A list of valid ports for Appium to use for communication with Chromedrivers. This capability supports multiple
* webview scenarios. The form of this capability is an array of numeric ports, where array items can themselves be
* arrays of length 2, where the first element is the start of an inclusive range and the second is the end.
* By default, Appium will use any free port.
* @since 1.13.0
*/
String CHROMEDRIVER_PORTS = "chromedriverPorts";
/**
* Sets the chromedriver flag {@code --disable-build-check} for Chrome webview tests.
* @since 1.11.0
*/
String CHROMEDRIVER_DISABLE_BUILD_CHECK = "chromedriverDisableBuildCheck";
/**
* Amount of time to wait for Webview context to become active, in ms. Defaults to 2000.
* @since 1.5.2
*/
String AUTO_WEBVIEW_TIMEOUT = "autoWebviewTimeout";
/**
* Intent action which will be used to start activity
* (default android.intent.action.MAIN).
*/
String INTENT_ACTION = "intentAction";
/**
* Intent category which will be used to start
* activity (default android.intent.category.LAUNCHER).
*/
String INTENT_CATEGORY = "intentCategory";
/**
* Flags that will be used to start activity (default 0x10200000).
*/
String INTENT_FLAGS = "intentFlags";
/**
* Additional intent arguments that will be used to start activity. See
* <a href="https://developer.android.com/reference/android/content/Intent.html">
* Intent arguments</a>.
*/
String OPTIONAL_INTENT_ARGUMENTS = "optionalIntentArguments";
/**
* Doesn't stop the process of the app under test, before starting the app using adb.
* If the app under test is created by another anchor app, setting this false,
* allows the process of the anchor app to be still alive, during the start of
* the test app using adb. In other words, with dontStopAppOnReset set to true,
* we will not include the -S flag in the adb shell am start call.
* With this capability omitted or set to false, we include the -S flag. Default false
* @since 1.4.0
*/
String DONT_STOP_APP_ON_RESET = "dontStopAppOnReset";
/**
* Enable Unicode input, default false.
* @since 1.2.0
*/
String UNICODE_KEYBOARD = "unicodeKeyboard";
/**
* Reset keyboard to its original state, after running Unicode tests with
* unicodeKeyboard capability. Ignored if used alone. Default false
*/
String RESET_KEYBOARD = "resetKeyboard";
/**
* Skip checking and signing of app with debug keys, will work only with
* UiAutomator and not with selendroid, default false.
* @since 1.2.2
*/
String NO_SIGN = "noSign";
/**
* Calls the setCompressedLayoutHierarchy() uiautomator function.
* This capability can speed up test execution, since Accessibility commands will run
* faster ignoring some elements. The ignored elements will not be findable,
* which is why this capability has also been implemented as a toggle-able
* setting as well as a capability. Defaults to false.
*/
String IGNORE_UNIMPORTANT_VIEWS = "ignoreUnimportantViews";
/**
* Disables android watchers that watch for application not responding and application crash,
* this will reduce cpu usage on android device/emulator. This capability will work only with
* UiAutomator and not with selendroid, default false.
* @since 1.4.0
*/
String DISABLE_ANDROID_WATCHERS = "disableAndroidWatchers";
/**
* Allows passing chromeOptions capability for ChromeDriver.
* For more information see
* <a href="https://sites.google.com/a/chromium.org/chromedriver/capabilities">
* chromeOptions</a>.
*/
String CHROME_OPTIONS = "chromeOptions";
/**
* Kill ChromeDriver session when moving to a non-ChromeDriver webview.
* Defaults to false
*/
String RECREATE_CHROME_DRIVER_SESSIONS = "recreateChromeDriverSessions";
/**
* In a web context, use native (adb) method for taking a screenshot, rather than proxying
* to ChromeDriver, default false.
* @since 1.5.3
*/
String NATIVE_WEB_SCREENSHOT = "nativeWebScreenshot";
/**
* The name of the directory on the device in which the screenshot will be put.
* Defaults to /data/local/tmp.
* @since 1.6.0
*/
String ANDROID_SCREENSHOT_PATH = "androidScreenshotPath";
/**
* Set the network speed emulation. Specify the maximum network upload and download speeds. Defaults to {@code full}
*/
String NETWORK_SPEED = "networkSpeed";
/**
* Toggle gps location provider for emulators before starting the session. By default the emulator will have this
* option enabled or not according to how it has been provisioned.
*/
String GPS_ENABLED = "gpsEnabled";
/**
* Set this capability to {@code true} to run the Emulator headless when device display is not needed to be visible.
* {@code false} is the default value. isHeadless is also support for iOS, check XCUITest-specific capabilities.
*/
String IS_HEADLESS = "isHeadless";
/**
* Timeout in milliseconds used to wait for adb command execution. Defaults to {@code 20000}
*/
String ADB_EXEC_TIMEOUT = "adbExecTimeout";
/**
* Sets the locale <a href="https://developer.android.com/reference/java/util/Locale">script</a>.
* @since 1.10.0
*/
String LOCALE_SCRIPT = "localeScript";
/**
* Skip device initialization which includes i.a.: installation and running of Settings app or setting of
* permissions. Can be used to improve startup performance when the device was already used for automation and
* it's prepared for the next automation. Defaults to {@code false}
* @since 1.11.0
*/
String SKIP_DEVICE_INITIALIZATION = "skipDeviceInitialization";
/**
* Have Appium automatically determine which permissions your app requires and
* grant them to the app on install. Defaults to {@code false}. If noReset is {@code true}, this capability doesn't
* work.
*/
String AUTO_GRANT_PERMISSIONS = "autoGrantPermissions";
/**
* Allow for correct handling of orientation on landscape-oriented devices.
* Set to {@code true} to basically flip the meaning of {@code PORTRAIT} and {@code LANDSCAPE}.
* Defaults to {@code false}.
* @since 1.6.4
*/
String ANDROID_NATURAL_ORIENTATION = "androidNaturalOrientation";
/**
* {@code systemPort} used to connect to <a href="https://github.com/appium/appium-uiautomator2-server">
* appium-uiautomator2-server</a> or
* <a href="https://github.com/appium/appium-espresso-driver">appium-espresso-driver</a>.
* The default is {@code 8200} in general and selects one port from {@code 8200} to {@code 8299}
* for appium-uiautomator2-server, it is {@code 8300} from {@code 8300} to {@code 8399} for
* appium-espresso-driver. When you run tests in parallel, you must adjust the port to avoid conflicts. Read
* <a href="https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/parallel-tests.md#parallel-android-tests">
* Parallel Testing Setup Guide</a> for more details.
*/
String SYSTEM_PORT = "systemPort";
/**
* Optional remote ADB server host.
* @since 1.7.0
*/
String REMOTE_ADB_HOST = "remoteAdbHost";
/**
* Skips unlock during session creation. Defaults to {@code false}
*/
String SKIP_UNLOCK = "skipUnlock";
/**
* Unlock the target device with particular lock pattern instead of just waking up the device with a helper app.
* It works with {@code unlockKey} capability. Defaults to undefined. {@code fingerprint} is available only for
* Android 6.0+ and emulators.
* Read <a href="https://github.com/appium/appium-android-driver/blob/master/docs/UNLOCK.md">unlock doc</a> in
* android driver.
*/
String UNLOCK_TYPE = "unlockType";
/**
* A key pattern to unlock used by {@code unlockType}.
*/
String UNLOCK_KEY = "unlockKey";
/**
* Initializing the app under test automatically.
* Appium does not launch the app under test if this is {@code false}. Defaults to {@code true}
*/
String AUTO_LAUNCH = "autoLaunch";
/**
* Skips to start capturing logcat. It might improve performance such as network.
* Log related commands will not work. Defaults to {@code false}.
* @since 1.12.0
*/
String SKIP_LOGCAT_CAPTURE = "skipLogcatCapture";
/**
* A package, list of packages or * to uninstall package/s before installing apks for test.
* {@code '*'} uninstall all of thrid-party packages except for packages which is necessary for Appium to test such
* as {@code io.appium.settings} or {@code io.appium.uiautomator2.server} since Appium already contains the logic to
* manage them.
* @since 1.12.0
*/
String UNINSTALL_OTHER_PACKAGES = "uninstallOtherPackages";
/**
* Set device animation scale zero if the value is {@code true}. After session is complete, Appium restores the
* animation scale to it's original value. Defaults to {@code false}
* @since 1.9.0
*/
String DISABLE_WINDOW_ANIMATION = "disableWindowAnimation";
}
| chore: update android capability types (#1326)
| src/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java | chore: update android capability types (#1326) | <ide><path>rc/main/java/io/appium/java_client/remote/AndroidMobileCapabilityType.java
<ide> * @since 1.9.0
<ide> */
<ide> String DISABLE_WINDOW_ANIMATION = "disableWindowAnimation";
<add>
<add> /**
<add> * Specify the Android build-tools version to be something different than the default, which is to use the most
<add> * recent version. It is helpful to use a non-default version if your environment uses alpha/beta build tools.
<add> * @since 1.14.0
<add> */
<add> String BUILD_TOOLS_VERSION = "buildToolsVersion";
<add>
<add> /**
<add> * By default application installation is skipped if newer or the same version of this app is already present on
<add> * the device under test. Setting this option to {@code true} will enforce Appium to always install the current
<add> * application build independently of the currently installed version of it. Defaults to {@code false}.
<add> * @since 1.16.0
<add> */
<add> String ENFORCE_APP_INSTALL = "enforceAppInstall";
<add>
<add> /**
<add> * Whether or not Appium should augment its webview detection with page detection, guaranteeing that any
<add> * webview contexts which show up in the context list have active pages. This can prevent an error if a
<add> * context is selected where Chromedriver cannot find any pages. Defaults to {@code false}.
<add> * @since 1.15.0
<add> */
<add> String ENSURE_WEBVIEWS_HAVE_PAGES = "ensureWebviewsHavePages";
<add>
<add> /**
<add> * To support the `ensureWebviewsHavePages` feature, it is necessary to open a TCP port for communication with
<add> * the webview on the device under test. This capability allows overriding of the default port of {@code 9222},
<add> * in case multiple sessions are running simultaneously (to avoid port clash), or in case the default port
<add> * is not appropriate for your system.
<add> * @since 1.15.0
<add> */
<add> String WEBVIEW_DEVTOOLS_PORT = "webviewDevtoolsPort";
<add>
<add> /**
<add> * Set the maximum number of remote cached apks which are pushed to the device-under-test's
<add> * local storage. Caching apks remotely speeds up the execution of sequential test cases, when using the
<add> * same set of apks, by avoiding the need to be push an apk to the remote file system every time a
<add> * reinstall is needed. Set this capability to {@code 0} to disable caching. Defaults to {@code 10}.
<add> * @since 1.14.0
<add> */
<add> String REMOTE_APPS_CACHE_LIMIT = "remoteAppsCacheLimit";
<ide> } |
|
Java | apache-2.0 | c85824f2fa516a1a0c0426fdc33f13daa9266ba8 | 0 | JNOSQL/diana | package org.apache.diana.api.key;
import org.apache.diana.api.Value;
import java.util.Objects;
public class KeyValue {
private final String key;
private final Value value;
private KeyValue(String key, Value value) {
this.key = Objects.requireNonNull(key, "key is required");
this.value = Objects.requireNonNull(value, "value is required");
}
public static KeyValue of(String key, Value value) {
return new KeyValue(key, value);
}
public String getKey() {
return key;
}
public Value getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KeyValue keyValue = (KeyValue) o;
return Objects.equals(key, keyValue.key) &&
Objects.equals(value, keyValue.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("KeyValue{");
sb.append("key='").append(key).append('\'');
sb.append(", value=").append(value);
sb.append('}');
return sb.toString();
}
}
| diana-api/src/main/java/org/apache/diana/api/key/KeyValue.java | package org.apache.diana.api.key;
import org.apache.diana.api.Value;
import java.util.Objects;
public class KeyValue {
private final String key;
private final Value value;
public KeyValue(String key, Value value) {
this.key = Objects.requireNonNull(key, "key is required");
this.value = Objects.requireNonNull(value, "value is required");
}
public String getKey() {
return key;
}
public Value getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KeyValue keyValue = (KeyValue) o;
return Objects.equals(key, keyValue.key) &&
Objects.equals(value, keyValue.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("KeyValue{");
sb.append("key='").append(key).append('\'');
sb.append(", value=").append(value);
sb.append('}');
return sb.toString();
}
}
| Adds default constructor to KeyValue
| diana-api/src/main/java/org/apache/diana/api/key/KeyValue.java | Adds default constructor to KeyValue | <ide><path>iana-api/src/main/java/org/apache/diana/api/key/KeyValue.java
<ide>
<ide> private final Value value;
<ide>
<del> public KeyValue(String key, Value value) {
<add> private KeyValue(String key, Value value) {
<ide> this.key = Objects.requireNonNull(key, "key is required");
<ide> this.value = Objects.requireNonNull(value, "value is required");
<add> }
<add>
<add> public static KeyValue of(String key, Value value) {
<add> return new KeyValue(key, value);
<ide> }
<ide>
<ide> public String getKey() { |
|
Java | apache-2.0 | 9a77a0aeaf47f25f7e48fffad0556a8eb0320e4b | 0 | apache/geronimo-gshell,apache/geronimo-gshell,apache/geronimo-gshell | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.gshell.wisdom.plugin.bundle;
import org.apache.geronimo.gshell.command.Command;
import org.apache.geronimo.gshell.registry.AliasRegistry;
import org.apache.geronimo.gshell.registry.CommandRegistry;
import org.apache.geronimo.gshell.wisdom.plugin.bundle.BundleSupport;
import java.util.List;
import java.util.Map;
/**
* A bundle of {@link Command} instances.
*
* @version $Rev$ $Date$
*/
public class CommandBundle
extends BundleSupport
{
private final CommandRegistry commandRegistry;
private final AliasRegistry aliasRegistry;
private List<Command> commands;
private Map<String,String> aliases;
public CommandBundle(final CommandRegistry commandRegistry, final AliasRegistry aliasRegistry, final String name) {
super(name);
assert commandRegistry != null;
this.commandRegistry = commandRegistry;
assert aliasRegistry != null;
this.aliasRegistry = aliasRegistry;
}
public List<Command> getCommands() {
return commands;
}
public void setCommands(final List<Command> commands) {
assert commands != null;
this.commands = commands;
}
public Map<String, String> getAliases() {
return aliases;
}
public void setAliases(final Map<String,String> aliases) {
assert aliases != null;
this.aliases = aliases;
}
protected void doEnable() throws Exception {
for (Command command : commands) {
commandRegistry.registerCommand(command);
}
for (String name : aliases.keySet()) {
aliasRegistry.registerAlias(name, aliases.get(name));
}
}
protected void doDisable() throws Exception {
for (Command command : commands) {
commandRegistry.removeCommand(command);
}
for (String name : aliases.keySet()) {
aliasRegistry.removeAlias(name);
}
}
} | gshell-wisdom/gshell-wisdom-core/src/main/java/org/apache/geronimo/gshell/wisdom/plugin/bundle/CommandBundle.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.gshell.wisdom.plugin.bundle;
import org.apache.geronimo.gshell.command.Command;
import org.apache.geronimo.gshell.registry.AliasRegistry;
import org.apache.geronimo.gshell.registry.CommandRegistry;
import org.apache.geronimo.gshell.wisdom.plugin.bundle.BundleSupport;
import java.util.List;
import java.util.Map;
/**
* A bundle of {@link Command} instances.
*
* @version $Rev$ $Date$
*/
public class CommandBundle
extends BundleSupport
{
private final CommandRegistry commandRegistry;
private final AliasRegistry aliasRegistry;
private List<Command> commands;
private Map<String,String> aliases;
public CommandBundle(final CommandRegistry commandRegistry, final AliasRegistry aliasRegistry, final String name) {
super(name);
assert commandRegistry != null;
this.commandRegistry = commandRegistry;
assert aliasRegistry != null;
this.aliasRegistry = aliasRegistry;
}
public List<Command> getCommands() {
return commands;
}
public void setCommands(final List<Command> commands) {
assert commands != null;
this.commands = commands;
}
public Map<String, String> getAliases() {
return aliases;
}
public void setAliases(final Map<String,String> aliases) {
assert aliases != null;
this.aliases = aliases;
}
protected void doEnable() throws Exception {
for (Command command : commands) {
commandRegistry.registerCommand(command);
}
assert aliasRegistry != null;
for (String name : aliases.keySet()) {
aliasRegistry.registerAlias(name, aliases.get(name));
}
}
protected void doDisable() throws Exception {
for (Command command : commands) {
commandRegistry.removeCommand(command);
}
for (String name : aliases.keySet()) {
aliasRegistry.removeAlias(name);
}
}
} | Drop one more assert
git-svn-id: cd28ba526fba5b39766c0a4e72305690b33c2c6e@706531 13f79535-47bb-0310-9956-ffa450edef68
| gshell-wisdom/gshell-wisdom-core/src/main/java/org/apache/geronimo/gshell/wisdom/plugin/bundle/CommandBundle.java | Drop one more assert | <ide><path>shell-wisdom/gshell-wisdom-core/src/main/java/org/apache/geronimo/gshell/wisdom/plugin/bundle/CommandBundle.java
<ide> commandRegistry.registerCommand(command);
<ide> }
<ide>
<del> assert aliasRegistry != null;
<ide> for (String name : aliases.keySet()) {
<ide> aliasRegistry.registerAlias(name, aliases.get(name));
<ide> } |
|
Java | apache-2.0 | 8bf7e1d5bc9834dfcb9e3507111cda3981851539 | 0 | Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,serge-rider/dbeaver | package org.jkiss.dbeaver.model.sql.format.tokenized;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPIdentifierCase;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLSyntaxManager;
import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class SQLFormatterTokenizedTest {
SQLFormatterTokenized formatter = new SQLFormatterTokenized();
@Mock
private SQLFormatterConfiguration configuration;
@Mock
private DBPPreferenceStore preferenceStore;
@Mock
private SQLSyntaxManager syntaxManager;
private SQLDialect dialect = BasicSQLDialect.INSTANCE;
private final String lineBreak = System.getProperty("line.separator");
@Before
public void init() throws Exception {
Mockito.when(configuration.getSyntaxManager()).thenReturn(syntaxManager);
String[] delimiters = new String[]{";"};
Mockito.when(syntaxManager.getStatementDelimiters()).thenReturn(delimiters);
Mockito.when(syntaxManager.getDialect()).thenReturn(dialect);
Mockito.when(syntaxManager.getCatalogSeparator()).thenReturn(".");
Mockito.when(configuration.getKeywordCase()).thenReturn(DBPIdentifierCase.UPPER);
Mockito.when(configuration.getIndentString()).thenReturn("\t");
Mockito.doReturn(preferenceStore).when(configuration).getPreferenceStore();
}
@Test
public void shouldDoDefaultFormat() {
//given
String expectedString = getExpectedString();
String inputString = "SELECT * FROM TABLE1 t WHERE a > 100 AND b BETWEEN 12 AND 45; SELECT t.*, j1.x, j2.y FROM TABLE1 t JOIN JT1 j1 ON j1.a = t.a LEFT OUTER JOIN JT2 j2 ON j2.a = t.a AND j2.b = j1.b WHERE t.xxx NOT NULL; DELETE FROM TABLE1 WHERE a = 1; UPDATE TABLE1 SET a = 2 WHERE a = 1; SELECT table1.id, table2.number, SUM(table1.amount) FROM table1 INNER JOIN table2 ON table.id = table2.table1_id WHERE table1.id IN ( SELECT table1_id FROM table3 WHERE table3.name = 'Foo Bar' AND table3.type = 'unknown_type') GROUP BY table1.id, table2.number ORDER BY table1.id;\n";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldReturnEmptyStringWhenThereIsOnlyOneSpace() {
//given
String expectedString = "";
String inputString = " ";
//when
String format = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, format);
}
@Test
public void shouldMakeUpperCaseForKeywords() {
//given
String expectedString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\tmytable;";
String inputString = "select * from mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldRemoveSpacesBeforeCommentSymbol() {
//given
String expectedString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\ttable1;" + lineBreak + "-- SELECT * FROM mytable;";
String inputString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\ttable1;" + lineBreak +" -- SELECT * FROM mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldAddLineBreakIfScriptStartsWithComment() {
//given
String expectedString = lineBreak + "-- SELECT * FROM mytable;";
String inputString = "-- SELECT * FROM mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldAddLineBreakBeforeBraceBySpecialSetting() {
//given
String expectedString = getExpectedStringWithLineBreakBeforeBraces();
String inputString = "SELECT (SELECT thecol FROM thetable) FROM dual";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_BREAK_BEFORE_CLOSE_BRACKET))).thenReturn(true);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldAddIndentForName() {
//given
String expectedString = "SELECT"+lineBreak + "\tmy_field" + lineBreak + "FROM" + lineBreak + "\tmy_table";
String inputString = "SELECT my_field FROM my_table";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_BREAK_BEFORE_CLOSE_BRACKET))).thenReturn(true);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
private String getExpectedStringWithLineBreakBeforeBraces() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT").append(lineBreak)
.append("\t(").append(lineBreak)
.append("\t\tSELECT").append(lineBreak)
.append("\t\t\tthecol").append(lineBreak)
.append("\t\tFROM").append(lineBreak)
.append("\t\t\tthetable").append(lineBreak)
.append("\t)").append(lineBreak)
.append("FROM").append(lineBreak).append("\tdual");
return sb.toString();
}
private String getExpectedString() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT").append(lineBreak)
.append("\t*").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1 t").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta > 100").append(lineBreak)
.append("\tAND b BETWEEN 12 AND 45;").append(lineBreak).append(lineBreak)
.append("SELECT").append(lineBreak)
.append("\tt.*,").append(lineBreak)
.append("\tj1.x,").append(lineBreak)
.append("\tj2.y").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1 t").append(lineBreak)
.append("JOIN JT1 j1 ON").append(lineBreak)
.append("\tj1.a = t.a").append(lineBreak)
.append("LEFT OUTER JOIN JT2 j2 ON").append(lineBreak)
.append("\tj2.a = t.a").append(lineBreak)
.append("\tAND j2.b = j1.b").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\tt.xxx NOT NULL;").append(lineBreak).append(lineBreak)
.append("DELETE").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta = 1;").append(lineBreak).append(lineBreak)
.append("UPDATE").append(lineBreak)
.append("\tTABLE1").append(lineBreak)
.append("SET").append(lineBreak)
.append("\ta = 2").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta = 1;").append(lineBreak).append(lineBreak)
.append("SELECT").append(lineBreak)
.append("\ttable1.id,").append(lineBreak)
.append("\ttable2.number,").append(lineBreak)
.append("\tSUM(table1.amount)").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\ttable1").append(lineBreak)
.append("INNER JOIN table2 ON").append(lineBreak)
.append("\ttable.id = table2.table1_id").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ttable1.id IN (").append(lineBreak)
.append("\tSELECT").append(lineBreak)
.append("\t\ttable1_id").append(lineBreak)
.append("\tFROM").append(lineBreak)
.append("\t\ttable3").append(lineBreak)
.append("\tWHERE").append(lineBreak)
.append("\t\ttable3.name = 'Foo Bar'").append(lineBreak)
.append("\t\tAND table3.type = 'unknown_type')").append(lineBreak)
.append("GROUP BY").append(lineBreak)
.append("\ttable1.id,").append(lineBreak)
.append("\ttable2.number").append(lineBreak)
.append("ORDER BY").append(lineBreak)
.append("\ttable1.id;").append(lineBreak);
return sb.toString();
}
}
| plugins/org.jkiss.dbeaver.model/tests/org/jkiss/dbeaver/model/sql/format/tokenized/SQLFormatterTokenizedTest.java | package org.jkiss.dbeaver.model.sql.format.tokenized;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPIdentifierCase;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLSyntaxManager;
import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class SQLFormatterTokenizedTest {
SQLFormatterTokenized formatter = new SQLFormatterTokenized();
@Mock
private SQLFormatterConfiguration configuration;
@Mock
private DBPPreferenceStore preferenceStore;
@Mock
private SQLSyntaxManager syntaxManager;
private SQLDialect dialect = BasicSQLDialect.INSTANCE;
private final String lineBreak = System.getProperty("line.separator");
@Before
public void init() throws Exception {
Mockito.when(configuration.getSyntaxManager()).thenReturn(syntaxManager);
String[] delimiters = new String[]{";"};
Mockito.when(syntaxManager.getStatementDelimiters()).thenReturn(delimiters);
Mockito.when(syntaxManager.getDialect()).thenReturn(dialect);
Mockito.when(syntaxManager.getCatalogSeparator()).thenReturn(".");
Mockito.when(configuration.getKeywordCase()).thenReturn(DBPIdentifierCase.UPPER);
Mockito.when(configuration.getIndentString()).thenReturn("\t");
Mockito.doReturn(preferenceStore).when(configuration).getPreferenceStore();
}
@Test
public void shouldDoDefaultFormat() {
//given
String expectedString = getExpectedString();
String inputString = "SELECT * FROM TABLE1 t WHERE a > 100 AND b BETWEEN 12 AND 45; SELECT t.*, j1.x, j2.y FROM TABLE1 t JOIN JT1 j1 ON j1.a = t.a LEFT OUTER JOIN JT2 j2 ON j2.a = t.a AND j2.b = j1.b WHERE t.xxx NOT NULL; DELETE FROM TABLE1 WHERE a = 1; UPDATE TABLE1 SET a = 2 WHERE a = 1; SELECT table1.id, table2.number, SUM(table1.amount) FROM table1 INNER JOIN table2 ON table.id = table2.table1_id WHERE table1.id IN ( SELECT table1_id FROM table3 WHERE table3.name = 'Foo Bar' AND table3.type = 'unknown_type') GROUP BY table1.id, table2.number ORDER BY table1.id;\n";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldReturnEmptyStringWhenThereIsOnlyOneSpace() {
//given
String expectedString = "";
String inputString = " ";
//when
String format = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, format);
}
@Test
public void shouldMakeUpperCaseForKeywords() {
//given
String expectedString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\tmytable;";
String inputString = "select * from mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldRemoveSpacesBeforeCommentSymbol() {
//given
String expectedString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\ttable1;" + lineBreak + "-- SELECT * FROM mytable;";
String inputString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\ttable1;" + lineBreak +" -- SELECT * FROM mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldAddLineBreakIfScriptStartsWithComment() {
//given
String expectedString = lineBreak + "-- SELECT * FROM mytable;";
String inputString = "-- SELECT * FROM mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldAddLineBreakBeforeBraceBySpecialSetting() {
//given
String expectedString = getExpectedStringWithLineBreakBeforeBraces();
String inputString = "SELECT (SELECT thecol FROM thetable) FROM dual";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_BREAK_BEFORE_CLOSE_BRACKET))).thenReturn(true);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldAddIndentForName() {
//given
String expectedString = "SELECT"+lineBreak + "\tmy_field" + lineBreak + "FROM" + lineBreak + "\tmy_table";
String inputString = "SELECT my_field FROM my_table";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_BREAK_BEFORE_CLOSE_BRACKET))).thenReturn(true);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
private String getExpectedStringWithLineBreakBeforeBraces() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT").append(lineBreak)
.append("\t(").append(lineBreak)
.append("\t\tSELECT").append(lineBreak)
.append("\t\t\tthecol").append(lineBreak)
.append("\t\tFROM").append(lineBreak)
.append("\t\t\tthetable").append(lineBreak)
.append("\t)").append(lineBreak)
.append("FROM").append(lineBreak).append("\tdual");
return sb.toString();
}
private String getExpectedString() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT").append(lineBreak)
.append("\t*").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1 t").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta > 100").append(lineBreak)
.append("\tAND b BETWEEN 12 AND 45;").append(lineBreak).append(lineBreak)
.append("SELECT").append(lineBreak)
.append("\tt.*,").append(lineBreak)
.append("\tj1.x,").append(lineBreak)
.append("\tj2.y").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1 t").append(lineBreak)
.append("JOIN JT1 j1 ON").append(lineBreak)
.append("\tj1.a = t.a").append(lineBreak)
.append("LEFT OUTER JOIN JT2 j2 ON").append(lineBreak)
.append("\tj2.a = t.a").append(lineBreak)
.append("\tAND j2.b = j1.b").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\tt.xxx NOT NULL;").append(lineBreak).append(lineBreak)
.append("DELETE").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta = 1;").append(lineBreak).append(lineBreak)
.append("UPDATE").append(lineBreak)
.append("\tTABLE1 SET").append(lineBreak)
.append("\t\ta = 2").append(lineBreak)
.append("\tWHERE").append(lineBreak)
.append("\t\ta = 1;").append(lineBreak).append(lineBreak)
.append("SELECT").append(lineBreak)
.append("\ttable1.id,").append(lineBreak)
.append("\ttable2.number,").append(lineBreak)
.append("\tSUM(table1.amount)").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\ttable1").append(lineBreak)
.append("INNER JOIN table2 ON").append(lineBreak)
.append("\ttable.id = table2.table1_id").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ttable1.id IN (").append(lineBreak)
.append("\tSELECT").append(lineBreak)
.append("\t\ttable1_id").append(lineBreak)
.append("\tFROM").append(lineBreak)
.append("\t\ttable3").append(lineBreak)
.append("\tWHERE").append(lineBreak)
.append("\t\ttable3.name = 'Foo Bar'").append(lineBreak)
.append("\t\tAND table3.type = 'unknown_type')").append(lineBreak)
.append("GROUP BY").append(lineBreak)
.append("\ttable1.id,").append(lineBreak)
.append("\ttable2.number").append(lineBreak)
.append("ORDER BY").append(lineBreak)
.append("\ttable1.id;").append(lineBreak);
return sb.toString();
}
}
| SQL formatting tests fix
Former-commit-id: e9d44f8323e4f94fd39b9100f151e58451bf9e8a | plugins/org.jkiss.dbeaver.model/tests/org/jkiss/dbeaver/model/sql/format/tokenized/SQLFormatterTokenizedTest.java | SQL formatting tests fix | <ide><path>lugins/org.jkiss.dbeaver.model/tests/org/jkiss/dbeaver/model/sql/format/tokenized/SQLFormatterTokenizedTest.java
<ide> .append("WHERE").append(lineBreak)
<ide> .append("\ta = 1;").append(lineBreak).append(lineBreak)
<ide> .append("UPDATE").append(lineBreak)
<del> .append("\tTABLE1 SET").append(lineBreak)
<del> .append("\t\ta = 2").append(lineBreak)
<del> .append("\tWHERE").append(lineBreak)
<del> .append("\t\ta = 1;").append(lineBreak).append(lineBreak)
<add> .append("\tTABLE1").append(lineBreak)
<add> .append("SET").append(lineBreak)
<add> .append("\ta = 2").append(lineBreak)
<add> .append("WHERE").append(lineBreak)
<add> .append("\ta = 1;").append(lineBreak).append(lineBreak)
<ide> .append("SELECT").append(lineBreak)
<ide> .append("\ttable1.id,").append(lineBreak)
<ide> .append("\ttable2.number,").append(lineBreak) |
|
Java | apache-2.0 | 98c2f6ca7bc293257bf40f29977d2df83257ad0b | 0 | songzhw/AndroidTestDemo | package ca.six.todo.tasks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import ca.six.todo.data.Task;
import ca.six.todo.data.source.TasksDataSource;
import ca.six.todo.data.source.TasksRepository;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
public class TasksPresenterTest {
@Mock TasksContract.View view;
@Mock TasksRepository repo;
@Captor ArgumentCaptor<TasksDataSource.LoadTasksCallback> captor;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(view.isActive()).thenReturn(true);
}
@Test
public void testFirstEnters_listShouldBeEmpty(){
TasksPresenter presenter = new TasksPresenter(repo, view);
presenter.start();
verify(view).setLoadingIndicator(true);
verify(repo).refreshTasks();
verify(repo).getTasks(captor.capture());
captor.getValue().onTasksLoaded(new ArrayList<Task>());
// default filter is : All_Tasks
verify(view).showNoTasks();
}
}
| Test-Todo/app/src/test/java/ca/six/todo/tasks/TasksPresenterTest.java | package ca.six.todo.tasks;
import org.junit.Test;
import static org.junit.Assert.*;
public class TasksPresenterTest {
@Test
public void testFirstEnters_listShouldBeEmpty(){
}
} | write unit test code
| Test-Todo/app/src/test/java/ca/six/todo/tasks/TasksPresenterTest.java | write unit test code | <ide><path>est-Todo/app/src/test/java/ca/six/todo/tasks/TasksPresenterTest.java
<ide> package ca.six.todo.tasks;
<ide>
<add>import org.junit.Before;
<ide> import org.junit.Test;
<add>import org.mockito.ArgumentCaptor;
<add>import org.mockito.Captor;
<add>import org.mockito.Mock;
<add>import org.mockito.MockitoAnnotations;
<ide>
<add>import ca.six.todo.data.Task;
<add>import ca.six.todo.data.source.TasksDataSource;
<add>import ca.six.todo.data.source.TasksRepository;
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.Mockito.verify;
<add>import static org.mockito.Mockito.when;
<add>
<add>import java.util.ArrayList;
<ide>
<ide> public class TasksPresenterTest {
<add> @Mock TasksContract.View view;
<add> @Mock TasksRepository repo;
<add> @Captor ArgumentCaptor<TasksDataSource.LoadTasksCallback> captor;
<add>
<add> @Before
<add> public void setUp() {
<add> MockitoAnnotations.initMocks(this);
<add> when(view.isActive()).thenReturn(true);
<add> }
<ide>
<ide> @Test
<ide> public void testFirstEnters_listShouldBeEmpty(){
<add> TasksPresenter presenter = new TasksPresenter(repo, view);
<add> presenter.start();
<ide>
<add> verify(view).setLoadingIndicator(true);
<add> verify(repo).refreshTasks();
<add>
<add> verify(repo).getTasks(captor.capture());
<add> captor.getValue().onTasksLoaded(new ArrayList<Task>());
<add>
<add> // default filter is : All_Tasks
<add> verify(view).showNoTasks();
<ide> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | 8bde3b7e97c0d355d02ffc4c3c6a7235b53d61c7 | 0 | serrapos/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,victos/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,victos/opencms-core,gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,MenZil/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,victos/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsStringUtil.java,v $
* Date : $Date: 2007/09/24 13:59:06 $
* Version: $Revision: 1.47 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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 org.opencms.util;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.I_CmsMessageBundle;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import java.awt.Color;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.oro.text.perl.MalformedPerl5PatternException;
import org.apache.oro.text.perl.Perl5Util;
/**
* Provides String utility functions.<p>
*
* @author Andreas Zahner
* @author Alexander Kandzior
* @author Thomas Weckert
*
* @version $Revision: 1.47 $
*
* @since 6.0.0
*/
public final class CmsStringUtil {
/** Regular expression that matches the HTML body end tag. */
public static final String BODY_END_REGEX = "<\\s*/\\s*body[^>]*>";
/** Regular expression that matches the HTML body start tag. */
public static final String BODY_START_REGEX = "<\\s*body[^>]*>";
/** Constant for <code>"false"</code>. */
public static final String FALSE = Boolean.toString(false);
/** a convenient shorthand to the line separator constant. */
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
/** Context macro. */
public static final String MACRO_OPENCMS_CONTEXT = "${OpenCmsContext}";
/** Contains all chars that end a sentence in the {@link #trimToSize(String, int, int, String)} method. */
public static final char[] SENTENCE_ENDING_CHARS = {'.', '!', '?'};
/** a convenient shorthand for tabulations. */
public static final String TABULATOR = " ";
/** Constant for <code>"true"</code>. */
public static final String TRUE = Boolean.toString(true);
/** Regex pattern that matches an end body tag. */
private static final Pattern BODY_END_PATTERN = Pattern.compile(BODY_END_REGEX, Pattern.CASE_INSENSITIVE);
/** Regex pattern that matches a start body tag. */
private static final Pattern BODY_START_PATTERN = Pattern.compile(BODY_START_REGEX, Pattern.CASE_INSENSITIVE);
/** Day constant. */
private static final long DAYS = 1000 * 60 * 60 * 24;
/** Hour constant. */
private static final long HOURS = 1000 * 60 * 60;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsStringUtil.class);
/** OpenCms context replace String, static for performance reasons. */
private static String m_contextReplace;
/** OpenCms context search String, static for performance reasons. */
private static String m_contextSearch;
/** Minute constant. */
private static final long MINUTES = 1000 * 60;
/** Second constant. */
private static final long SECONDS = 1000;
/** Regex that matches an encoding String in an xml head. */
private static final Pattern XML_ENCODING_REGEX = Pattern.compile(
"encoding\\s*=\\s*[\"'].+[\"']",
Pattern.CASE_INSENSITIVE);
/** Regex that matches an xml head. */
private static final Pattern XML_HEAD_REGEX = Pattern.compile("<\\s*\\?.*\\?\\s*>", Pattern.CASE_INSENSITIVE);
/**
* Default constructor (empty), private because this class has only
* static methods.<p>
*/
private CmsStringUtil() {
// empty
}
/**
* Changes the filename suffix.
*
* @param filename the filename to be changed
* @param suffix the new suffix of the file
*
* @return the filename with the replaced suffix
*/
public static String changeFileNameSuffixTo(String filename, String suffix) {
int dotPos = filename.lastIndexOf('.');
if (dotPos != -1) {
return filename.substring(0, dotPos + 1) + suffix;
} else {
// the string has no suffix
return filename;
}
}
/**
* Checks if a given name is composed only of the characters <code>a...z,A...Z,0...9</code>
* and the provided <code>constraints</code>.<p>
*
* If the check fails, an Exception is generated. The provided bundle and key is
* used to generate the Exception. 4 parameters are passed to the Exception:<ol>
* <li>The <code>name</code>
* <li>The first illegal character found
* <li>The position where the illegal character was found
* <li>The <code>constraints</code></ol>
*
* @param name the name to check
* @param contraints the additional character constraints
* @param key the key to use for generating the Exception (if required)
* @param bundle the bundle to use for generating the Exception (if required)
*
* @throws CmsIllegalArgumentException if the check fails (generated from the given key and bundle)
*/
public static void checkName(String name, String contraints, String key, I_CmsMessageBundle bundle)
throws CmsIllegalArgumentException {
int l = name.length();
for (int i = 0; i < l; i++) {
char c = name.charAt(i);
if (((c < 'a') || (c > 'z'))
&& ((c < '0') || (c > '9'))
&& ((c < 'A') || (c > 'Z'))
&& (contraints.indexOf(c) < 0)) {
throw new CmsIllegalArgumentException(bundle.container(key, new Object[] {
name,
new Character(c),
new Integer(i),
contraints}));
}
}
}
/**
* Returns a string representation for the given collection using the given separator.<p>
*
* @param collection the collection to print
* @param separator the item separator
*
* @return the string representation for the given collection
*/
public static String collectionAsString(Collection collection, String separator) {
StringBuffer string = new StringBuffer(128);
Iterator it = collection.iterator();
while (it.hasNext()) {
string.append(it.next());
if (it.hasNext()) {
string.append(separator);
}
}
return string.toString();
}
/**
* Replaces occurrences of special control characters in the given input with
* a HTML representation.<p>
*
* This method currently replaces line breaks to <code><br/></code> and special HTML chars
* like <code>< > & "</code> with their HTML entity representation.<p>
*
* @param source the String to escape
*
* @return the escaped String
*/
public static String escapeHtml(String source) {
if (source == null) {
return null;
}
source = CmsEncoder.escapeXml(source);
source = CmsStringUtil.substitute(source, "\r", "");
source = CmsStringUtil.substitute(source, "\n", "<br/>\n");
return source;
}
/**
* Escapes a String so it may be used in JavaScript String definitions.<p>
*
* This method replaces line breaks, quotation marks and \ characters.<p>
*
* @param source the String to escape
*
* @return the escaped String
*/
public static String escapeJavaScript(String source) {
source = CmsStringUtil.substitute(source, "\\", "\\\\");
source = CmsStringUtil.substitute(source, "\"", "\\\"");
source = CmsStringUtil.substitute(source, "\'", "\\\'");
source = CmsStringUtil.substitute(source, "\r\n", "\\n");
source = CmsStringUtil.substitute(source, "\n", "\\n");
return source;
}
/**
* Escapes a String so it may be used as a Perl5 regular expression.<p>
*
* This method replaces the following characters in a String:<br>
* <code>{}[]()\$^.*+/</code><p>
*
* @param source the string to escape
*
* @return the escaped string
*/
public static String escapePattern(String source) {
if (source == null) {
return null;
}
StringBuffer result = new StringBuffer(source.length() * 2);
for (int i = 0; i < source.length(); ++i) {
char ch = source.charAt(i);
switch (ch) {
case '\\':
result.append("\\\\");
break;
case '/':
result.append("\\/");
break;
case '$':
result.append("\\$");
break;
case '^':
result.append("\\^");
break;
case '.':
result.append("\\.");
break;
case '*':
result.append("\\*");
break;
case '+':
result.append("\\+");
break;
case '|':
result.append("\\|");
break;
case '?':
result.append("\\?");
break;
case '{':
result.append("\\{");
break;
case '}':
result.append("\\}");
break;
case '[':
result.append("\\[");
break;
case ']':
result.append("\\]");
break;
case '(':
result.append("\\(");
break;
case ')':
result.append("\\)");
break;
default:
result.append(ch);
}
}
return new String(result);
}
/**
* This method takes a part of a html tag definition, an attribute to extend within the
* given text and a default value for this attribute; and returns a <code>{@link Map}</code>
* with 2 values: a <code>{@link String}</code> with key <code>"text"</code> with the new text
* without the given attribute, and another <code>{@link String}</code> with key <code>"value"</code>
* with the new extended value for the given attribute, this value is surrounded by the same type of
* quotation marks as in the given text.<p>
*
* @param text the text to search in
* @param attribute the attribute to remove and extend from the text
* @param defValue a default value for the attribute, should not have any quotation mark
*
* @return a map with the new text and the new value for the given attribute
*/
public static Map extendAttribute(String text, String attribute, String defValue) {
Map retValue = new HashMap();
retValue.put("text", text);
retValue.put("value", "'" + defValue + "'");
if ((text != null) && (text.toLowerCase().indexOf(attribute.toLowerCase()) >= 0)) {
// this does not work for things like "att=method()" without quotations.
String quotation = "\'";
int pos1 = text.toLowerCase().indexOf(attribute.toLowerCase());
// looking for the opening quotation mark
int pos2 = text.indexOf(quotation, pos1);
int test = text.indexOf("\"", pos1);
if ((test > -1) && ((pos2 == -1) || (test < pos2))) {
quotation = "\"";
pos2 = test;
}
// assuming there is a closing quotation mark
int pos3 = text.indexOf(quotation, pos2 + 1);
// building the new attribute value
String newValue = quotation + defValue + text.substring(pos2 + 1, pos3 + 1);
// removing the onload statement from the parameters
String newText = text.substring(0, pos1);
if (pos3 < text.length()) {
newText += text.substring(pos3 + 1);
}
retValue.put("text", newText);
retValue.put("value", newValue);
}
return retValue;
}
/**
* Extracts the content of a <code><body></code> tag in a HTML page.<p>
*
* This method should be pretty robust and work even if the input HTML does not contains
* a valid body tag.<p>
*
* @param content the content to extract the body from
*
* @return the extracted body tag content
*/
public static String extractHtmlBody(String content) {
Matcher startMatcher = BODY_START_PATTERN.matcher(content);
Matcher endMatcher = BODY_END_PATTERN.matcher(content);
int start = 0;
int end = content.length();
if (startMatcher.find()) {
start = startMatcher.end();
}
if (endMatcher.find(start)) {
end = endMatcher.start();
}
return content.substring(start, end);
}
/**
* Extracts the xml encoding setting from an xml file that is contained in a String by parsing
* the xml head.<p>
*
* This is useful if you have a byte array that contains a xml String,
* but you do not know the xml encoding setting. Since the encoding setting
* in the xml head is usually encoded with standard US-ASCII, you usually
* just create a String of the byte array without encoding setting,
* and use this method to find the 'true' encoding. Then create a String
* of the byte array again, this time using the found encoding.<p>
*
* This method will return <code>null</code> in case no xml head
* or encoding information is contained in the input.<p>
*
* @param content the xml content to extract the encoding from
*
* @return the extracted encoding, or null if no xml encoding setting was found in the input
*/
public static String extractXmlEncoding(String content) {
String result = null;
Matcher xmlHeadMatcher = XML_HEAD_REGEX.matcher(content);
if (xmlHeadMatcher.find()) {
String xmlHead = xmlHeadMatcher.group();
Matcher encodingMatcher = XML_ENCODING_REGEX.matcher(xmlHead);
if (encodingMatcher.find()) {
String encoding = encodingMatcher.group();
int pos1 = encoding.indexOf('=') + 2;
String charset = encoding.substring(pos1, encoding.length() - 1);
if (Charset.isSupported(charset)) {
result = charset;
}
}
}
return result;
}
/**
* Formats a resource name that it is displayed with the maximum length and path information is adjusted.<p>
* In order to reduce the length of the displayed names, single folder names are removed/replaced with ... successively,
* starting with the second! folder. The first folder is removed as last.<p>
*
* Example: formatResourceName("/myfolder/subfolder/index.html", 21) returns <code>/myfolder/.../index.html</code>.<p>
*
* @param name the resource name to format
* @param maxLength the maximum length of the resource name (without leading <code>/...</code>)
*
* @return the formatted resource name
*/
public static String formatResourceName(String name, int maxLength) {
if (name == null) {
return null;
}
if (name.length() <= maxLength) {
return name;
}
int total = name.length();
String[] names = CmsStringUtil.splitAsArray(name, "/");
if (name.endsWith("/")) {
names[names.length - 1] = names[names.length - 1] + "/";
}
for (int i = 1; (total > maxLength) && (i < names.length - 1); i++) {
if (i > 1) {
names[i - 1] = "";
}
names[i] = "...";
total = 0;
for (int j = 0; j < names.length; j++) {
int l = names[j].length();
total += l + ((l > 0) ? 1 : 0);
}
}
if (total > maxLength) {
names[0] = (names.length > 2) ? "" : (names.length > 1) ? "..." : names[0];
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < names.length; i++) {
if (names[i].length() > 0) {
result.append("/");
result.append(names[i]);
}
}
return result.toString();
}
/**
* Formats a runtime in the format hh:mm:ss, to be used e.g. in reports.<p>
*
* If the runtime is greater then 24 hours, the format dd:hh:mm:ss is used.<p>
*
* @param runtime the time to format
*
* @return the formatted runtime
*/
public static String formatRuntime(long runtime) {
long seconds = (runtime / SECONDS) % 60;
long minutes = (runtime / MINUTES) % 60;
long hours = (runtime / HOURS) % 24;
long days = runtime / DAYS;
StringBuffer strBuf = new StringBuffer();
if (days > 0) {
if (days < 10) {
strBuf.append('0');
}
strBuf.append(days);
strBuf.append(':');
}
if (hours < 10) {
strBuf.append('0');
}
strBuf.append(hours);
strBuf.append(':');
if (minutes < 10) {
strBuf.append('0');
}
strBuf.append(minutes);
strBuf.append(':');
if (seconds < 10) {
strBuf.append('0');
}
strBuf.append(seconds);
return strBuf.toString();
}
/**
* Returns the color value (<code>{@link Color}</code>) for the given String value.<p>
*
* All parse errors are caught and the given default value is returned in this case.<p>
*
* @param value the value to parse as color
* @param defaultValue the default value in case of parsing errors
* @param key a key to be included in the debug output in case of parse errors
*
* @return the int value for the given parameter value String
*/
public static Color getColorValue(String value, Color defaultValue, String key) {
Color result;
try {
char pre = value.charAt(0);
if (pre != '#') {
value = "#" + value;
}
result = Color.decode(value);
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_UNABLE_TO_PARSE_COLOR_2, value, key));
}
result = defaultValue;
}
return result;
}
/**
* Returns the Integer (int) value for the given String value.<p>
*
* All parse errors are caught and the given default value is returned in this case.<p>
*
* @param value the value to parse as int
* @param defaultValue the default value in case of parsing errors
* @param key a key to be included in the debug output in case of parse errors
*
* @return the int value for the given parameter value String
*/
public static int getIntValue(String value, int defaultValue, String key) {
int result;
try {
result = Integer.valueOf(value).intValue();
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_UNABLE_TO_PARSE_INT_2, value, key));
}
result = defaultValue;
}
return result;
}
/**
* Returns <code>true</code> if the provided String is either <code>null</code>
* or the empty String <code>""</code>.<p>
*
* @param value the value to check
*
* @return true, if the provided value is null or the empty String, false otherwise
*/
public static boolean isEmpty(String value) {
return (value == null) || (value.length() == 0);
}
/**
* Returns <code>true</code> if the provided String is either <code>null</code>
* or contains only white spaces.<p>
*
* @param value the value to check
*
* @return true, if the provided value is null or contains only white spaces, false otherwise
*/
public static boolean isEmptyOrWhitespaceOnly(String value) {
return isEmpty(value) || (value.trim().length() == 0);
}
/**
* Returns <code>true</code> if the provided Objects are either both <code>null</code>
* or equal according to {@link Object#equals(Object)}.<p>
*
* @param value1 the first object to compare
* @param value2 the second object to compare
*
* @return <code>true</code> if the provided Objects are either both <code>null</code>
* or equal according to {@link Object#equals(Object)}
*/
public static boolean isEqual(Object value1, Object value2) {
if (value1 == null) {
return (value2 == null);
}
return value1.equals(value2);
}
/**
* Returns <code>true</code> if the provided String is neither <code>null</code>
* nor the empty String <code>""</code>.<p>
*
* @param value the value to check
*
* @return true, if the provided value is not null and not the empty String, false otherwise
*/
public static boolean isNotEmpty(String value) {
return (value != null) && (value.length() != 0);
}
/**
* Returns <code>true</code> if the provided String is neither <code>null</code>
* nor contains only white spaces.<p>
*
* @param value the value to check
*
* @return <code>true</code>, if the provided value is <code>null</code>
* or contains only white spaces, <code>false</code> otherwise
*/
public static boolean isNotEmptyOrWhitespaceOnly(String value) {
return (value != null) && (value.trim().length() > 0);
}
/**
* Checks if the given class name is a valid Java class name.<p>
*
* @param className the name to check
*
* @return true if the given class name is a valid Java class name
*/
public static boolean isValidJavaClassName(String className) {
if (CmsStringUtil.isEmpty(className)) {
return false;
}
int length = className.length();
boolean nodot = true;
for (int i = 0; i < length; i++) {
char ch = className.charAt(i);
if (nodot) {
if (ch == '.') {
return false;
} else if (Character.isJavaIdentifierStart(ch)) {
nodot = false;
} else {
return false;
}
} else {
if (ch == '.') {
nodot = true;
} else if (Character.isJavaIdentifierPart(ch)) {
nodot = false;
} else {
return false;
}
}
}
return true;
}
/**
* Returns the last index of any of the given chars in the given source.<p>
*
* If no char is found, -1 is returned.<p>
*
* @param source the source to check
* @param chars the chars to find
*
* @return the last index of any of the given chars in the given source, or -1
*/
public static int lastIndexOf(String source, char[] chars) {
// now try to find an "sentence ending" char in the text in the "findPointArea"
int result = -1;
for (int i = 0; i < chars.length; i++) {
int pos = source.lastIndexOf(chars[i]);
if (pos > result) {
// found new last char
result = pos;
}
}
return result;
}
/**
* Returns the last index a whitespace char the given source.<p>
*
* If no whitespace char is found, -1 is returned.<p>
*
* @param source the source to check
*
* @return the last index a whitespace char the given source, or -1
*/
public static int lastWhitespaceIn(String source) {
if (CmsStringUtil.isEmpty(source)) {
return -1;
}
int pos = -1;
for (int i = source.length() - 1; i >= 0; i--) {
if (Character.isWhitespace(source.charAt(i))) {
pos = i;
break;
}
}
return pos;
}
/**
* Returns a string representation for the given map using the given separators.<p>
*
* @param map the map to write
* @param sepItem the item separator string
* @param sepKeyval the key-value pair separator string
*
* @return the string representation for the given map
*/
public static String mapAsString(Map map, String sepItem, String sepKeyval) {
StringBuffer string = new StringBuffer(128);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
string.append(entry.getKey());
string.append(sepKeyval);
string.append(entry.getValue());
if (it.hasNext()) {
string.append(sepItem);
}
}
return string.toString();
}
/**
* Applies white space padding to the left of the given String.<p>
*
* @param input the input to pad left
* @param size the size of the padding
*
* @return the input padded to the left
*/
public static String padLeft(String input, int size) {
return (new PrintfFormat("%" + size + "s")).sprintf(input);
}
/**
* Applies white space padding to the right of the given String.<p>
*
* @param input the input to pad right
* @param size the size of the padding
*
* @return the input padded to the right
*/
public static String padRight(String input, int size) {
return (new PrintfFormat("%-" + size + "s")).sprintf(input);
}
/**
* Splits a String into substrings along the provided char delimiter and returns
* the result as an Array of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the Array of splitted Substrings
*/
public static String[] splitAsArray(String source, char delimiter) {
List result = splitAsList(source, delimiter);
return (String[])result.toArray(new String[result.size()]);
}
/**
* Splits a String into substrings along the provided String delimiter and returns
* the result as an Array of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the Array of splitted Substrings
*/
public static String[] splitAsArray(String source, String delimiter) {
List result = splitAsList(source, delimiter);
return (String[])result.toArray(new String[result.size()]);
}
/**
* Splits a String into substrings along the provided char delimiter and returns
* the result as a List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the List of splitted Substrings
*/
public static List splitAsList(String source, char delimiter) {
return splitAsList(source, delimiter, false);
}
/**
* Splits a String into substrings along the provided char delimiter and returns
* the result as a List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
* @param trim flag to indicate if leading and trailing white spaces should be omitted
*
* @return the List of splitted Substrings
*/
public static List splitAsList(String source, char delimiter, boolean trim) {
List result = new ArrayList();
int i = 0;
int l = source.length();
int n = source.indexOf(delimiter);
while (n != -1) {
// zero - length items are not seen as tokens at start or end
if ((i < n) || ((i > 0) && (i < l))) {
result.add(trim ? source.substring(i, n).trim() : source.substring(i, n));
}
i = n + 1;
n = source.indexOf(delimiter, i);
}
// is there a non - empty String to cut from the tail?
if (n < 0) {
n = source.length();
}
if (i < n) {
result.add(trim ? source.substring(i).trim() : source.substring(i));
}
return result;
}
/**
* Splits a String into substrings along the provided String delimiter and returns
* the result as List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the Array of splitted Substrings
*/
public static List splitAsList(String source, String delimiter) {
return splitAsList(source, delimiter, false);
}
/**
* Splits a String into substrings along the provided String delimiter and returns
* the result as List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
* @param trim flag to indicate if leading and trailing white spaces should be omitted
*
* @return the Array of splitted Substrings
*/
public static List splitAsList(String source, String delimiter, boolean trim) {
int dl = delimiter.length();
if (dl == 1) {
// optimize for short strings
return splitAsList(source, delimiter.charAt(0), trim);
}
List result = new ArrayList();
int i = 0;
int l = source.length();
int n = source.indexOf(delimiter);
while (n != -1) {
// zero - length items are not seen as tokens at start or end: ",," is one empty token but not three
if ((i < n) || ((i > 0) && (i < l))) {
result.add(trim ? source.substring(i, n).trim() : source.substring(i, n));
}
i = n + dl;
n = source.indexOf(delimiter, i);
}
// is there a non - empty String to cut from the tail?
if (n < 0) {
n = source.length();
}
if (i < n) {
result.add(trim ? source.substring(i).trim() : source.substring(i));
}
return result;
}
/**
* Splits a String into substrings along the provided <code>paramDelim</code> delimiter,
* then each substring is treat as a key-value pair delimited by <code>keyValDelim</code>.<p>
*
* @param source the string to split
* @param paramDelim the string to delimit each key-value pair
* @param keyValDelim the string to delimit key and value
*
* @return a map of splitted key-value pairs
*/
public static Map splitAsMap(String source, String paramDelim, String keyValDelim) {
Map params = new HashMap();
Iterator itParams = CmsStringUtil.splitAsList(source, paramDelim, true).iterator();
while (itParams.hasNext()) {
String param = (String)itParams.next();
int pos = param.indexOf(keyValDelim);
String key = param;
String value = "";
if (pos > 0) {
key = param.substring(0, pos);
if (pos + keyValDelim.length() < param.length()) {
value = param.substring(pos + 1);
}
}
params.put(key, value);
}
return params;
}
/**
* Replaces a set of <code>searchString</code> and <code>replaceString</code> pairs,
* given by the <code>substitutions</code> Map parameter.<p>
*
* @param source the string to scan
* @param substitions the map of substitutions
*
* @return the substituted String
*
* @see #substitute(String, String, String)
*/
public static String substitute(String source, Map substitions) {
String result = source;
Iterator it = substitions.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
result = substitute(result, (String)entry.getKey(), entry.getValue().toString());
}
return result;
}
/**
* Substitutes <code>searchString</code> in the given source String with <code>replaceString</code>.<p>
*
* This is a high-performance implementation which should be used as a replacement for
* <code>{@link String#replaceAll(java.lang.String, java.lang.String)}</code> in case no
* regular expression evaluation is required.<p>
*
* @param source the content which is scanned
* @param searchString the String which is searched in content
* @param replaceString the String which replaces <code>searchString</code>
*
* @return the substituted String
*/
public static String substitute(String source, String searchString, String replaceString) {
if (source == null) {
return null;
}
if (isEmpty(searchString)) {
return source;
}
if (replaceString == null) {
replaceString = "";
}
int len = source.length();
int sl = searchString.length();
int rl = replaceString.length();
int length;
if (sl == rl) {
length = len;
} else {
int c = 0;
int s = 0;
int e;
while ((e = source.indexOf(searchString, s)) != -1) {
c++;
s = e + sl;
}
if (c == 0) {
return source;
}
length = len - (c * (sl - rl));
}
int s = 0;
int e = source.indexOf(searchString, s);
if (e == -1) {
return source;
}
StringBuffer sb = new StringBuffer(length);
while (e != -1) {
sb.append(source.substring(s, e));
sb.append(replaceString);
s = e + sl;
e = source.indexOf(searchString, s);
}
e = len;
sb.append(source.substring(s, e));
return sb.toString();
}
/**
* Substitutes the OpenCms context path (e.g. /opencms/opencms/) in a HTML page with a
* special variable so that the content also runs if the context path of the server changes.<p>
*
* @param htmlContent the HTML to replace the context path in
* @param context the context path of the server
*
* @return the HTML with the replaced context path
*/
public static String substituteContextPath(String htmlContent, String context) {
if (m_contextSearch == null) {
m_contextSearch = "([^\\w/])" + context;
m_contextReplace = "$1" + CmsStringUtil.escapePattern(CmsStringUtil.MACRO_OPENCMS_CONTEXT) + "/";
}
return substitutePerl(htmlContent, m_contextSearch, m_contextReplace, "g");
}
/**
* Substitutes searchString in content with replaceItem.<p>
*
* @param content the content which is scanned
* @param searchString the String which is searched in content
* @param replaceItem the new String which replaces searchString
* @param occurences must be a "g" if all occurrences of searchString shall be replaced
*
* @return String the substituted String
*/
public static String substitutePerl(String content, String searchString, String replaceItem, String occurences) {
String translationRule = "s#" + searchString + "#" + replaceItem + "#" + occurences;
Perl5Util perlUtil = new Perl5Util();
try {
return perlUtil.substitute(translationRule, content);
} catch (MalformedPerl5PatternException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_MALFORMED_TRANSLATION_RULE_1, translationRule), e);
}
}
return content;
}
/**
* Returns the java String literal for the given String. <p>
*
* This is the form of the String that had to be written into source code
* using the unicode escape sequence for special characters. <p>
*
* Example: "" would be transformed to "\\u00C4".<p>
*
* @param s a string that may contain non-ascii characters
*
* @return the java unicode escaped string Literal of the given input string
*/
public static String toUnicodeLiteral(String s) {
StringBuffer result = new StringBuffer();
char[] carr = s.toCharArray();
String unicode;
for (int i = 0; i < carr.length; i++) {
result.append("\\u");
// append leading zeros
unicode = Integer.toHexString(carr[i]).toUpperCase();
for (int j = 4 - unicode.length(); j > 0; j--) {
result.append("0");
}
result.append(unicode);
}
return result.toString();
}
/**
* Returns a substring of the source, which is at most length characters long.<p>
*
* This is the same as calling {@link #trimToSize(String, int, String)} with the
* parameters <code>(source, length, " ...")</code>.<p>
*
* @param source the string to trim
* @param length the maximum length of the string to be returned
*
* @return a substring of the source, which is at most length characters long
*/
public static String trimToSize(String source, int length) {
return trimToSize(source, length, length, " ...");
}
/**
* Returns a substring of the source, which is at most length characters long.<p>
*
* If a char is cut, the given <code>suffix</code> is appended to the result.<p>
*
* This is almost the same as calling {@link #trimToSize(String, int, int, String)} with the
* parameters <code>(source, length, length*, suffix)</code>. If <code>length</code>
* if larger then 100, then <code>length* = length / 2</code>,
* otherwise <code>length* = length</code>.<p>
*
* @param source the string to trim
* @param length the maximum length of the string to be returned
* @param suffix the suffix to append in case the String was trimmed
*
* @return a substring of the source, which is at most length characters long
*/
public static String trimToSize(String source, int length, String suffix) {
int area = (length > 100) ? length / 2 : length;
return trimToSize(source, length, area, suffix);
}
/**
* Returns a substring of the source, which is at most length characters long, cut
* in the last <code>area</code> chars in the source at a sentence ending char or whitespace.<p>
*
* If a char is cut, the given <code>suffix</code> is appended to the result.<p>
*
* @param source the string to trim
* @param length the maximum length of the string to be returned
* @param area the area at the end of the string in which to find a sentence ender or whitespace
* @param suffix the suffix to append in case the String was trimmed
*
* @return a substring of the source, which is at most length characters long
*/
public static String trimToSize(String source, int length, int area, String suffix) {
if ((source == null) || (source.length() <= length)) {
// no operation is required
return source;
}
if (CmsStringUtil.isEmpty(suffix)) {
// we need an empty suffix
suffix = "";
}
// must remove the length from the after sequence chars since these are always added in the end
int modLength = length - suffix.length();
if (modLength <= 0) {
// we are to short, return beginning of the suffix
return suffix.substring(0, length);
}
int modArea = area + suffix.length();
if ((modArea > modLength) || (modArea < 0)) {
// area must not be longer then max length
modArea = modLength;
}
// first reduce the String to the maximum allowed length
String findPointSource = source.substring(modLength - modArea, modLength);
String result;
// try to find an "sentence ending" char in the text
int pos = lastIndexOf(findPointSource, SENTENCE_ENDING_CHARS);
if (pos >= 0) {
// found a sentence ender in the lookup area, keep the sentence ender
result = source.substring(0, modLength - modArea + pos + 1) + suffix;
} else {
// no sentence ender was found, try to find a whitespace
pos = lastWhitespaceIn(findPointSource);
if (pos >= 0) {
// found a whitespace, don't keep the whitespace
result = source.substring(0, modLength - modArea + pos) + suffix;
} else {
// not even a whitespace was found, just cut away what's to long
result = source.substring(0, modLength) + suffix;
}
}
return result;
}
/**
* Validates a value against a regular expression.<p>
*
* @param value the value to test
* @param regex the regular expression
* @param allowEmpty if an empty value is allowed
*
* @return <code>true</code> if the value satisfies the validation
*/
public static boolean validateRegex(String value, String regex, boolean allowEmpty) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
return allowEmpty;
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
/**
* Checks if the provided name is a valid resource name, that is contains only
* valid characters.<p>
*
* @param name the resource name to check
* @return true if the resource name is valid, false otherwise
*
* @deprecated use {@link org.opencms.file.CmsResource#checkResourceName(String)} instead
*/
public static boolean validateResourceName(String name) {
if (name == null) {
return false;
}
int l = name.length();
if (l == 0) {
return false;
}
if (name.length() != name.trim().length()) {
// leading or trailing white space are not allowed
return false;
}
for (int i = 0; i < l; i++) {
char ch = name.charAt(i);
switch (ch) {
case '/':
return false;
case '\\':
return false;
case ':':
return false;
case '*':
return false;
case '?':
return false;
case '"':
return false;
case '>':
return false;
case '<':
return false;
case '|':
return false;
default:
// ISO control chars are not allowed
if (Character.isISOControl(ch)) {
return false;
}
// chars not defined in unicode are not allowed
if (!Character.isDefined(ch)) {
return false;
}
}
}
return true;
}
} | src/org/opencms/util/CmsStringUtil.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsStringUtil.java,v $
* Date : $Date: 2007/08/30 12:05:47 $
* Version: $Revision: 1.46 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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 org.opencms.util;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.I_CmsMessageBundle;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import java.awt.Color;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.oro.text.perl.MalformedPerl5PatternException;
import org.apache.oro.text.perl.Perl5Util;
/**
* Provides String utility functions.<p>
*
* @author Andreas Zahner
* @author Alexander Kandzior
* @author Thomas Weckert
*
* @version $Revision: 1.46 $
*
* @since 6.0.0
*/
public final class CmsStringUtil {
/** Regular expression that matches the HTML body end tag. */
public static final String BODY_END_REGEX = "<\\s*/\\s*body[^>]*>";
/** Regular expression that matches the HTML body start tag. */
public static final String BODY_START_REGEX = "<\\s*body[^>]*>";
/** Constant for <code>"false"</code>. */
public static final String FALSE = Boolean.toString(false);
/** a convienient shorthand to the line separator constant. */
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
/** Context macro. */
public static final String MACRO_OPENCMS_CONTEXT = "${OpenCmsContext}";
/** Contains all chars that end a sentence in the {@link #trimToSize(String, int, int, String)} method. */
public static final char[] SENTENCE_ENDING_CHARS = {'.', '!', '?'};
/** a convienient shorthand for tabulations. */
public static final String TABULATOR = " ";
/** Constant for <code>"true"</code>. */
public static final String TRUE = Boolean.toString(true);
/** Regex pattern that matches an end body tag. */
private static final Pattern BODY_END_PATTERN = Pattern.compile(BODY_END_REGEX, Pattern.CASE_INSENSITIVE);
/** Regex pattern that matches a start body tag. */
private static final Pattern BODY_START_PATTERN = Pattern.compile(BODY_START_REGEX, Pattern.CASE_INSENSITIVE);
/** Day constant. */
private static final long DAYS = 1000 * 60 * 60 * 24;
/** Hour constant. */
private static final long HOURS = 1000 * 60 * 60;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsStringUtil.class);
/** OpenCms context replace String, static for performance reasons. */
private static String m_contextReplace;
/** OpenCms context search String, static for performance reasons. */
private static String m_contextSearch;
/** Minute constant. */
private static final long MINUTES = 1000 * 60;
/** Second constant. */
private static final long SECONDS = 1000;
/** Regex that matches an encoding String in an xml head. */
private static final Pattern XML_ENCODING_REGEX = Pattern.compile(
"encoding\\s*=\\s*[\"'].+[\"']",
Pattern.CASE_INSENSITIVE);
/** Regex that matches an xml head. */
private static final Pattern XML_HEAD_REGEX = Pattern.compile("<\\s*\\?.*\\?\\s*>", Pattern.CASE_INSENSITIVE);
/**
* Default constructor (empty), private because this class has only
* static methods.<p>
*/
private CmsStringUtil() {
// empty
}
/**
* Changes the filename suffix.
*
* @param filename the filename to be changed
* @param suffix the new suffix of the file
* @return the filename with the replaced suffix
*/
public static String changeFileNameSuffixTo(String filename, String suffix) {
int dotPos = filename.lastIndexOf('.');
if (dotPos != -1) {
return filename.substring(0, dotPos + 1) + suffix;
} else {
// the string has no suffix
return filename;
}
}
/**
* Checks if a given name is composed only of the characters <code>a...z,A...Z,0...9</code>
* and the provided <code>contraints</code>.<p>
*
* If the check fails, an Exception is generated. The provided bundle and key is
* used to generate the Exception. 4 parameters are passed to the Exception:<ol>
* <li>The <code>name</code>
* <li>The first illegal character found
* <li>The position where the illegal character was found
* <li>The <code>contraints</code></ol>
*
* @param name the name to check
* @param contraints the additional character contraints
* @param key the key to use for generating the Exception (if required)
* @param bundle the bundle to use for generating the Exception (if required)
*
* @throws CmsIllegalArgumentException if the check fails (generated from the given key and bundle)
*/
public static void checkName(String name, String contraints, String key, I_CmsMessageBundle bundle)
throws CmsIllegalArgumentException {
int l = name.length();
for (int i = 0; i < l; i++) {
char c = name.charAt(i);
if (((c < 'a') || (c > 'z'))
&& ((c < '0') || (c > '9'))
&& ((c < 'A') || (c > 'Z'))
&& (contraints.indexOf(c) < 0)) {
throw new CmsIllegalArgumentException(bundle.container(key, new Object[] {
name,
new Character(c),
new Integer(i),
contraints}));
}
}
}
/**
* Returns a string representation for the given collection using the given separator.<p>
*
* @param collection the collection to print
* @param separator the item separator
*
* @return the string representation for the given collection
*/
public static String collectionAsString(Collection collection, String separator) {
StringBuffer string = new StringBuffer(128);
Iterator it = collection.iterator();
while (it.hasNext()) {
string.append(it.next());
if (it.hasNext()) {
string.append(separator);
}
}
return string.toString();
}
/**
* Replaces occurences of special control characters in the given input with
* a HTML representation.<p>
*
* This method currrently replaces line breaks to <code><br/></code> and special HTML chars
* like <code>< > & "</code> with their HTML entity representation.<p>
*
* @param source the String to escape
* @return the escaped String
*/
public static String escapeHtml(String source) {
if (source == null) {
return null;
}
source = CmsEncoder.escapeXml(source);
source = CmsStringUtil.substitute(source, "\r", "");
source = CmsStringUtil.substitute(source, "\n", "<br/>\n");
return source;
}
/**
* Escapes a String so it may be used in JavaScript String definitions.<p>
*
* This method replaces line breaks, quotationmarks and \ characters.<p>
*
* @param source the String to escape
* @return the escaped String
*/
public static String escapeJavaScript(String source) {
source = CmsStringUtil.substitute(source, "\\", "\\\\");
source = CmsStringUtil.substitute(source, "\"", "\\\"");
source = CmsStringUtil.substitute(source, "\'", "\\\'");
source = CmsStringUtil.substitute(source, "\r\n", "\\n");
source = CmsStringUtil.substitute(source, "\n", "\\n");
return source;
}
/**
* Escapes a String so it may be used as a Perl5 regular expression.<p>
*
* This method replaces the following characters in a String:<br>
* <code>{}[]()\$^.*+/</code>
*
*
* @param source the string to escape
* @return the escaped string
*/
public static String escapePattern(String source) {
if (source == null) {
return null;
}
StringBuffer result = new StringBuffer(source.length() * 2);
for (int i = 0; i < source.length(); ++i) {
char ch = source.charAt(i);
switch (ch) {
case '\\':
result.append("\\\\");
break;
case '/':
result.append("\\/");
break;
case '$':
result.append("\\$");
break;
case '^':
result.append("\\^");
break;
case '.':
result.append("\\.");
break;
case '*':
result.append("\\*");
break;
case '+':
result.append("\\+");
break;
case '|':
result.append("\\|");
break;
case '?':
result.append("\\?");
break;
case '{':
result.append("\\{");
break;
case '}':
result.append("\\}");
break;
case '[':
result.append("\\[");
break;
case ']':
result.append("\\]");
break;
case '(':
result.append("\\(");
break;
case ')':
result.append("\\)");
break;
default:
result.append(ch);
}
}
return new String(result);
}
/**
* This method takes a part of a html tag definition, an attribute to extend within the
* given text and a default value for this attribute; and returns a <code>{@link Map}</code>
* with 2 values: a <code>{@link String}</code> with key <code>"text"</code> with the new text
* without the given attribute, and another <code>{@link String}</code> with key <code>"value"</code>
* with the new extended value for the given attribute, this value is sourrounded by the same type of
* quotation marks as in the given text.<p>
*
* @param text the text to search in
* @param attribute the attribute to remove and extend from the text
* @param defValue a default value for the attribute, should not have any quotation mark
*
* @return a map with the new text and the new value for the given attribute
*/
public static Map extendAttribute(String text, String attribute, String defValue) {
Map retValue = new HashMap();
retValue.put("text", text);
retValue.put("value", "'" + defValue + "'");
if ((text != null) && (text.toLowerCase().indexOf(attribute.toLowerCase()) >= 0)) {
// this doesnot work for things like "att=method()" without quotations.
String quotation = "\'";
int pos1 = text.toLowerCase().indexOf(attribute.toLowerCase());
// looking for the opening quotation mark
int pos2 = text.indexOf(quotation, pos1);
int test = text.indexOf("\"", pos1);
if ((test > -1) && ((pos2 == -1) || (test < pos2))) {
quotation = "\"";
pos2 = test;
}
// assuming there is a closing quotation mark
int pos3 = text.indexOf(quotation, pos2 + 1);
// building the new attribute value
String newValue = quotation + defValue + text.substring(pos2 + 1, pos3 + 1);
// removing the onload statement from the parameters
String newText = text.substring(0, pos1);
if (pos3 < text.length()) {
newText += text.substring(pos3 + 1);
}
retValue.put("text", newText);
retValue.put("value", newValue);
}
return retValue;
}
/**
* Extracts the content of a <body> tag in a HTML page.<p>
*
* This method should be pretty robust and work even if the input HTML does not contains
* a valid body tag.<p>
*
* @param content the content to extract the body from
* @return the extracted body tag content
*/
public static String extractHtmlBody(String content) {
Matcher startMatcher = BODY_START_PATTERN.matcher(content);
Matcher endMatcher = BODY_END_PATTERN.matcher(content);
int start = 0;
int end = content.length();
if (startMatcher.find()) {
start = startMatcher.end();
}
if (endMatcher.find(start)) {
end = endMatcher.start();
}
return content.substring(start, end);
}
/**
* Extracts the xml encoding setting from an xml file that is contained in a String by parsing
* the xml head.<p>
*
* This is useful if you have a byte array that contains a xml String,
* but you do not know the xml encoding setting. Since the encoding setting
* in the xml head is usually encoded with standard US-ASCII, you usually
* just create a String of the byte array without encoding setting,
* and use this method to find the 'true' encoding. Then create a String
* of the byte array again, this time using the found encoding.<p>
*
* This method will return <code>null</code> in case no xml head
* or encoding information is contained in the input.<p>
*
* @param content the xml content to extract the encoding from
* @return the extracted encoding, or null if no xml encoding setting was found in the input
*/
public static String extractXmlEncoding(String content) {
String result = null;
Matcher xmlHeadMatcher = XML_HEAD_REGEX.matcher(content);
if (xmlHeadMatcher.find()) {
String xmlHead = xmlHeadMatcher.group();
Matcher encodingMatcher = XML_ENCODING_REGEX.matcher(xmlHead);
if (encodingMatcher.find()) {
String encoding = encodingMatcher.group();
int pos1 = encoding.indexOf('=') + 2;
String charset = encoding.substring(pos1, encoding.length() - 1);
if (Charset.isSupported(charset)) {
result = charset;
}
}
}
return result;
}
/**
* Formats a resource name that it is displayed with the maximum length and path information is adjusted.<p>
* In order to reduce the length of the displayed names, single folder names are removed/replaced with ... successively,
* starting with the second! folder. The first folder is removed as last.
*
* Example: formatResourceName("/myfolder/subfolder/index.html", 21) returns <code>/myfolder/.../index.html</code>.<p>
*
* @param name the resource name to format
* @param maxLength the maximum length of the resource name (without leading <code>/...</code>)
* @return the formatted resource name
*/
public static String formatResourceName(String name, int maxLength) {
if (name == null) {
return null;
}
if (name.length() <= maxLength) {
return name;
}
int total = name.length();
String[] names = CmsStringUtil.splitAsArray(name, "/");
if (name.endsWith("/")) {
names[names.length - 1] = names[names.length - 1] + "/";
}
for (int i = 1; (total > maxLength) && (i < names.length - 1); i++) {
if (i > 1) {
names[i - 1] = "";
}
names[i] = "...";
total = 0;
for (int j = 0; j < names.length; j++) {
int l = names[j].length();
total += l + ((l > 0) ? 1 : 0);
}
}
if (total > maxLength) {
names[0] = (names.length > 2) ? "" : (names.length > 1) ? "..." : names[0];
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < names.length; i++) {
if (names[i].length() > 0) {
result.append("/");
result.append(names[i]);
}
}
return result.toString();
}
/**
* Formats a runtime in the format hh:mm:ss, to be used e.g. in reports.<p>
*
* If the runtime is greater then 24 hours, the format dd:hh:mm:ss is used.<p>
*
* @param runtime the time to format
* @return the formatted runtime
*/
public static String formatRuntime(long runtime) {
long seconds = (runtime / SECONDS) % 60;
long minutes = (runtime / MINUTES) % 60;
long hours = (runtime / HOURS) % 24;
long days = runtime / DAYS;
StringBuffer strBuf = new StringBuffer();
if (days > 0) {
if (days < 10) {
strBuf.append('0');
}
strBuf.append(days);
strBuf.append(':');
}
if (hours < 10) {
strBuf.append('0');
}
strBuf.append(hours);
strBuf.append(':');
if (minutes < 10) {
strBuf.append('0');
}
strBuf.append(minutes);
strBuf.append(':');
if (seconds < 10) {
strBuf.append('0');
}
strBuf.append(seconds);
return strBuf.toString();
}
/**
* Returns the color value (<code>{@link Color}</code>) for the given String value.<p>
*
* All parse errors are caught and the given default value is returned in this case.<p>
*
* @param value the value to parse as color
* @param defaultValue the default value in case of parsing errors
* @param key a key to be included in the debug output in case of parse errors
*
* @return the int value for the given parameter value String
*/
public static Color getColorValue(String value, Color defaultValue, String key) {
Color result;
try {
char pre = value.charAt(0);
if (pre != '#') {
value = "#" + value;
}
result = Color.decode(value);
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_UNABLE_TO_PARSE_COLOR_2, value, key));
}
result = defaultValue;
}
return result;
}
/**
* Returns the Integer (int) value for the given String value.<p>
*
* All parse errors are caught and the given default value is returned in this case.<p>
*
* @param value the value to parse as int
* @param defaultValue the default value in case of parsing errors
* @param key a key to be included in the debug output in case of parse errors
*
* @return the int value for the given parameter value String
*/
public static int getIntValue(String value, int defaultValue, String key) {
int result;
try {
result = Integer.valueOf(value).intValue();
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_UNABLE_TO_PARSE_INT_2, value, key));
}
result = defaultValue;
}
return result;
}
/**
* Returns <code>true</code> if the provided String is either <code>null</code>
* or the empty String <code>""</code>.<p>
*
* @param value the value to check
* @return true, if the provided value is null or the empty String, false otherwise
*/
public static boolean isEmpty(String value) {
return (value == null) || (value.length() == 0);
}
/**
* Returns <code>true</code> if the provided String is either <code>null</code>
* or contains only white spaces.<p>
*
* @param value the value to check
* @return true, if the provided value is null or contains only white spaces, false otherwise
*/
public static boolean isEmptyOrWhitespaceOnly(String value) {
return isEmpty(value) || (value.trim().length() == 0);
}
/**
* Returns <code>true</code> if the provided Objects are either both <code>null</code>
* or equal according to {@link Object#equals(Object)}.<p>
*
* @param value1 the first object to compare
* @param value2 the second object to compare
*
* @return <code>true</code> if the provided Objects are either both <code>null</code>
* or equal according to {@link Object#equals(Object)}
*/
public static boolean isEqual(Object value1, Object value2) {
if (value1 == null) {
return (value2 == null);
}
return value1.equals(value2);
}
/**
* Returns <code>true</code> if the provided String is neither <code>null</code>
* nor the empty String <code>""</code>.<p>
*
* @param value the value to check
* @return true, if the provided value is not null and not the empty String, false otherwise
*/
public static boolean isNotEmpty(String value) {
return (value != null) && (value.length() != 0);
}
/**
* Returns <code>true</code> if the provided String is neither <code>null</code>
* nor contains only white spaces.<p>
*
* @param value the value to check
* @return true, if the provided value is null or contains only white spaces, false otherwise
*/
public static boolean isNotEmptyOrWhitespaceOnly(String value) {
return (value != null) && (value.trim().length() > 0);
}
/**
* Checks if the given class name is a valid Java class name.<p>
*
* @param className the name to check
* @return true if the given class name is a valid Java class name
*/
public static boolean isValidJavaClassName(String className) {
if (CmsStringUtil.isEmpty(className)) {
return false;
}
int length = className.length();
boolean nodot = true;
for (int i = 0; i < length; i++) {
char ch = className.charAt(i);
if (nodot) {
if (ch == '.') {
return false;
} else if (Character.isJavaIdentifierStart(ch)) {
nodot = false;
} else {
return false;
}
} else {
if (ch == '.') {
nodot = true;
} else if (Character.isJavaIdentifierPart(ch)) {
nodot = false;
} else {
return false;
}
}
}
return true;
}
/**
* Returns the last index of any of the given chars in the given source.<p>
*
* If no char is found, -1 is returned.<p>
*
* @param source the source to check
* @param chars the chars to find
*
* @return the last index of any of the given chars in the given source, or -1
*/
public static int lastIndexOf(String source, char[] chars) {
// now try to find an "sentence ending" char in the text in the "findPointArea"
int result = -1;
for (int i = 0; i < chars.length; i++) {
int pos = source.lastIndexOf(chars[i]);
if (pos > result) {
// found new last char
result = pos;
}
}
return result;
}
/**
* Returns the last index a whitespace char the given source.<p>
*
* If no whitespace char is found, -1 is returned.<p>
*
* @param source the source to check
*
* @return the last index a whitespace char the given source, or -1
*/
public static int lastWhitespaceIn(String source) {
if (CmsStringUtil.isEmpty(source)) {
return -1;
}
int pos = -1;
for (int i = source.length() - 1; i >= 0; i--) {
if (Character.isWhitespace(source.charAt(i))) {
pos = i;
break;
}
}
return pos;
}
/**
* Returns a string representation for the given map using the given separators.<p>
*
* @param map the map to write
* @param sepItem the item separator string
* @param sepKeyval the key-value pair separator string
*
* @return the string representation for the given map
*/
public static String mapAsString(Map map, String sepItem, String sepKeyval) {
StringBuffer string = new StringBuffer(128);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
string.append(entry.getKey());
string.append(sepKeyval);
string.append(entry.getValue());
if (it.hasNext()) {
string.append(sepItem);
}
}
return string.toString();
}
/**
* Applies white space padding to the left of the given String.<p>
*
* @param input the input to pad left
* @param size the size of the padding
*
* @return the input padded to the left
*/
public static String padLeft(String input, int size) {
return (new PrintfFormat("%" + size + "s")).sprintf(input);
}
/**
* Applies white space padding to the right of the given String.<p>
*
* @param input the input to pad right
* @param size the size of the padding
*
* @return the input padded to the right
*/
public static String padRight(String input, int size) {
return (new PrintfFormat("%-" + size + "s")).sprintf(input);
}
/**
* Splits a String into substrings along the provided char delimiter and returns
* the result as an Array of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the Array of splitted Substrings
*/
public static String[] splitAsArray(String source, char delimiter) {
List result = splitAsList(source, delimiter);
return (String[])result.toArray(new String[result.size()]);
}
/**
* Splits a String into substrings along the provided String delimiter and returns
* the result as an Array of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the Array of splitted Substrings
*/
public static String[] splitAsArray(String source, String delimiter) {
List result = splitAsList(source, delimiter);
return (String[])result.toArray(new String[result.size()]);
}
/**
* Splits a String into substrings along the provided char delimiter and returns
* the result as a List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the List of splitted Substrings
*/
public static List splitAsList(String source, char delimiter) {
return splitAsList(source, delimiter, false);
}
/**
* Splits a String into substrings along the provided char delimiter and returns
* the result as a List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
* @param trim flag to indicate if leading and trailing whitespaces should be omitted
*
* @return the List of splitted Substrings
*/
public static List splitAsList(String source, char delimiter, boolean trim) {
List result = new ArrayList();
int i = 0;
int l = source.length();
int n = source.indexOf(delimiter);
while (n != -1) {
// zero - length items are not seen as tokens at start or end
if ((i < n) || ((i > 0) && (i < l))) {
result.add(trim ? source.substring(i, n).trim() : source.substring(i, n));
}
i = n + 1;
n = source.indexOf(delimiter, i);
}
// is there a non - empty String to cut from the tail?
if (n < 0) {
n = source.length();
}
if (i < n) {
result.add(trim ? source.substring(i).trim() : source.substring(i));
}
return result;
}
/**
* Splits a String into substrings along the provided String delimiter and returns
* the result as List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
*
* @return the Array of splitted Substrings
*/
public static List splitAsList(String source, String delimiter) {
return splitAsList(source, delimiter, false);
}
/**
* Splits a String into substrings along the provided String delimiter and returns
* the result as List of Substrings.<p>
*
* @param source the String to split
* @param delimiter the delimiter to split at
* @param trim flag to indicate if leading and trailing whitespaces should be omitted
*
* @return the Array of splitted Substrings
*/
public static List splitAsList(String source, String delimiter, boolean trim) {
int dl = delimiter.length();
if (dl == 1) {
// optimize for short strings
return splitAsList(source, delimiter.charAt(0), trim);
}
List result = new ArrayList();
int i = 0;
int l = source.length();
int n = source.indexOf(delimiter);
while (n != -1) {
// zero - length items are not seen as tokens at start or end: ",," is one empty token but not three
if ((i < n) || ((i > 0) && (i < l))) {
result.add(trim ? source.substring(i, n).trim() : source.substring(i, n));
}
i = n + dl;
n = source.indexOf(delimiter, i);
}
// is there a non - empty String to cut from the tail?
if (n < 0) {
n = source.length();
}
if (i < n) {
result.add(trim ? source.substring(i).trim() : source.substring(i));
}
return result;
}
/**
* Splits a String into substrings along the provided <code>paramDelim</code> delimiter,
* then each substring is treat as a key-value pair delimited by <code>keyValDelim</code>.
*
* @param source the string to split
* @param paramDelim the string to delimit each key-value pair
* @param keyValDelim the string to delimit key and value
*
* @return a map of splitted key-value pairs
*/
public static Map splitAsMap(String source, String paramDelim, String keyValDelim) {
Map params = new HashMap();
Iterator itParams = CmsStringUtil.splitAsList(source, paramDelim, true).iterator();
while (itParams.hasNext()) {
String param = (String)itParams.next();
int pos = param.indexOf(keyValDelim);
String key = param;
String value = "";
if (pos > 0) {
key = param.substring(0, pos);
if (pos + keyValDelim.length() < param.length()) {
value = param.substring(pos + 1);
}
}
params.put(key, value);
}
return params;
}
/**
* Replaces a set of <code>searchString</code> and <code>replaceString</code> pairs,
* given by the <code>substitutions</code> Map parameter.<p>
*
* @param source the constent which is scanned
* @param substitions the map of substitutions
*
* @return the substituted String
*
* @see #substitute(String, String, String)
*/
public static String substitute(String source, Map substitions) {
String result = source;
Iterator it = substitions.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
result = substitute(result, (String)entry.getKey(), entry.getValue().toString());
}
return result;
}
/**
* Substitutes <code>searchString</code> in the given source String with <code>replaceString</code>.<p>
*
* This is a high-performance implementation which should be used as a replacement for
* <code>{@link String#replaceAll(java.lang.String, java.lang.String)}</code> in case no
* regular expression evaluation is required.<p>
*
* @param source the content which is scanned
* @param searchString the String which is searched in content
* @param replaceString the String which replaces <code>searchString</code>
*
* @return the substituted String
*/
public static String substitute(String source, String searchString, String replaceString) {
if (source == null) {
return null;
}
if (isEmpty(searchString)) {
return source;
}
if (replaceString == null) {
replaceString = "";
}
int len = source.length();
int sl = searchString.length();
int rl = replaceString.length();
int length;
if (sl == rl) {
length = len;
} else {
int c = 0;
int s = 0;
int e;
while ((e = source.indexOf(searchString, s)) != -1) {
c++;
s = e + sl;
}
if (c == 0) {
return source;
}
length = len - (c * (sl - rl));
}
int s = 0;
int e = source.indexOf(searchString, s);
if (e == -1) {
return source;
}
StringBuffer sb = new StringBuffer(length);
while (e != -1) {
sb.append(source.substring(s, e));
sb.append(replaceString);
s = e + sl;
e = source.indexOf(searchString, s);
}
e = len;
sb.append(source.substring(s, e));
return sb.toString();
}
/**
* Substitutes the OpenCms context path (e.g. /opencms/opencms/) in a HTML page with a
* special variable so that the content also runs if the context path of the server changes.<p>
*
* @param htmlContent the HTML to replace the context path in
* @param context the context path of the server
* @return the HTML with the replaced context path
*/
public static String substituteContextPath(String htmlContent, String context) {
if (m_contextSearch == null) {
m_contextSearch = "([^\\w/])" + context;
m_contextReplace = "$1" + CmsStringUtil.escapePattern(CmsStringUtil.MACRO_OPENCMS_CONTEXT) + "/";
}
return substitutePerl(htmlContent, m_contextSearch, m_contextReplace, "g");
}
/**
* Substitutes searchString in content with replaceItem.<p>
*
* @param content the content which is scanned
* @param searchString the String which is searched in content
* @param replaceItem the new String which replaces searchString
* @param occurences must be a "g" if all occurences of searchString shall be replaced
* @return String the substituted String
*/
public static String substitutePerl(String content, String searchString, String replaceItem, String occurences) {
String translationRule = "s#" + searchString + "#" + replaceItem + "#" + occurences;
Perl5Util perlUtil = new Perl5Util();
try {
return perlUtil.substitute(translationRule, content);
} catch (MalformedPerl5PatternException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_MALFORMED_TRANSLATION_RULE_1, translationRule), e);
}
}
return content;
}
/**
* Returns the java String literal for the given String. <p>
*
* This is the form of the String that had to be written into sourcecode
* using the unicode escape sequence for special characters. <p>
*
* Example: "" would be transformed to "\\u00C4".<p>
*
* @param s a string that may contain non-ascii characters
*
* @return the java unicode escaped string Literal of the given input string
*/
public static String toUnicodeLiteral(String s) {
StringBuffer result = new StringBuffer();
char[] carr = s.toCharArray();
String unicode;
for (int i = 0; i < carr.length; i++) {
result.append("\\u");
// append leading zeros
unicode = Integer.toHexString(carr[i]).toUpperCase();
for (int j = 4 - unicode.length(); j > 0; j--) {
result.append("0");
}
result.append(unicode);
}
return result.toString();
}
/**
* Returns a substring of the source, which is at most length characters long.<p>
*
* This is the same as calling {@link #trimToSize(String, int, String)} with the
* parameters <code>(source, length, " ...")</code>.<p>
*
* @param source the string to trim
* @param length the maximum length of the string to be returned
*
* @return a substring of the source, which is at most length characters long
*/
public static String trimToSize(String source, int length) {
return trimToSize(source, length, length, " ...");
}
/**
* Returns a substring of the source, which is at most length characters long.<p>
*
* If a char is cut, the given <code>suffix</code> is appended to the result.<p>
*
* This is almost the same as calling {@link #trimToSize(String, int, int, String)} with the
* parameters <code>(source, length, length*, suffix)</code>. If <code>length</code>
* if larger then 100, then <code>length* = length / 2</code>,
* otherwise <code>length* = length</code>.<p>
*
* @param source the string to trim
* @param length the maximum length of the string to be returned
* @param suffix the suffix to append in case the String was trimmed
*
* @return a substring of the source, which is at most length characters long
*/
public static String trimToSize(String source, int length, String suffix) {
int area = (length > 100) ? length / 2 : length;
return trimToSize(source, length, area, suffix);
}
/**
* Returns a substring of the source, which is at most length characters long, cut
* in the last <code>area</code> chars in the source at a sentence ending char or whitespace.<p>
*
* If a char is cut, the given <code>suffix</code> is appended to the result.<p>
*
* @param source the string to trim
* @param length the maximum length of the string to be returned
* @param area the area at the end of the string in which to find a sentence ender or whitespace
* @param suffix the suffix to append in case the String was trimmed
*
* @return a substring of the source, which is at most length characters long
*/
public static String trimToSize(String source, int length, int area, String suffix) {
if ((source == null) || (source.length() <= length)) {
// no operation is required
return source;
}
if (CmsStringUtil.isEmpty(suffix)) {
// we need an empty suffix
suffix = "";
}
// must remove the length from the after sequence chars since these are always added in the end
int modLength = length - suffix.length();
if (modLength <= 0) {
// we are to short, return beginning of the suffix
return suffix.substring(0, length);
}
int modArea = area + suffix.length();
if ((modArea > modLength) || (modArea < 0)) {
// area must not be longer then max length
modArea = modLength;
}
// first reduce the String to the maximum allowed length
String findPointSource = source.substring(modLength - modArea, modLength);
String result;
// try to find an "sentence ending" char in the text
int pos = lastIndexOf(findPointSource, SENTENCE_ENDING_CHARS);
if (pos >= 0) {
// found a sentence ender in the lookup area, keep the sentence ender
result = source.substring(0, modLength - modArea + pos + 1) + suffix;
} else {
// no sentence ender was found, try to find a whitespace
pos = lastWhitespaceIn(findPointSource);
if (pos >= 0) {
// found a whitespace, don't keep the whitespace
result = source.substring(0, modLength - modArea + pos) + suffix;
} else {
// not even a whitespace was found, just cut away what's to long
result = source.substring(0, modLength) + suffix;
}
}
return result;
}
/**
* Validates a value against a regular expression.<p>
*
* @param value the value to test
* @param regex the regular expression
* @param allowEmpty if an empty value is allowed
*
* @return <code>true</code> if the value satisfies the validation
*/
public static boolean validateRegex(String value, String regex, boolean allowEmpty) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
return allowEmpty;
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
/**
* Checks if the provided name is a valid resource name, that is contains only
* valid characters.<p>
*
* @param name the resource name to check
* @return true if the resource name is vaild, false otherwise
*
* @deprecated use {@link org.opencms.file.CmsResource#checkResourceName(String)} instead
*/
public static boolean validateResourceName(String name) {
if (name == null) {
return false;
}
int l = name.length();
if (l == 0) {
return false;
}
if (name.length() != name.trim().length()) {
// leading or trainling white space are not allowed
return false;
}
for (int i = 0; i < l; i++) {
char ch = name.charAt(i);
switch (ch) {
case '/':
return false;
case '\\':
return false;
case ':':
return false;
case '*':
return false;
case '?':
return false;
case '"':
return false;
case '>':
return false;
case '<':
return false;
case '|':
return false;
default:
// ISO control chars are not allowed
if (Character.isISOControl(ch)) {
return false;
}
// chars not defined in unicode are not allowed
if (!Character.isDefined(ch)) {
return false;
}
}
}
return true;
}
} | corrected typos and formatting
| src/org/opencms/util/CmsStringUtil.java | corrected typos and formatting | <ide><path>rc/org/opencms/util/CmsStringUtil.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/util/CmsStringUtil.java,v $
<del> * Date : $Date: 2007/08/30 12:05:47 $
<del> * Version: $Revision: 1.46 $
<add> * Date : $Date: 2007/09/24 13:59:06 $
<add> * Version: $Revision: 1.47 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Management System
<ide> * @author Alexander Kandzior
<ide> * @author Thomas Weckert
<ide> *
<del> * @version $Revision: 1.46 $
<add> * @version $Revision: 1.47 $
<ide> *
<ide> * @since 6.0.0
<ide> */
<ide> /** Constant for <code>"false"</code>. */
<ide> public static final String FALSE = Boolean.toString(false);
<ide>
<del> /** a convienient shorthand to the line separator constant. */
<add> /** a convenient shorthand to the line separator constant. */
<ide> public static final String LINE_SEPARATOR = System.getProperty("line.separator");
<ide>
<ide> /** Context macro. */
<ide> /** Contains all chars that end a sentence in the {@link #trimToSize(String, int, int, String)} method. */
<ide> public static final char[] SENTENCE_ENDING_CHARS = {'.', '!', '?'};
<ide>
<del> /** a convienient shorthand for tabulations. */
<add> /** a convenient shorthand for tabulations. */
<ide> public static final String TABULATOR = " ";
<ide>
<ide> /** Constant for <code>"true"</code>. */
<ide> *
<ide> * @param filename the filename to be changed
<ide> * @param suffix the new suffix of the file
<add> *
<ide> * @return the filename with the replaced suffix
<ide> */
<ide> public static String changeFileNameSuffixTo(String filename, String suffix) {
<ide>
<ide> /**
<ide> * Checks if a given name is composed only of the characters <code>a...z,A...Z,0...9</code>
<del> * and the provided <code>contraints</code>.<p>
<add> * and the provided <code>constraints</code>.<p>
<ide> *
<ide> * If the check fails, an Exception is generated. The provided bundle and key is
<ide> * used to generate the Exception. 4 parameters are passed to the Exception:<ol>
<ide> * <li>The <code>name</code>
<ide> * <li>The first illegal character found
<ide> * <li>The position where the illegal character was found
<del> * <li>The <code>contraints</code></ol>
<add> * <li>The <code>constraints</code></ol>
<ide> *
<ide> * @param name the name to check
<del> * @param contraints the additional character contraints
<add> * @param contraints the additional character constraints
<ide> * @param key the key to use for generating the Exception (if required)
<ide> * @param bundle the bundle to use for generating the Exception (if required)
<ide> *
<ide> }
<ide>
<ide> /**
<del> * Replaces occurences of special control characters in the given input with
<add> * Replaces occurrences of special control characters in the given input with
<ide> * a HTML representation.<p>
<ide> *
<del> * This method currrently replaces line breaks to <code><br/></code> and special HTML chars
<add> * This method currently replaces line breaks to <code><br/></code> and special HTML chars
<ide> * like <code>< > & "</code> with their HTML entity representation.<p>
<ide> *
<ide> * @param source the String to escape
<add> *
<ide> * @return the escaped String
<ide> */
<ide> public static String escapeHtml(String source) {
<ide> /**
<ide> * Escapes a String so it may be used in JavaScript String definitions.<p>
<ide> *
<del> * This method replaces line breaks, quotationmarks and \ characters.<p>
<add> * This method replaces line breaks, quotation marks and \ characters.<p>
<ide> *
<ide> * @param source the String to escape
<add> *
<ide> * @return the escaped String
<ide> */
<ide> public static String escapeJavaScript(String source) {
<ide> * Escapes a String so it may be used as a Perl5 regular expression.<p>
<ide> *
<ide> * This method replaces the following characters in a String:<br>
<del> * <code>{}[]()\$^.*+/</code>
<del> *
<add> * <code>{}[]()\$^.*+/</code><p>
<ide> *
<ide> * @param source the string to escape
<add> *
<ide> * @return the escaped string
<ide> */
<ide> public static String escapePattern(String source) {
<ide> * given text and a default value for this attribute; and returns a <code>{@link Map}</code>
<ide> * with 2 values: a <code>{@link String}</code> with key <code>"text"</code> with the new text
<ide> * without the given attribute, and another <code>{@link String}</code> with key <code>"value"</code>
<del> * with the new extended value for the given attribute, this value is sourrounded by the same type of
<add> * with the new extended value for the given attribute, this value is surrounded by the same type of
<ide> * quotation marks as in the given text.<p>
<ide> *
<ide> * @param text the text to search in
<ide> retValue.put("text", text);
<ide> retValue.put("value", "'" + defValue + "'");
<ide> if ((text != null) && (text.toLowerCase().indexOf(attribute.toLowerCase()) >= 0)) {
<del> // this doesnot work for things like "att=method()" without quotations.
<add> // this does not work for things like "att=method()" without quotations.
<ide> String quotation = "\'";
<ide> int pos1 = text.toLowerCase().indexOf(attribute.toLowerCase());
<ide> // looking for the opening quotation mark
<ide> }
<ide>
<ide> /**
<del> * Extracts the content of a <body> tag in a HTML page.<p>
<add> * Extracts the content of a <code><body></code> tag in a HTML page.<p>
<ide> *
<ide> * This method should be pretty robust and work even if the input HTML does not contains
<ide> * a valid body tag.<p>
<ide> *
<ide> * @param content the content to extract the body from
<add> *
<ide> * @return the extracted body tag content
<ide> */
<ide> public static String extractHtmlBody(String content) {
<ide> * or encoding information is contained in the input.<p>
<ide> *
<ide> * @param content the xml content to extract the encoding from
<add> *
<ide> * @return the extracted encoding, or null if no xml encoding setting was found in the input
<ide> */
<ide> public static String extractXmlEncoding(String content) {
<ide> /**
<ide> * Formats a resource name that it is displayed with the maximum length and path information is adjusted.<p>
<ide> * In order to reduce the length of the displayed names, single folder names are removed/replaced with ... successively,
<del> * starting with the second! folder. The first folder is removed as last.
<add> * starting with the second! folder. The first folder is removed as last.<p>
<ide> *
<ide> * Example: formatResourceName("/myfolder/subfolder/index.html", 21) returns <code>/myfolder/.../index.html</code>.<p>
<ide> *
<ide> * @param name the resource name to format
<ide> * @param maxLength the maximum length of the resource name (without leading <code>/...</code>)
<add> *
<ide> * @return the formatted resource name
<ide> */
<ide> public static String formatResourceName(String name, int maxLength) {
<ide> * If the runtime is greater then 24 hours, the format dd:hh:mm:ss is used.<p>
<ide> *
<ide> * @param runtime the time to format
<add> *
<ide> * @return the formatted runtime
<ide> */
<ide> public static String formatRuntime(long runtime) {
<ide> * or the empty String <code>""</code>.<p>
<ide> *
<ide> * @param value the value to check
<add> *
<ide> * @return true, if the provided value is null or the empty String, false otherwise
<ide> */
<ide> public static boolean isEmpty(String value) {
<ide> * or contains only white spaces.<p>
<ide> *
<ide> * @param value the value to check
<add> *
<ide> * @return true, if the provided value is null or contains only white spaces, false otherwise
<ide> */
<ide> public static boolean isEmptyOrWhitespaceOnly(String value) {
<ide> * @param value2 the second object to compare
<ide> *
<ide> * @return <code>true</code> if the provided Objects are either both <code>null</code>
<del> * or equal according to {@link Object#equals(Object)}
<add> * or equal according to {@link Object#equals(Object)}
<ide> */
<ide> public static boolean isEqual(Object value1, Object value2) {
<ide>
<ide> * nor the empty String <code>""</code>.<p>
<ide> *
<ide> * @param value the value to check
<add> *
<ide> * @return true, if the provided value is not null and not the empty String, false otherwise
<ide> */
<ide> public static boolean isNotEmpty(String value) {
<ide> * nor contains only white spaces.<p>
<ide> *
<ide> * @param value the value to check
<del> * @return true, if the provided value is null or contains only white spaces, false otherwise
<add> *
<add> * @return <code>true</code>, if the provided value is <code>null</code>
<add> * or contains only white spaces, <code>false</code> otherwise
<ide> */
<ide> public static boolean isNotEmptyOrWhitespaceOnly(String value) {
<ide>
<ide> * Checks if the given class name is a valid Java class name.<p>
<ide> *
<ide> * @param className the name to check
<add> *
<ide> * @return true if the given class name is a valid Java class name
<ide> */
<ide> public static boolean isValidJavaClassName(String className) {
<ide> *
<ide> * @param source the String to split
<ide> * @param delimiter the delimiter to split at
<del> * @param trim flag to indicate if leading and trailing whitespaces should be omitted
<add> * @param trim flag to indicate if leading and trailing white spaces should be omitted
<ide> *
<ide> * @return the List of splitted Substrings
<ide> */
<ide> *
<ide> * @param source the String to split
<ide> * @param delimiter the delimiter to split at
<del> * @param trim flag to indicate if leading and trailing whitespaces should be omitted
<add> * @param trim flag to indicate if leading and trailing white spaces should be omitted
<ide> *
<ide> * @return the Array of splitted Substrings
<ide> */
<ide>
<ide> /**
<ide> * Splits a String into substrings along the provided <code>paramDelim</code> delimiter,
<del> * then each substring is treat as a key-value pair delimited by <code>keyValDelim</code>.
<add> * then each substring is treat as a key-value pair delimited by <code>keyValDelim</code>.<p>
<ide> *
<ide> * @param source the string to split
<ide> * @param paramDelim the string to delimit each key-value pair
<ide> * Replaces a set of <code>searchString</code> and <code>replaceString</code> pairs,
<ide> * given by the <code>substitutions</code> Map parameter.<p>
<ide> *
<del> * @param source the constent which is scanned
<add> * @param source the string to scan
<ide> * @param substitions the map of substitutions
<ide> *
<ide> * @return the substituted String
<ide> *
<ide> * @param htmlContent the HTML to replace the context path in
<ide> * @param context the context path of the server
<add> *
<ide> * @return the HTML with the replaced context path
<ide> */
<ide> public static String substituteContextPath(String htmlContent, String context) {
<ide> * @param content the content which is scanned
<ide> * @param searchString the String which is searched in content
<ide> * @param replaceItem the new String which replaces searchString
<del> * @param occurences must be a "g" if all occurences of searchString shall be replaced
<add> * @param occurences must be a "g" if all occurrences of searchString shall be replaced
<add> *
<ide> * @return String the substituted String
<ide> */
<ide> public static String substitutePerl(String content, String searchString, String replaceItem, String occurences) {
<ide> /**
<ide> * Returns the java String literal for the given String. <p>
<ide> *
<del> * This is the form of the String that had to be written into sourcecode
<add> * This is the form of the String that had to be written into source code
<ide> * using the unicode escape sequence for special characters. <p>
<ide> *
<ide> * Example: "" would be transformed to "\\u00C4".<p>
<ide> * valid characters.<p>
<ide> *
<ide> * @param name the resource name to check
<del> * @return true if the resource name is vaild, false otherwise
<add> * @return true if the resource name is valid, false otherwise
<ide> *
<ide> * @deprecated use {@link org.opencms.file.CmsResource#checkResourceName(String)} instead
<ide> */
<ide> return false;
<ide> }
<ide> if (name.length() != name.trim().length()) {
<del> // leading or trainling white space are not allowed
<add> // leading or trailing white space are not allowed
<ide> return false;
<ide> }
<ide> for (int i = 0; i < l; i++) { |
|
Java | mit | f2c7d360fbc777aad48b3ee099ba6695453e57a0 | 0 | nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server | control-base/src/main/java/fi/nls/oskari/control/layer/GetWFSLayerConfigurationHandler.java | package fi.nls.oskari.control.layer;
import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionHandler;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.domain.map.UserDataLayer;
import fi.nls.oskari.domain.map.analysis.Analysis;
import fi.nls.oskari.domain.map.wfs.WFSLayerConfiguration;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.analysis.service.AnalysisDataService;
import fi.nls.oskari.myplaces.MyPlacesService;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.PropertyUtil;
import fi.nls.oskari.util.ResponseHelper;
import fi.nls.oskari.wfs.WFSLayerConfigurationService;
import fi.nls.oskari.wfs.WFSLayerConfigurationServiceIbatisImpl;
import org.json.JSONObject;
import org.oskari.map.userlayer.service.UserLayerDbService;
@OskariActionRoute("GetWFSLayerConfiguration")
public class GetWFSLayerConfigurationHandler extends ActionHandler {
private static final Logger log = LogFactory
.getLogger(GetWFSLayerConfigurationHandler.class);
private final WFSLayerConfigurationService layerConfigurationService = new WFSLayerConfigurationServiceIbatisImpl();
private AnalysisDataService analysisDataService = new AnalysisDataService();
private UserLayerDbService userLayerDbService;
private MyPlacesService myPlacesService = null;
private final static String PARAMS_ID = "id";
private final static String RESULT = "result";
private final static String RESULT_SUCCESS = "success";
private final static String RESULT_WFSLAYER = "wfslayer";
// Analysis
public static final String ANALYSIS_BASELAYER_ID = "analysis.baselayer.id";
public static final String ANALYSIS_PREFIX = "analysis_";
// My places
public static final String MYPLACES_BASELAYER_ID = "myplaces.baselayer.id";
public static final String MYPLACES_PREFIX = "myplaces_";
// User layer
public static final String USERLAYER_BASELAYER_ID = "userlayer.baselayer.id";
public static final String USERLAYER_PREFIX = "userlayer_";
public void init() {
myPlacesService = OskariComponentManager.getComponentOfType(MyPlacesService.class);
userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class);
}
public void handleAction(ActionParameters params) throws ActionException {
// Because of analysis layers
final String sid = params.getHttpParam(PARAMS_ID, "n/a");
final int id = ConversionHelper.getInt(getBaseLayerId(sid), -1);
if(id == -1) {
throw new ActionParamsException("Required parameter '" + PARAMS_ID + "' missing!");
}
final WFSLayerConfiguration lc = getLayerInfoForRedis(id, sid);
if (lc == null) {
throw new ActionParamsException("Couldn't find matching layer for id " + id +
". Requested layer: " + sid);
}
// lc.save() saves the layer info to redis as JSON so transport can use this
lc.save();
final JSONObject root = new JSONObject();
if (params.getUser().isAdmin()) {
// for admin, write the JSON to response as admin-layerselector uses this
JSONHelper.putValue(root, RESULT_WFSLAYER, lc.getAsJSONObject());
} else {
// for all other users, just reply success (==data can be read from Redis)
JSONHelper.putValue(root, RESULT, RESULT_SUCCESS);
}
ResponseHelper.writeResponse(params, root);
}
private WFSLayerConfiguration getLayerInfoForRedis(final int id, final String requestedLayerId) {
log.info("Loading wfs layer with id:", id, "requested layer id:", requestedLayerId);
final WFSLayerConfiguration lc = layerConfigurationService.findConfiguration(id);
log.debug(lc);
final long userDataLayerId = extractId(requestedLayerId);
UserDataLayer userLayer = null;
// Extra manage for analysis
if (requestedLayerId.startsWith(ANALYSIS_PREFIX)) {
final Analysis analysis = analysisDataService.getAnalysisById(userDataLayerId);
// Set analysis layer fields as id based
lc.setSelectedFeatureParams(analysisDataService.getAnalysisNativeColumns(analysis));
userLayer = analysis;
}
// Extra manage for myplaces
else if (requestedLayerId.startsWith(MYPLACES_PREFIX)) {
userLayer = myPlacesService.findCategory(userDataLayerId);
}
// Extra manage for imported data
else if (requestedLayerId.startsWith(USERLAYER_PREFIX)) {
userLayer = userLayerDbService.getUserLayerById(userDataLayerId);
}
if(userLayer != null) {
log.debug("Was a user created layer");
// set id to user data layer id for redis
lc.setLayerId(requestedLayerId);
if(userLayer.isPublished()) {
// Transport uses this uuid in WFS query instead of users id if published is true.
lc.setPublished(true);
lc.setUuid(userLayer.getUuid());
log.debug("Was published", lc);
}
}
return lc;
}
/**
* Return base wfs id
*
* @param sid
* @return id
*/
private String getBaseLayerId(final String sid) {
if (sid.startsWith(ANALYSIS_PREFIX)) {
return PropertyUtil.get(ANALYSIS_BASELAYER_ID);
}
else if (sid.startsWith(MYPLACES_PREFIX)) {
return PropertyUtil.get(MYPLACES_BASELAYER_ID);
}
else if (sid.startsWith(USERLAYER_PREFIX)) {
return PropertyUtil.get(USERLAYER_BASELAYER_ID);
}
return sid;
}
private long extractId(final String layerId) {
if (layerId == null) {
return -1;
}
// takeout the last _-separated token
// -> this is the actual id in analysis, myplaces, userlayer
final String[] values = layerId.split("_");
if(values.length < 2) {
// wasn't valid id!
return -1;
}
final String id = values[values.length - 1];
return ConversionHelper.getLong(id, -1);
}
}
| Remove as transport specific
| control-base/src/main/java/fi/nls/oskari/control/layer/GetWFSLayerConfigurationHandler.java | Remove as transport specific | <ide><path>ontrol-base/src/main/java/fi/nls/oskari/control/layer/GetWFSLayerConfigurationHandler.java
<del>package fi.nls.oskari.control.layer;
<del>
<del>import fi.nls.oskari.annotation.OskariActionRoute;
<del>import fi.nls.oskari.control.ActionException;
<del>import fi.nls.oskari.control.ActionHandler;
<del>import fi.nls.oskari.control.ActionParameters;
<del>import fi.nls.oskari.control.ActionParamsException;
<del>import fi.nls.oskari.domain.map.UserDataLayer;
<del>import fi.nls.oskari.domain.map.analysis.Analysis;
<del>import fi.nls.oskari.domain.map.wfs.WFSLayerConfiguration;
<del>import fi.nls.oskari.log.LogFactory;
<del>import fi.nls.oskari.log.Logger;
<del>import fi.nls.oskari.map.analysis.service.AnalysisDataService;
<del>import fi.nls.oskari.myplaces.MyPlacesService;
<del>import fi.nls.oskari.service.OskariComponentManager;
<del>import fi.nls.oskari.util.ConversionHelper;
<del>import fi.nls.oskari.util.JSONHelper;
<del>import fi.nls.oskari.util.PropertyUtil;
<del>import fi.nls.oskari.util.ResponseHelper;
<del>import fi.nls.oskari.wfs.WFSLayerConfigurationService;
<del>import fi.nls.oskari.wfs.WFSLayerConfigurationServiceIbatisImpl;
<del>import org.json.JSONObject;
<del>import org.oskari.map.userlayer.service.UserLayerDbService;
<del>
<del>@OskariActionRoute("GetWFSLayerConfiguration")
<del>public class GetWFSLayerConfigurationHandler extends ActionHandler {
<del>
<del> private static final Logger log = LogFactory
<del> .getLogger(GetWFSLayerConfigurationHandler.class);
<del>
<del> private final WFSLayerConfigurationService layerConfigurationService = new WFSLayerConfigurationServiceIbatisImpl();
<del> private AnalysisDataService analysisDataService = new AnalysisDataService();
<del> private UserLayerDbService userLayerDbService;
<del> private MyPlacesService myPlacesService = null;
<del>
<del> private final static String PARAMS_ID = "id";
<del>
<del> private final static String RESULT = "result";
<del> private final static String RESULT_SUCCESS = "success";
<del> private final static String RESULT_WFSLAYER = "wfslayer";
<del>
<del> // Analysis
<del> public static final String ANALYSIS_BASELAYER_ID = "analysis.baselayer.id";
<del> public static final String ANALYSIS_PREFIX = "analysis_";
<del>
<del> // My places
<del> public static final String MYPLACES_BASELAYER_ID = "myplaces.baselayer.id";
<del> public static final String MYPLACES_PREFIX = "myplaces_";
<del>
<del> // User layer
<del> public static final String USERLAYER_BASELAYER_ID = "userlayer.baselayer.id";
<del> public static final String USERLAYER_PREFIX = "userlayer_";
<del>
<del> public void init() {
<del> myPlacesService = OskariComponentManager.getComponentOfType(MyPlacesService.class);
<del> userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class);
<del> }
<del>
<del> public void handleAction(ActionParameters params) throws ActionException {
<del>
<del> // Because of analysis layers
<del> final String sid = params.getHttpParam(PARAMS_ID, "n/a");
<del> final int id = ConversionHelper.getInt(getBaseLayerId(sid), -1);
<del> if(id == -1) {
<del> throw new ActionParamsException("Required parameter '" + PARAMS_ID + "' missing!");
<del> }
<del> final WFSLayerConfiguration lc = getLayerInfoForRedis(id, sid);
<del>
<del> if (lc == null) {
<del> throw new ActionParamsException("Couldn't find matching layer for id " + id +
<del> ". Requested layer: " + sid);
<del> }
<del>
<del> // lc.save() saves the layer info to redis as JSON so transport can use this
<del> lc.save();
<del>
<del> final JSONObject root = new JSONObject();
<del> if (params.getUser().isAdmin()) {
<del> // for admin, write the JSON to response as admin-layerselector uses this
<del> JSONHelper.putValue(root, RESULT_WFSLAYER, lc.getAsJSONObject());
<del> } else {
<del> // for all other users, just reply success (==data can be read from Redis)
<del> JSONHelper.putValue(root, RESULT, RESULT_SUCCESS);
<del> }
<del> ResponseHelper.writeResponse(params, root);
<del> }
<del>
<del> private WFSLayerConfiguration getLayerInfoForRedis(final int id, final String requestedLayerId) {
<del>
<del> log.info("Loading wfs layer with id:", id, "requested layer id:", requestedLayerId);
<del> final WFSLayerConfiguration lc = layerConfigurationService.findConfiguration(id);
<del> log.debug(lc);
<del> final long userDataLayerId = extractId(requestedLayerId);
<del> UserDataLayer userLayer = null;
<del>
<del> // Extra manage for analysis
<del> if (requestedLayerId.startsWith(ANALYSIS_PREFIX)) {
<del> final Analysis analysis = analysisDataService.getAnalysisById(userDataLayerId);
<del> // Set analysis layer fields as id based
<del> lc.setSelectedFeatureParams(analysisDataService.getAnalysisNativeColumns(analysis));
<del> userLayer = analysis;
<del> }
<del> // Extra manage for myplaces
<del> else if (requestedLayerId.startsWith(MYPLACES_PREFIX)) {
<del> userLayer = myPlacesService.findCategory(userDataLayerId);
<del> }
<del> // Extra manage for imported data
<del> else if (requestedLayerId.startsWith(USERLAYER_PREFIX)) {
<del> userLayer = userLayerDbService.getUserLayerById(userDataLayerId);
<del> }
<del> if(userLayer != null) {
<del> log.debug("Was a user created layer");
<del> // set id to user data layer id for redis
<del> lc.setLayerId(requestedLayerId);
<del> if(userLayer.isPublished()) {
<del> // Transport uses this uuid in WFS query instead of users id if published is true.
<del> lc.setPublished(true);
<del> lc.setUuid(userLayer.getUuid());
<del> log.debug("Was published", lc);
<del> }
<del> }
<del> return lc;
<del> }
<del>
<del> /**
<del> * Return base wfs id
<del> *
<del> * @param sid
<del> * @return id
<del> */
<del> private String getBaseLayerId(final String sid) {
<del> if (sid.startsWith(ANALYSIS_PREFIX)) {
<del> return PropertyUtil.get(ANALYSIS_BASELAYER_ID);
<del> }
<del> else if (sid.startsWith(MYPLACES_PREFIX)) {
<del> return PropertyUtil.get(MYPLACES_BASELAYER_ID);
<del> }
<del> else if (sid.startsWith(USERLAYER_PREFIX)) {
<del> return PropertyUtil.get(USERLAYER_BASELAYER_ID);
<del> }
<del> return sid;
<del> }
<del>
<del> private long extractId(final String layerId) {
<del> if (layerId == null) {
<del> return -1;
<del> }
<del> // takeout the last _-separated token
<del> // -> this is the actual id in analysis, myplaces, userlayer
<del> final String[] values = layerId.split("_");
<del> if(values.length < 2) {
<del> // wasn't valid id!
<del> return -1;
<del> }
<del> final String id = values[values.length - 1];
<del> return ConversionHelper.getLong(id, -1);
<del> }
<del>} |
||
JavaScript | apache-2.0 | c8c968a2aaf79ab812b34e58f654e86da0fd0378 | 0 | flamingcowtv/cosmopolite,flamingcowtv/cosmopolite,flamingcowtv/cosmopolite,flamingcowtv/cosmopolite,flamingcowtv/cosmopolite | /**
* @license
* Copyright 2014, Ian Gulliver
*
* 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.
*/
/*
A quick note on testing philosophy:
These tests cover both the client (JavaScript) and the server (Python), as
well as the server's interaction with appengine (via dev_appserver or a
deployed instance). There is intentionally no mock server. The client and
server interactions are complex and tests should be structured to verify them,
not to verify the behavior of a simulation.
*/
/*
These tests break if you turn on global pollution detection because of at
least:
* goog: goog.appengine.Channel seems to always be global.
* closure_lm_*: The Channel code has a bug that puts this in globals.
*/
var randstring = function() {
var ret = [];
for (var i = 0; i < 16; i++) {
var ran = (Math.random() * 16) | 0;
ret.push(ran.toString(16));
}
return ret.join('');
};
var logout = function(callback) {
var innerCallback = function(e) {
window.removeEventListener('message', innerCallback);
if (e.origin != window.location.origin ||
e.data != 'logout_complete') {
return;
}
if (callback) {
callback();
}
};
window.addEventListener('message', innerCallback);
window.open('/cosmopolite/auth/logout');
};
QUnit.testStart(localStorage.clear.bind(localStorage));
QUnit.testDone(localStorage.clear.bind(localStorage));
module('All platforms');
test('Construct/shutdown', function() {
expect(2);
var cosmo = new Cosmopolite({}, null, randstring());
ok(true, 'new Cosmopolite() succeeds');
cosmo.shutdown();
ok(true, 'shutdown() succeeds');
});
asyncTest('onLogout fires', function() {
expect(1);
logout(function() {
var callbacks = {
'onLogout': function(login_url) {
ok(true, 'onLogout fired');
cosmo.shutdown();
start();
}
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
});
});
asyncTest('Message round trip', function() {
expect(2);
var subject = randstring();
var message = randstring();
var callbacks = {
'onMessage': function(e) {
equal(e['subject']['name'], subject, 'subject matches');
equal(e['message'], message, 'message matches');
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.sendMessage(subject, message);
cosmo.subscribe(subject, -1);
});
asyncTest('Overwrite key', function() {
expect(8);
var subject = randstring();
var message1 = randstring();
var message2 = randstring();
var key = randstring();
var messages = 0;
var callbacks = {
'onMessage': function(e) {
messages++;
equal(e['subject']['name'], subject, 'subject matches');
equal(e['key'], key, 'key matches');
if (messages == 1) {
equal(e['message'], message1, 'message #1 matches');
equal(cosmo.getKeyMessage(subject, key)['message'], message1, 'message #1 matches by key')
cosmo.sendMessage(subject, message2, key);
return;
}
equal(e['message'], message2, 'message #2 matches');
equal(cosmo.getKeyMessage(subject, key)['message'], message2, 'message #2 matches by key')
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.subscribe(subject, -1);
cosmo.sendMessage(subject, message1, key);
});
asyncTest('Complex object', function() {
expect(2);
var subject = randstring();
var message = {
'foo': 'bar',
5: 'zig',
'zag': [16, 22, 59, 76],
'boo': {
'nested': 'object',
10: 100,
},
'unicode': '☠☣☃��',
};
var callbacks = {
'onMessage': function(e) {
equal(e['subject']['name'], subject, 'subject matches');
deepEqual(e['message'], message, 'message matches');
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.sendMessage(subject, message);
cosmo.subscribe(subject, -1);
});
asyncTest('sendMessage Promise', function() {
expect(1);
var subject = randstring();
var message = randstring();
var cosmo = new Cosmopolite({}, null, randstring());
cosmo.sendMessage(subject, message).then(function() {
ok(true, 'sendMessage Promise fulfilled');
cosmo.shutdown();
start();
});
});
asyncTest('subscribe/unsubscribe Promise', function() {
expect(2);
var subject = randstring();
var message = randstring();
var cosmo = new Cosmopolite({}, null, randstring());
cosmo.subscribe(subject).then(function() {
ok(true, 'subscribe Promise fulfilled');
cosmo.unsubscribe(subject).then(function() {
ok(true, 'unsubscribe Promise fulfilled');
cosmo.shutdown();
start();
});
});
});
asyncTest('Duplicate message suppression', function() {
expect(3);
var subject = randstring();
var key = randstring();
var message1 = randstring();
var message2 = randstring();
var callbacks = {
'onMessage': function (msg) {
equal(msg['subject']['name'], subject, 'subject matches');
equal(msg['key'], key, 'key matches');
equal(msg['message'], message1, 'message matches');
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
// Break cosmo's UUID generator so that it generates duplicate values.
cosmo.uuid_ = function() {
return '4';
// chosen by fair dice roll.
// guaranteed to be random.
};
cosmo.sendMessage(subject, message1, key).then(function() {
cosmo.sendMessage(subject, message2, key).then(function() {
cosmo.subscribe(subject, 0, [key]);
});
});
});
asyncTest('Message persistence', function() {
expect(2);
var subject = randstring();
var message = randstring();
var namespace = randstring();
// Send a message and shut down too fast for it to hit the wire.
var cosmo1 = new Cosmopolite({}, null, namespace);
cosmo1.sendMessage(subject, message);
cosmo1.shutdown();
var callbacks = {
'onMessage': function(msg) {
equal(msg['subject']['name'], subject, 'subject matches');
equal(msg['message'], message, 'message matches');
cosmo2.shutdown();
start();
},
};
var cosmo2 = new Cosmopolite(callbacks, null, namespace);
cosmo2.subscribe(subject, -1);
// Should pick up the message from the persistent queue.
});
test('getMessages/subscribe', function() {
expect(2);
var subject = randstring();
var cosmo = new Cosmopolite({}, null, randstring());
throws(
cosmo.getMessages.bind(undefined, subject),
'getMessages before subscribe fails');
cosmo.subscribe(subject);
// Verify that we can call getMessages immediately after subscribe
cosmo.getMessages(subject);
ok(true, 'getMessages after subscribe succeeds');
cosmo.shutdown();
});
module('dev_appserver only');
asyncTest('Login', function() {
expect(3);
var anonymousProfile;
logout(function() {
var callbacks = {
'onLogout': function(login_url) {
ok(true, 'onLogout fired');
anonymousProfile = cosmo.profile();
// Entirely magic URL that sets the login cookie and redirects.
window.open('/_ah/login?email=test%40example.com&action=Login&continue=/cosmopolite/static/login_complete.html');
},
'onLogin': function(login_url) {
ok(true, 'onLogin fired');
notEqual(anonymousProfile, cosmo.profile(), 'profile changed');
cosmo.shutdown();
logout();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
});
});
asyncTest('Profile merge', function() {
expect(6);
var subject = randstring();
var message = randstring();
var messages = 0;
logout(function() {
var callbacks = {
'onMessage': function(msg) {
messages++;
equal(msg['subject']['name'], subject,
'message #' + messages + ': subject matches');
equal(msg['message'], message,
'message #' + messages + ': message matches');
equal(msg['sender'], cosmo.profile(),
'message #' + messages + ': profile matches');
if (messages == 1) {
cosmo.unsubscribe(subject);
// Entirely magic URL that sets the login cookie and redirects.
window.open('/_ah/login?email=test%40example.com&action=Login&continue=/cosmopolite/static/login_complete.html');
}
if (messages == 2) {
cosmo.shutdown();
start();
}
},
'onLogin': function(logout_url) {
cosmo.subscribe(subject, -1);
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.sendMessage(subject, message);
cosmo.subscribe(subject, -1);
});
});
| static/test.js | /**
* @license
* Copyright 2014, Ian Gulliver
*
* 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.
*/
/*
A quick note on testing philosophy:
These tests cover both the client (JavaScript) and the server (Python), as
well as the server's interaction with appengine (via dev_appserver or a
deployed instance). There is intentionally no mock server. The client and
server interactions are complex and tests should be structured to verify them,
not to verify the behavior of a simulation.
*/
/*
These tests break if you turn on global pollution detection because of at
least:
* goog: goog.appengine.Channel seems to always be global.
* closure_lm_*: The Channel code has a bug that puts this in globals.
*/
var randstring = function() {
var ret = [];
for (var i = 0; i < 16; i++) {
var ran = (Math.random() * 16) | 0;
ret.push(ran.toString(16));
}
return ret.join('');
};
var logout = function(callback) {
var innerCallback = function(e) {
window.removeEventListener('message', innerCallback);
if (e.origin != window.location.origin ||
e.data != 'logout_complete') {
return;
}
if (callback) {
callback();
}
};
window.addEventListener('message', innerCallback);
window.open('/cosmopolite/auth/logout');
};
QUnit.testStart(localStorage.clear.bind(localStorage));
QUnit.testDone(localStorage.clear.bind(localStorage));
module('All platforms');
test('Construct/shutdown', function() {
expect(2);
var cosmo = new Cosmopolite({});
ok(true, 'new Cosmopolite() succeeds');
cosmo.shutdown();
ok(true, 'shutdown() succeeds');
});
asyncTest('onLogout fires', function() {
expect(1);
logout(function() {
var callbacks = {
'onLogout': function(login_url) {
ok(true, 'onLogout fired');
cosmo.shutdown();
start();
}
};
var cosmo = new Cosmopolite(callbacks);
});
});
asyncTest('Message round trip', function() {
expect(2);
var subject = randstring();
var message = randstring();
var callbacks = {
'onMessage': function(e) {
equal(e['subject']['name'], subject, 'subject matches');
equal(e['message'], message, 'message matches');
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.sendMessage(subject, message);
cosmo.subscribe(subject, -1);
});
asyncTest('Overwrite key', function() {
expect(8);
var subject = randstring();
var message1 = randstring();
var message2 = randstring();
var key = randstring();
var messages = 0;
var callbacks = {
'onMessage': function(e) {
messages++;
equal(e['subject']['name'], subject, 'subject matches');
equal(e['key'], key, 'key matches');
if (messages == 1) {
equal(e['message'], message1, 'message #1 matches');
equal(cosmo.getKeyMessage(subject, key)['message'], message1, 'message #1 matches by key')
cosmo.sendMessage(subject, message2, key);
return;
}
equal(e['message'], message2, 'message #2 matches');
equal(cosmo.getKeyMessage(subject, key)['message'], message2, 'message #2 matches by key')
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.subscribe(subject, -1);
cosmo.sendMessage(subject, message1, key);
});
asyncTest('Complex object', function() {
expect(2);
var subject = randstring();
var message = {
'foo': 'bar',
5: 'zig',
'zag': [16, 22, 59, 76],
'boo': {
'nested': 'object',
10: 100,
},
'unicode': '☠☣☃��',
};
var callbacks = {
'onMessage': function(e) {
equal(e['subject']['name'], subject, 'subject matches');
deepEqual(e['message'], message, 'message matches');
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
cosmo.sendMessage(subject, message);
cosmo.subscribe(subject, -1);
});
asyncTest('sendMessage Promise', function() {
expect(1);
var subject = randstring();
var message = randstring();
var cosmo = new Cosmopolite({}, null, randstring());
cosmo.sendMessage(subject, message).then(function() {
ok(true, 'sendMessage Promise fulfilled');
cosmo.shutdown();
start();
});
});
asyncTest('subscribe/unsubscribe Promise', function() {
expect(2);
var subject = randstring();
var message = randstring();
var cosmo = new Cosmopolite({}, null, randstring());
cosmo.subscribe(subject).then(function() {
ok(true, 'subscribe Promise fulfilled');
cosmo.unsubscribe(subject).then(function() {
ok(true, 'unsubscribe Promise fulfilled');
cosmo.shutdown();
start();
});
});
});
asyncTest('Duplicate message suppression', function() {
expect(3);
var subject = randstring();
var key = randstring();
var message1 = randstring();
var message2 = randstring();
var callbacks = {
'onMessage': function (msg) {
equal(msg['subject']['name'], subject, 'subject matches');
equal(msg['key'], key, 'key matches');
equal(msg['message'], message1, 'message matches');
cosmo.shutdown();
start();
},
};
var cosmo = new Cosmopolite(callbacks, null, randstring());
// Break cosmo's UUID generator so that it generates duplicate values.
cosmo.uuid_ = function() {
return '4';
// chosen by fair dice roll.
// guaranteed to be random.
};
cosmo.sendMessage(subject, message1, key).then(function() {
cosmo.sendMessage(subject, message2, key).then(function() {
cosmo.subscribe(subject, 0, [key]);
});
});
});
asyncTest('Message persistence', function() {
expect(2);
var subject = randstring();
var message = randstring();
var namespace = randstring();
// Send a message and shut down too fast for it to hit the wire.
var cosmo1 = new Cosmopolite({}, null, namespace);
cosmo1.sendMessage(subject, message);
cosmo1.shutdown();
var callbacks = {
'onMessage': function(msg) {
equal(msg['subject']['name'], subject, 'subject matches');
equal(msg['message'], message, 'message matches');
cosmo2.shutdown();
start();
},
};
var cosmo2 = new Cosmopolite(callbacks, null, namespace);
cosmo2.subscribe(subject, -1);
// Should pick up the message from the persistent queue.
});
module('dev_appserver only');
asyncTest('Login', function() {
expect(3);
var anonymousProfile;
logout(function() {
var callbacks = {
'onLogout': function(login_url) {
ok(true, 'onLogout fired');
anonymousProfile = cosmo.profile();
// Entirely magic URL that sets the login cookie and redirects.
window.open('/_ah/login?email=test%40example.com&action=Login&continue=/cosmopolite/static/login_complete.html');
},
'onLogin': function(login_url) {
ok(true, 'onLogin fired');
notEqual(anonymousProfile, cosmo.profile(), 'profile changed');
cosmo.shutdown();
logout();
start();
},
};
var cosmo = new Cosmopolite(callbacks);
});
});
asyncTest('Profile merge', function() {
expect(6);
var subject = randstring();
var message = randstring();
var messages = 0;
logout(function() {
var callbacks = {
'onMessage': function(msg) {
messages++;
equal(msg['subject']['name'], subject,
'message #' + messages + ': subject matches');
equal(msg['message'], message,
'message #' + messages + ': message matches');
equal(msg['sender'], cosmo.profile(),
'message #' + messages + ': profile matches');
if (messages == 1) {
cosmo.unsubscribe(subject);
// Entirely magic URL that sets the login cookie and redirects.
window.open('/_ah/login?email=test%40example.com&action=Login&continue=/cosmopolite/static/login_complete.html');
}
if (messages == 2) {
cosmo.shutdown();
start();
}
},
'onLogin': function(logout_url) {
cosmo.subscribe(subject, -1);
},
};
var cosmo = new Cosmopolite(callbacks);
cosmo.sendMessage(subject, message);
cosmo.subscribe(subject, -1);
});
});
| Add test for getMessages/subscribe interaction. Move other tests into their own namespaces.
| static/test.js | Add test for getMessages/subscribe interaction. Move other tests into their own namespaces. | <ide><path>tatic/test.js
<ide>
<ide> test('Construct/shutdown', function() {
<ide> expect(2);
<del> var cosmo = new Cosmopolite({});
<add> var cosmo = new Cosmopolite({}, null, randstring());
<ide> ok(true, 'new Cosmopolite() succeeds');
<ide> cosmo.shutdown();
<ide> ok(true, 'shutdown() succeeds');
<ide> start();
<ide> }
<ide> };
<del> var cosmo = new Cosmopolite(callbacks);
<add> var cosmo = new Cosmopolite(callbacks, null, randstring());
<ide> });
<ide> });
<ide>
<ide> var cosmo2 = new Cosmopolite(callbacks, null, namespace);
<ide> cosmo2.subscribe(subject, -1);
<ide> // Should pick up the message from the persistent queue.
<add>});
<add>
<add>test('getMessages/subscribe', function() {
<add> expect(2);
<add>
<add> var subject = randstring();
<add>
<add> var cosmo = new Cosmopolite({}, null, randstring());
<add> throws(
<add> cosmo.getMessages.bind(undefined, subject),
<add> 'getMessages before subscribe fails');
<add> cosmo.subscribe(subject);
<add> // Verify that we can call getMessages immediately after subscribe
<add> cosmo.getMessages(subject);
<add> ok(true, 'getMessages after subscribe succeeds');
<add>
<add> cosmo.shutdown();
<ide> });
<ide>
<ide>
<ide> start();
<ide> },
<ide> };
<del> var cosmo = new Cosmopolite(callbacks);
<add> var cosmo = new Cosmopolite(callbacks, null, randstring());
<ide> });
<ide> });
<ide>
<ide> cosmo.subscribe(subject, -1);
<ide> },
<ide> };
<del> var cosmo = new Cosmopolite(callbacks);
<add> var cosmo = new Cosmopolite(callbacks, null, randstring());
<ide> cosmo.sendMessage(subject, message);
<ide> cosmo.subscribe(subject, -1);
<ide> }); |
|
Java | apache-2.0 | 27dcdef75b7d9f679e006d7107ea3f743bfd9b35 | 0 | acsl/orika,brabenetz/orika,Log10Solutions/orika,orika-mapper/orika,leimer/orika,andreabertagnolli/orika,ellis429/orika | /*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011 Orika 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 ma.glasnost.orika.impl;
import java.util.concurrent.ConcurrentHashMap;
import ma.glasnost.orika.BoundMapperFacade;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.MappingContextFactory;
import ma.glasnost.orika.ObjectFactory;
import ma.glasnost.orika.impl.mapping.strategy.MappingStrategy;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;
import ma.glasnost.orika.unenhance.UnenhanceStrategy;
/**
* DefaultBoundMapperFacade is the base implementation of BoundMapperFacade
*
* @author [email protected]
*
*/
class DefaultBoundMapperFacade<A, B> implements BoundMapperFacade<A, B> {
/*
* Keep small cache of strategies; we expect the total size to be == 1 in most cases,
* but some polymorphism is possible
*/
protected final BoundStrategyCache aToB;
protected final BoundStrategyCache bToA;
protected final BoundStrategyCache aToBInPlace;
protected final BoundStrategyCache bToAInPlace;
protected volatile ObjectFactory<A> objectFactoryA;
protected volatile ObjectFactory<B> objectFactoryB;
protected final java.lang.reflect.Type rawAType;
protected final java.lang.reflect.Type rawBType;
protected final Type<A> aType;
protected final Type<B> bType;
protected final MapperFactory mapperFactory;
protected final MappingContextFactory contextFactory;
/**
* Constructs a new instance of DefaultBoundMapperFacade
*
* @param mapperFactory
* @param contextFactory
* @param typeOfA
* @param typeOfB
*/
DefaultBoundMapperFacade(MapperFactory mapperFactory, MappingContextFactory contextFactory, java.lang.reflect.Type typeOfA, java.lang.reflect.Type typeOfB) {
this.mapperFactory = mapperFactory;
this.contextFactory = contextFactory;
this.rawAType = typeOfA;
this.rawBType = typeOfB;
this.aType = TypeFactory.valueOf(typeOfA);
this.bType = TypeFactory.valueOf(typeOfB);
this.aToB = new BoundStrategyCache(aType, bType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), false);
this.bToA = new BoundStrategyCache(bType, aType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), false);
this.aToBInPlace = new BoundStrategyCache(aType, bType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), true);
this.bToAInPlace = new BoundStrategyCache(bType, aType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), true);
}
public Type<A> getAType() {
return aType;
}
public Type<B> getBType() {
return bType;
}
public B map(A instanceA) {
MappingContext context = contextFactory.getContext();
try {
return map(instanceA, context);
} finally {
contextFactory.release(context);
}
}
public A mapReverse(B source) {
MappingContext context = contextFactory.getContext();
try {
return mapReverse(source, context);
} finally {
contextFactory.release(context);
}
}
public B map(A instanceA, B instanceB) {
MappingContext context = contextFactory.getContext();
try {
return map(instanceA, instanceB, context);
} finally {
contextFactory.release(context);
}
}
public A mapReverse(B instanceB, A instanceA) {
MappingContext context = contextFactory.getContext();
try {
return mapReverse(instanceB, instanceA, context);
} finally {
contextFactory.release(context);
}
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapAtoB(java.lang.Object,
* ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public B map(A instanceA, MappingContext context) {
B result = (B) context.getMappedObject(instanceA, bType);
if (result == null && instanceA != null) {
result = (B) aToB.getStrategy(instanceA, context).map(instanceA, null, context);
}
return result;
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapBtoA(java.lang.Object,
* ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public A mapReverse(B instanceB, MappingContext context) {
A result = (A) context.getMappedObject(instanceB, aType);
if (result == null && instanceB != null) {
result = (A) bToA.getStrategy(instanceB, context).map(instanceB, null, context);
}
return result;
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapAtoB(java.lang.Object,
* java.lang.Object, ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public B map(A instanceA, B instanceB, MappingContext context) {
B result = (B) context.getMappedObject(instanceA, bType);
if (result == null && instanceA != null) {
result = (B) aToBInPlace.getStrategy(instanceA, context).map(instanceA, instanceB, context);
}
return result;
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapBtoA(java.lang.Object,
* java.lang.Object, ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public A mapReverse(B instanceB, A instanceA, MappingContext context) {
A result = (A) context.getMappedObject(instanceB, aType);
if (result == null && instanceB != null) {
result = (A) bToAInPlace.getStrategy(instanceB, context).map(instanceB, instanceA, context);
}
return result;
}
public String toString() {
return getClass().getSimpleName() + "(" + aType +", " + bType + ")";
}
/* (non-Javadoc)
* @see ma.glasnost.orika.DedicatedMapperFacade#newObjectB(java.lang.Object, ma.glasnost.orika.MappingContext)
*/
public B newObject(A source, MappingContext context) {
if (objectFactoryB == null) {
synchronized(this) {
if (objectFactoryB == null) {
objectFactoryB = mapperFactory.lookupObjectFactory(bType, aType);
}
}
}
return objectFactoryB.create(source, context);
}
/* (non-Javadoc)
* @see ma.glasnost.orika.DedicatedMapperFacade#newObjectA(java.lang.Object, ma.glasnost.orika.MappingContext)
*/
public A newObjectReverse(B source, MappingContext context) {
if (objectFactoryA == null) {
synchronized(this) {
if (objectFactoryA == null) {
objectFactoryA = mapperFactory.lookupObjectFactory(aType, bType);
}
}
}
return objectFactoryA.create(source, context);
}
/**
* BoundStrategyCache attempts to optimize caching of MappingStrategies for a particular
* situation based on the assumption that the most common case involves mapping with a single
* source type class (no polymorphism within most BoundMapperFacades); it accomplishes this
* by caching a single MappingStrategy as a default case which is always fast at hand, falling
* back to a (small) hashmap of backup strategies, keyed by source Class (since all of the other
* inputs to resolve the strategy are fixed to the BoundStrategyCache instance).
*
* @author [email protected]
*
*/
private static class BoundStrategyCache {
private final Type<?> aType;
private final Type<?> bType;
private final boolean inPlace;
private final MapperFacade mapperFacade;
private final UnenhanceStrategy unenhanceStrategy;
protected final ConcurrentHashMap<Class<?>, MappingStrategy> strategies = new ConcurrentHashMap<Class<?>, MappingStrategy>(2);
private volatile Class<?> idClass;
private volatile MappingStrategy defaultStrategy;
private BoundStrategyCache(Type<?> aType, Type<?> bType, MapperFacade mapperFacade, UnenhanceStrategy unenhanceStrategy, boolean inPlace) {
this.aType = aType;
this.bType = bType;
this.mapperFacade = mapperFacade;
this.unenhanceStrategy = unenhanceStrategy;
this.inPlace = inPlace;
}
public MappingStrategy getStrategy(Object sourceObject, MappingContext context) {
MappingStrategy strategy = null;
Class<?> sourceClass = getClass(sourceObject);
if (defaultStrategy != null && sourceClass.equals(idClass)) {
strategy = defaultStrategy;
} else if (defaultStrategy == null) {
synchronized(this) {
if (defaultStrategy == null) {
defaultStrategy = mapperFacade.resolveMappingStrategy(sourceObject, aType, bType, inPlace, context);
idClass = sourceClass;
strategies.put(idClass, defaultStrategy);
}
}
strategy = defaultStrategy;
} else {
strategy = strategies.get(sourceClass);
if (strategy == null) {
strategy = mapperFacade.resolveMappingStrategy(sourceObject, aType, bType, inPlace, context);
strategies.put(sourceClass, strategy);
}
}
/*
* Set the resolved types on the current mapping context; this can be used
* by downstream Mappers to determine the originally resolved types
*/
context.setResolvedSourceType(strategy.getAType());
context.setResolvedDestinationType(strategy.getBType());
return strategy;
}
protected Class<?> getClass(Object object) {
if (this.unenhanceStrategy == null) {
return object.getClass();
} else {
return unenhanceStrategy.unenhanceObject(object, TypeFactory.TYPE_OF_OBJECT).getClass();
}
}
}
}
| core/src/main/java/ma/glasnost/orika/impl/DefaultBoundMapperFacade.java | /*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011 Orika 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 ma.glasnost.orika.impl;
import java.util.concurrent.ConcurrentHashMap;
import ma.glasnost.orika.BoundMapperFacade;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.MappingContextFactory;
import ma.glasnost.orika.ObjectFactory;
import ma.glasnost.orika.impl.mapping.strategy.MappingStrategy;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;
import ma.glasnost.orika.unenhance.UnenhanceStrategy;
/**
* DefaultBoundMapperFacade is the base implementation of BoundMapperFacade
*
* @author [email protected]
*
*/
class DefaultBoundMapperFacade<A, B> implements BoundMapperFacade<A, B> {
/*
* Keep small cache of strategies; we expect the total size to be == 1 in most cases,
* but some polymorphism is possible
*/
protected final BoundStrategyCache aToB;
protected final BoundStrategyCache bToA;
protected final BoundStrategyCache aToBInPlace;
protected final BoundStrategyCache bToAInPlace;
protected volatile ObjectFactory<A> objectFactoryA;
protected volatile ObjectFactory<B> objectFactoryB;
protected final java.lang.reflect.Type rawAType;
protected final java.lang.reflect.Type rawBType;
protected final Type<A> aType;
protected final Type<B> bType;
protected final MapperFactory mapperFactory;
protected final MappingContextFactory contextFactory;
/**
* Constructs a new instance of DefaultBoundMapperFacade
*
* @param mapperFactory
* @param contextFactory
* @param typeOfA
* @param typeOfB
*/
DefaultBoundMapperFacade(MapperFactory mapperFactory, MappingContextFactory contextFactory, java.lang.reflect.Type typeOfA, java.lang.reflect.Type typeOfB) {
this.mapperFactory = mapperFactory;
this.contextFactory = contextFactory;
this.rawAType = typeOfA;
this.rawBType = typeOfB;
this.aType = TypeFactory.valueOf(typeOfA);
this.bType = TypeFactory.valueOf(typeOfB);
this.aToB = new BoundStrategyCache(aType, bType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), false);
this.bToA = new BoundStrategyCache(bType, aType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), false);
this.aToBInPlace = new BoundStrategyCache(aType, bType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), true);
this.bToAInPlace = new BoundStrategyCache(bType, aType, mapperFactory.getMapperFacade(), mapperFactory.getUserUnenhanceStrategy(), true);
}
public Type<A> getAType() {
return aType;
}
public Type<B> getBType() {
return bType;
}
public B map(A instanceA) {
MappingContext context = contextFactory.getContext();
try {
return map(instanceA, context);
} finally {
contextFactory.release(context);
}
}
public A mapReverse(B source) {
MappingContext context = contextFactory.getContext();
try {
return mapReverse(source, context);
} finally {
contextFactory.release(context);
}
}
public B map(A instanceA, B instanceB) {
MappingContext context = contextFactory.getContext();
try {
return map(instanceA, instanceB, context);
} finally {
contextFactory.release(context);
}
}
public A mapReverse(B instanceB, A instanceA) {
MappingContext context = contextFactory.getContext();
try {
return mapReverse(instanceB, instanceA, context);
} finally {
contextFactory.release(context);
}
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapAtoB(java.lang.Object,
* ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public B map(A instanceA, MappingContext context) {
B result = (B) context.getMappedObject(instanceA, bType);
if (result == null && instanceA != null) {
result = (B) aToB.getStrategy(instanceA, context).map(instanceA, null, context);
}
return result;
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapBtoA(java.lang.Object,
* ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public A mapReverse(B instanceB, MappingContext context) {
A result = (A) context.getMappedObject(instanceB, aType);
if (result == null && instanceB != null) {
result = (A) bToA.getStrategy(instanceB, context).map(instanceB, null, context);
}
return result;
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapAtoB(java.lang.Object,
* java.lang.Object, ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public B map(A instanceA, B instanceB, MappingContext context) {
B result = (B) context.getMappedObject(instanceA, bType);
if (result == null && instanceA != null) {
result = (B) aToBInPlace.getStrategy(instanceA, context).map(instanceA, instanceB, context);
}
return result;
}
/*
* (non-Javadoc)
*
* @see ma.glasnost.orika.DedicatedMapperFacade#mapBtoA(java.lang.Object,
* java.lang.Object, ma.glasnost.orika.MappingContext)
*/
@SuppressWarnings("unchecked")
public A mapReverse(B instanceB, A instanceA, MappingContext context) {
A result = (A) context.getMappedObject(instanceB, aType);
if (result == null && instanceB != null) {
result = (A) bToAInPlace.getStrategy(instanceB, context).map(instanceB, instanceA, context);
}
return result;
}
public String toString() {
return getClass().getSimpleName() + "(" + aType +", " + bType + ")";
}
/* (non-Javadoc)
* @see ma.glasnost.orika.DedicatedMapperFacade#newObjectB(java.lang.Object, ma.glasnost.orika.MappingContext)
*/
public B newObject(A source, MappingContext context) {
if (objectFactoryB == null) {
synchronized(this) {
if (objectFactoryB == null) {
objectFactoryB = mapperFactory.lookupObjectFactory(bType, aType);
}
}
}
return objectFactoryB.create(source, context);
}
/* (non-Javadoc)
* @see ma.glasnost.orika.DedicatedMapperFacade#newObjectA(java.lang.Object, ma.glasnost.orika.MappingContext)
*/
public A newObjectReverse(B source, MappingContext context) {
if (objectFactoryA == null) {
synchronized(this) {
if (objectFactoryA == null) {
objectFactoryA = mapperFactory.lookupObjectFactory(aType, bType);
}
}
}
return objectFactoryA.create(source, context);
}
/**
* BoundStrategyCache attempts to optimize caching of MappingStrategies for a particular
* situation based on the assumption that the most common case involves mapping with a single
* source type class (no polymorphism within most BoundMapperFacades); it accomplishes this
* by caching a single MappingStrategy as a default case which is always fast at hand, falling
* back to a (small) hashmap of backup strategies, keyed by source Class (since all of the other
* inputs to resolve the strategy are fixed to the BoundStrategyCache instance).
*
* @author [email protected]
*
*/
private static class BoundStrategyCache {
private final Type<?> aType;
private final Type<?> bType;
private final boolean inPlace;
private final MapperFacade mapperFacade;
private final UnenhanceStrategy unenhanceStrategy;
protected final ConcurrentHashMap<Class<?>, MappingStrategy> strategies = new ConcurrentHashMap<Class<?>, MappingStrategy>(2);
private volatile Class<?> idClass;
private volatile MappingStrategy defaultStrategy;
private BoundStrategyCache(Type<?> aType, Type<?> bType, MapperFacade mapperFacade, UnenhanceStrategy unenhanceStrategy, boolean inPlace) {
this.aType = aType;
this.bType = bType;
this.mapperFacade = mapperFacade;
this.unenhanceStrategy = unenhanceStrategy;
this.inPlace = inPlace;
}
public MappingStrategy getStrategy(Object sourceObject, MappingContext context) {
MappingStrategy strategy = null;
Class<?> sourceClass = getClass(sourceObject);
if (defaultStrategy != null && sourceClass.equals(idClass)) {
strategy = defaultStrategy;
} else if (defaultStrategy == null) {
synchronized(this) {
if (defaultStrategy == null) {
defaultStrategy = mapperFacade.resolveMappingStrategy(sourceObject, aType, bType, inPlace, context);
idClass = sourceClass;
strategies.put(idClass, defaultStrategy);
}
}
strategy = defaultStrategy;
} else {
strategy = strategies.get(sourceClass);
if (strategy == null) {
strategy = mapperFacade.resolveMappingStrategy(sourceObject, aType, bType, inPlace, context);
strategies.put(sourceClass, strategy);
}
}
/*
* Set the resolved types on the current mapping context; this can be used
* by downstream Mappers to determine the originally resolved types
*/
context.setResolvedSourceType(strategy.getSoureType());
context.setResolvedDestinationType(strategy.getDestinationType());
return strategy;
}
protected Class<?> getClass(Object object) {
if (this.unenhanceStrategy == null) {
return object.getClass();
} else {
return unenhanceStrategy.unenhanceObject(object, TypeFactory.TYPE_OF_OBJECT).getClass();
}
}
}
}
| Updated to account for change to MappingStrategy causing it to implement
MappedTypePair | core/src/main/java/ma/glasnost/orika/impl/DefaultBoundMapperFacade.java | Updated to account for change to MappingStrategy causing it to implement MappedTypePair | <ide><path>ore/src/main/java/ma/glasnost/orika/impl/DefaultBoundMapperFacade.java
<ide> * Set the resolved types on the current mapping context; this can be used
<ide> * by downstream Mappers to determine the originally resolved types
<ide> */
<del> context.setResolvedSourceType(strategy.getSoureType());
<del> context.setResolvedDestinationType(strategy.getDestinationType());
<add> context.setResolvedSourceType(strategy.getAType());
<add> context.setResolvedDestinationType(strategy.getBType());
<ide>
<ide> return strategy;
<ide> } |
|
Java | apache-2.0 | 814a157ba47f89f0b5939e99c1db817aa72883f3 | 0 | vishalzanzrukia/streamex,manikitos/streamex,amaembo/streamex | /*
* Copyright 2015 Tagir Valeev
*
* 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 javax.util.streamex;
import java.util.Spliterator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleConsumer;
import java.util.function.IntBinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.LongBinaryOperator;
import java.util.function.LongConsumer;
abstract class PairSpliterator<T, S extends Spliterator<T>, R> implements Spliterator<R> {
S source;
boolean hasLast, hasPrev;
public PairSpliterator(S source, boolean hasPrev, boolean hasLast) {
this.source = source;
this.hasLast = hasLast;
this.hasPrev = hasPrev;
}
@Override
public long estimateSize() {
long size = source.estimateSize();
if(size == Long.MAX_VALUE)
return size;
if(hasLast)
size++;
if(!hasPrev && size > 0)
size--;
return size;
}
@Override
public int characteristics() {
return NONNULL | (source.characteristics() & (SIZED | SUBSIZED | CONCURRENT | IMMUTABLE | ORDERED));
}
static class PSOfRef<T, R> extends PairSpliterator<T, Spliterator<T>, R> {
private T cur;
private final T last;
private final BiFunction<T, T, R> mapper;
public PSOfRef(BiFunction<T, T, R> mapper, Spliterator<T> source, T prev, boolean hasPrev, T last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(T t) {
cur = t;
}
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if(!hasPrev) {
if(!source.tryAdvance(this::setCur)) {
return false;
}
hasPrev = true;
}
T prev = cur;
if(!source.tryAdvance(this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.apply(prev, cur));
return true;
}
@Override
public Spliterator<R> trySplit() {
Spliterator<T> prefixSource = source.trySplit();
if(prefixSource == null)
return null;
T prev = cur;
if(!source.tryAdvance(this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfRef<>(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
static class PSOfInt extends PairSpliterator<Integer, Spliterator.OfInt, Integer> implements Spliterator.OfInt {
private int cur;
private final int last;
private final IntBinaryOperator mapper;
PSOfInt(IntBinaryOperator mapper, Spliterator.OfInt source, int prev, boolean hasPrev, int last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(int t) {
cur = t;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if(!hasPrev) {
if(!source.tryAdvance((IntConsumer)this::setCur)) {
return false;
}
hasPrev = true;
}
int prev = cur;
if(!source.tryAdvance((IntConsumer)this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.applyAsInt(prev, cur));
return true;
}
@Override
public Spliterator.OfInt trySplit() {
Spliterator.OfInt prefixSource = source.trySplit();
if(prefixSource == null)
return null;
int prev = cur;
if(!source.tryAdvance((IntConsumer)this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfInt(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
static class PSOfLong extends PairSpliterator<Long, Spliterator.OfLong, Long> implements Spliterator.OfLong {
private long cur;
private final long last;
private final LongBinaryOperator mapper;
PSOfLong(LongBinaryOperator mapper, Spliterator.OfLong source, long prev, boolean hasPrev, long last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(long t) {
cur = t;
}
@Override
public boolean tryAdvance(LongConsumer action) {
if(!hasPrev) {
if(!source.tryAdvance((LongConsumer)this::setCur)) {
return false;
}
hasPrev = true;
}
long prev = cur;
if(!source.tryAdvance((LongConsumer)this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.applyAsLong(prev, cur));
return true;
}
@Override
public Spliterator.OfLong trySplit() {
Spliterator.OfLong prefixSource = source.trySplit();
if(prefixSource == null)
return null;
long prev = cur;
if(!source.tryAdvance((LongConsumer)this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfLong(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
static class PSOfDouble extends PairSpliterator<Double, Spliterator.OfDouble, Double> implements Spliterator.OfDouble {
private double cur;
private final double last;
private final DoubleBinaryOperator mapper;
PSOfDouble(DoubleBinaryOperator mapper, Spliterator.OfDouble source, double prev, boolean hasPrev, double last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(double t) {
cur = t;
}
@Override
public boolean tryAdvance(DoubleConsumer action) {
if(!hasPrev) {
if(!source.tryAdvance((DoubleConsumer)this::setCur)) {
return false;
}
hasPrev = true;
}
double prev = cur;
if(!source.tryAdvance((DoubleConsumer)this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.applyAsDouble(prev, cur));
return true;
}
@Override
public Spliterator.OfDouble trySplit() {
Spliterator.OfDouble prefixSource = source.trySplit();
if(prefixSource == null)
return null;
double prev = cur;
if(!source.tryAdvance((DoubleConsumer)this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfDouble(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
}
| src/main/java/javax/util/streamex/PairSpliterator.java | /*
* Copyright 2015 Tagir Valeev
*
* 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 javax.util.streamex;
import java.util.Spliterator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleConsumer;
import java.util.function.IntBinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.LongBinaryOperator;
import java.util.function.LongConsumer;
abstract class PairSpliterator<T, S extends Spliterator<T>, R> implements Spliterator<R> {
S source;
boolean hasLast, hasPrev;
public PairSpliterator(S source, boolean hasPrev, boolean hasLast) {
this.source = source;
this.hasLast = hasLast;
this.hasPrev = hasPrev;
}
@Override
public long estimateSize() {
long size = source.estimateSize();
if(size == Long.MAX_VALUE)
return size;
if(hasLast)
size++;
if(!hasPrev && size > 0)
size--;
return size;
}
@Override
public int characteristics() {
return NONNULL | (source.characteristics() & (SIZED | SUBSIZED | CONCURRENT | DISTINCT | IMMUTABLE | ORDERED));
}
static class PSOfRef<T, R> extends PairSpliterator<T, Spliterator<T>, R> {
private T cur;
private final T last;
private final BiFunction<T, T, R> mapper;
public PSOfRef(BiFunction<T, T, R> mapper, Spliterator<T> source, T prev, boolean hasPrev, T last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(T t) {
cur = t;
}
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if(!hasPrev) {
if(!source.tryAdvance(this::setCur)) {
return false;
}
hasPrev = true;
}
T prev = cur;
if(!source.tryAdvance(this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.apply(prev, cur));
return true;
}
@Override
public Spliterator<R> trySplit() {
Spliterator<T> prefixSource = source.trySplit();
if(prefixSource == null)
return null;
T prev = cur;
if(!source.tryAdvance(this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfRef<>(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
static class PSOfInt extends PairSpliterator<Integer, Spliterator.OfInt, Integer> implements Spliterator.OfInt {
private int cur;
private final int last;
private final IntBinaryOperator mapper;
PSOfInt(IntBinaryOperator mapper, Spliterator.OfInt source, int prev, boolean hasPrev, int last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(int t) {
cur = t;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if(!hasPrev) {
if(!source.tryAdvance((IntConsumer)this::setCur)) {
return false;
}
hasPrev = true;
}
int prev = cur;
if(!source.tryAdvance((IntConsumer)this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.applyAsInt(prev, cur));
return true;
}
@Override
public Spliterator.OfInt trySplit() {
Spliterator.OfInt prefixSource = source.trySplit();
if(prefixSource == null)
return null;
int prev = cur;
if(!source.tryAdvance((IntConsumer)this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfInt(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
static class PSOfLong extends PairSpliterator<Long, Spliterator.OfLong, Long> implements Spliterator.OfLong {
private long cur;
private final long last;
private final LongBinaryOperator mapper;
PSOfLong(LongBinaryOperator mapper, Spliterator.OfLong source, long prev, boolean hasPrev, long last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(long t) {
cur = t;
}
@Override
public boolean tryAdvance(LongConsumer action) {
if(!hasPrev) {
if(!source.tryAdvance((LongConsumer)this::setCur)) {
return false;
}
hasPrev = true;
}
long prev = cur;
if(!source.tryAdvance((LongConsumer)this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.applyAsLong(prev, cur));
return true;
}
@Override
public Spliterator.OfLong trySplit() {
Spliterator.OfLong prefixSource = source.trySplit();
if(prefixSource == null)
return null;
long prev = cur;
if(!source.tryAdvance((LongConsumer)this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfLong(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
static class PSOfDouble extends PairSpliterator<Double, Spliterator.OfDouble, Double> implements Spliterator.OfDouble {
private double cur;
private final double last;
private final DoubleBinaryOperator mapper;
PSOfDouble(DoubleBinaryOperator mapper, Spliterator.OfDouble source, double prev, boolean hasPrev, double last, boolean hasLast) {
super(source, hasPrev, hasLast);
this.cur = prev;
this.last = last;
this.mapper = mapper;
}
void setCur(double t) {
cur = t;
}
@Override
public boolean tryAdvance(DoubleConsumer action) {
if(!hasPrev) {
if(!source.tryAdvance((DoubleConsumer)this::setCur)) {
return false;
}
hasPrev = true;
}
double prev = cur;
if(!source.tryAdvance((DoubleConsumer)this::setCur)) {
if(!hasLast)
return false;
hasLast = false;
cur = last;
}
action.accept(mapper.applyAsDouble(prev, cur));
return true;
}
@Override
public Spliterator.OfDouble trySplit() {
Spliterator.OfDouble prefixSource = source.trySplit();
if(prefixSource == null)
return null;
double prev = cur;
if(!source.tryAdvance((DoubleConsumer)this::setCur)) {
source = prefixSource;
return null;
}
boolean oldHasPrev = hasPrev;
hasPrev = true;
return new PSOfDouble(mapper, prefixSource, prev, oldHasPrev, cur, true);
}
}
}
| PairSpliterator: DISTINCT characteristic reset as it depends on mapping
function | src/main/java/javax/util/streamex/PairSpliterator.java | PairSpliterator: DISTINCT characteristic reset as it depends on mapping function | <ide><path>rc/main/java/javax/util/streamex/PairSpliterator.java
<ide>
<ide> @Override
<ide> public int characteristics() {
<del> return NONNULL | (source.characteristics() & (SIZED | SUBSIZED | CONCURRENT | DISTINCT | IMMUTABLE | ORDERED));
<add> return NONNULL | (source.characteristics() & (SIZED | SUBSIZED | CONCURRENT | IMMUTABLE | ORDERED));
<ide> }
<ide>
<ide> static class PSOfRef<T, R> extends PairSpliterator<T, Spliterator<T>, R> { |
|
Java | apache-2.0 | 326c2382b1dc990a64313a77bdec6a397386c065 | 0 | apache/velocity-engine,apache/velocity-engine | package org.apache.velocity.runtime.log;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* Base interface that Logging systems need to implement.
*
* @author <a href="mailto:[email protected]">Jon S. Stevens</a>
* @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a>
* @version $Id: LogSystem.java,v 1.2 2001/03/19 05:19:48 geirm Exp $
*/
public interface LogSystem
{
public final static boolean DEBUG_ON = true;
/**
* Prefix for debug messages.
*/
public final static int DEBUG_ID = 0;
/**
* Prefix for info messages.
*/
public final static int INFO_ID = 1;
/**
* Prefix for warning messages.
*/
public final static int WARN_ID = 2;
/**
* Prefix for error messages.
*/
public final static int ERROR_ID = 3;
public void logVelocityMessage( int level, String messsage);
}
| src/java/org/apache/velocity/runtime/log/LogSystem.java | package org.apache.velocity.runtime.log;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* Base interface that Logging systems need to implement.
*
* @author <a href="mailto:[email protected]">Jon S. Stevens</a>
* @version $Id: LogSystem.java,v 1.1 2001/03/12 07:19:53 jon Exp $
*/
public interface LogSystem
{
public final static boolean DEBUG_ON = true;
/**
* Prefix for warning messages.
*/
public final static String WARN = " [warn] ";
public final static int WARN_ID = 0;
/**
* Prefix for info messages.
*/
public final static String INFO = " [info] ";
public final static int INFO_ID = 1;
/**
* Prefix for debug messages.
*/
public final static String DEBUG = " [debug] ";
public final static int DEBUG_ID = 2;
/**
* Prefix for error messages.
*/
public final static String ERROR = " [error] ";
public final static int ERROR_ID = 3;
public void init(String logFile) throws Exception;
public void info (Object messsage);
public void error (Object messsage);
public void debug (Object messsage);
public void warn (Object messsage);
public void log (int type, Object messsage);
public boolean getStackTrace();
public void setStackTrace(boolean value);
} | Boiled the interface down to 1 method and 4 level constants. Rest was removed and pulled back
into Runtime or RuntimeConstants
PR:
Obtained from:
Submitted by:
Reviewed by:
git-svn-id: 7267684f36935cb3df12efc1f4c0216d758271d4@74551 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/velocity/runtime/log/LogSystem.java | Boiled the interface down to 1 method and 4 level constants. Rest was removed and pulled back into Runtime or RuntimeConstants PR: Obtained from: Submitted by: Reviewed by: | <ide><path>rc/java/org/apache/velocity/runtime/log/LogSystem.java
<ide> * Alternately, this acknowlegement may appear in the software itself,
<ide> * if and wherever such third-party acknowlegements normally appear.
<ide> *
<del> * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
<add> * 4. The names "The Jakarta Project", "Velocity", and "Apache Software
<ide> * Foundation" must not be used to endorse or promote products derived
<ide> * from this software without prior written permission. For written
<ide> * permission, please contact [email protected].
<ide> * Base interface that Logging systems need to implement.
<ide> *
<ide> * @author <a href="mailto:[email protected]">Jon S. Stevens</a>
<del> * @version $Id: LogSystem.java,v 1.1 2001/03/12 07:19:53 jon Exp $
<add> * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a>
<add> * @version $Id: LogSystem.java,v 1.2 2001/03/19 05:19:48 geirm Exp $
<ide> */
<ide> public interface LogSystem
<ide> {
<ide> public final static boolean DEBUG_ON = true;
<ide>
<del> /**
<del> * Prefix for warning messages.
<add> /**
<add> * Prefix for debug messages.
<ide> */
<del> public final static String WARN = " [warn] ";
<del> public final static int WARN_ID = 0;
<add> public final static int DEBUG_ID = 0;
<ide>
<ide> /**
<ide> * Prefix for info messages.
<ide> */
<del> public final static String INFO = " [info] ";
<ide> public final static int INFO_ID = 1;
<ide>
<ide> /**
<del> * Prefix for debug messages.
<add> * Prefix for warning messages.
<ide> */
<del> public final static String DEBUG = " [debug] ";
<del> public final static int DEBUG_ID = 2;
<del>
<add> public final static int WARN_ID = 2;
<add>
<ide> /**
<ide> * Prefix for error messages.
<ide> */
<del> public final static String ERROR = " [error] ";
<ide> public final static int ERROR_ID = 3;
<add>
<add> public void logVelocityMessage( int level, String messsage);
<add>
<add>}
<ide>
<del> public void init(String logFile) throws Exception;
<del>
<del> public void info (Object messsage);
<del> public void error (Object messsage);
<del> public void debug (Object messsage);
<del> public void warn (Object messsage);
<del> public void log (int type, Object messsage);
<del>
<del> public boolean getStackTrace();
<del> public void setStackTrace(boolean value);
<del>} |
|
Java | apache-2.0 | 01c529cb77008c693350664e076c2ff27e075378 | 0 | wisgood/hive,WANdisco/amplab-hive,asonipsl/hive,wisgood/hive,WANdisco/hive,winningsix/hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/amplab-hive,WANdisco/amplab-hive,wisgood/hive,asonipsl/hive,winningsix/hive,winningsix/hive,asonipsl/hive,wisgood/hive,WANdisco/hive,WANdisco/amplab-hive,winningsix/hive,WANdisco/hive,winningsix/hive,WANdisco/hive,WANdisco/hive,wisgood/hive,WANdisco/hive,WANdisco/amplab-hive,wisgood/hive,WANdisco/amplab-hive,winningsix/hive,asonipsl/hive,winningsix/hive,wisgood/hive,WANdisco/amplab-hive,winningsix/hive,wisgood/hive,asonipsl/hive,asonipsl/hive,asonipsl/hive,WANdisco/hive,asonipsl/hive | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.parse;
import org.antlr.runtime.tree.Tree;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.plan.LoadTableDesc;
import org.apache.hadoop.hive.ql.plan.MoveWork;
import org.apache.hadoop.hive.ql.plan.StatsWork;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* LoadSemanticAnalyzer.
*
*/
public class LoadSemanticAnalyzer extends BaseSemanticAnalyzer {
private boolean isLocal;
private boolean isOverWrite;
public LoadSemanticAnalyzer(HiveConf conf) throws SemanticException {
super(conf);
}
public static FileStatus[] matchFilesOrDir(FileSystem fs, Path path)
throws IOException {
FileStatus[] srcs = fs.globStatus(path, new PathFilter() {
@Override
public boolean accept(Path p) {
String name = p.getName();
return name.equals("_metadata") ? true : !name.startsWith("_") && !name.startsWith(".");
}
});
if ((srcs != null) && srcs.length == 1) {
if (srcs[0].isDir()) {
srcs = fs.listStatus(srcs[0].getPath(), new PathFilter() {
@Override
public boolean accept(Path p) {
String name = p.getName();
return !name.startsWith("_") && !name.startsWith(".");
}
});
}
}
return (srcs);
}
private URI initializeFromURI(String fromPath) throws IOException,
URISyntaxException {
URI fromURI = new Path(fromPath).toUri();
String fromScheme = fromURI.getScheme();
String fromAuthority = fromURI.getAuthority();
String path = fromURI.getPath();
// generate absolute path relative to current directory or hdfs home
// directory
if (!path.startsWith("/")) {
if (isLocal) {
path = URIUtil.decode(
new Path(System.getProperty("user.dir"), fromPath).toUri().toString());
} else {
path = new Path(new Path("/user/" + System.getProperty("user.name")),
path).toString();
}
}
// set correct scheme and authority
if (StringUtils.isEmpty(fromScheme)) {
if (isLocal) {
// file for local
fromScheme = "file";
} else {
// use default values from fs.default.name
URI defaultURI = FileSystem.get(conf).getUri();
fromScheme = defaultURI.getScheme();
fromAuthority = defaultURI.getAuthority();
}
}
// if scheme is specified but not authority then use the default authority
if ((!fromScheme.equals("file")) && StringUtils.isEmpty(fromAuthority)) {
URI defaultURI = FileSystem.get(conf).getUri();
fromAuthority = defaultURI.getAuthority();
}
LOG.debug(fromScheme + "@" + fromAuthority + "@" + path);
return new URI(fromScheme, fromAuthority, path, null, null);
}
private void applyConstraints(URI fromURI, URI toURI, Tree ast,
boolean isLocal) throws SemanticException {
// local mode implies that scheme should be "file"
// we can change this going forward
if (isLocal && !fromURI.getScheme().equals("file")) {
throw new SemanticException(ErrorMsg.ILLEGAL_PATH.getMsg(ast,
"Source file system should be \"file\" if \"local\" is specified"));
}
try {
FileStatus[] srcs = matchFilesOrDir(FileSystem.get(fromURI, conf), new Path(fromURI));
if (srcs == null || srcs.length == 0) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(ast,
"No files matching path " + fromURI));
}
for (FileStatus oneSrc : srcs) {
if (oneSrc.isDir()) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(ast,
"source contains directory: " + oneSrc.getPath().toString()));
}
}
} catch (IOException e) {
// Has to use full name to make sure it does not conflict with
// org.apache.commons.lang.StringUtils
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(ast), e);
}
// only in 'local' mode do we copy stuff from one place to another.
// reject different scheme/authority in other cases.
if (!isLocal
&& (!StringUtils.equals(fromURI.getScheme(), toURI.getScheme()) || !StringUtils
.equals(fromURI.getAuthority(), toURI.getAuthority()))) {
String reason = "Move from: " + fromURI.toString() + " to: "
+ toURI.toString() + " is not valid. "
+ "Please check that values for params \"default.fs.name\" and "
+ "\"hive.metastore.warehouse.dir\" do not conflict.";
throw new SemanticException(ErrorMsg.ILLEGAL_PATH.getMsg(ast, reason));
}
}
@Override
public void analyzeInternal(ASTNode ast) throws SemanticException {
isLocal = false;
isOverWrite = false;
Tree fromTree = ast.getChild(0);
Tree tableTree = ast.getChild(1);
if (ast.getChildCount() == 4) {
isLocal = true;
isOverWrite = true;
}
if (ast.getChildCount() == 3) {
if (ast.getChild(2).getText().toLowerCase().equals("local")) {
isLocal = true;
} else {
isOverWrite = true;
}
}
// initialize load path
URI fromURI;
try {
String fromPath = stripQuotes(fromTree.getText());
fromURI = initializeFromURI(fromPath);
} catch (IOException e) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(fromTree, e
.getMessage()), e);
} catch (URISyntaxException e) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(fromTree, e
.getMessage()), e);
}
// initialize destination table/partition
tableSpec ts = new tableSpec(db, conf, (ASTNode) tableTree);
if (ts.tableHandle.isOffline()){
throw new SemanticException(
ErrorMsg.OFFLINE_TABLE_OR_PARTITION.getMsg(":Table " + ts.tableName));
}
if (ts.tableHandle.isView()) {
throw new SemanticException(ErrorMsg.DML_AGAINST_VIEW.getMsg());
}
if (ts.tableHandle.isNonNative()) {
throw new SemanticException(ErrorMsg.LOAD_INTO_NON_NATIVE.getMsg());
}
if(ts.tableHandle.isStoredAsSubDirectories()) {
throw new SemanticException(ErrorMsg.LOAD_INTO_STORED_AS_DIR.getMsg());
}
URI toURI = ((ts.partHandle != null) ? ts.partHandle.getDataLocation()
: ts.tableHandle.getDataLocation()).toUri();
List<FieldSchema> parts = ts.tableHandle.getPartitionKeys();
if ((parts != null && parts.size() > 0)
&& (ts.partSpec == null || ts.partSpec.size() == 0)) {
throw new SemanticException(ErrorMsg.NEED_PARTITION_ERROR.getMsg());
}
// make sure the arguments make sense
applyConstraints(fromURI, toURI, fromTree, isLocal);
inputs.add(new ReadEntity(new Path(fromURI), isLocal));
Task<? extends Serializable> rTask = null;
// create final load/move work
boolean preservePartitionSpecs = false;
Map<String, String> partSpec = ts.getPartSpec();
if (partSpec == null) {
partSpec = new LinkedHashMap<String, String>();
outputs.add(new WriteEntity(ts.tableHandle,
(isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
WriteEntity.WriteType.INSERT)));
} else {
try{
Partition part = Hive.get().getPartition(ts.tableHandle, partSpec, false);
if (part != null) {
if (part.isOffline()) {
throw new SemanticException(ErrorMsg.OFFLINE_TABLE_OR_PARTITION.
getMsg(ts.tableName + ":" + part.getName()));
}
if (isOverWrite){
outputs.add(new WriteEntity(part, WriteEntity.WriteType.INSERT_OVERWRITE));
} else {
outputs.add(new WriteEntity(part, WriteEntity.WriteType.INSERT));
// If partition already exists and we aren't overwriting it, then respect
// its current location info rather than picking it from the parent TableDesc
preservePartitionSpecs = true;
}
} else {
outputs.add(new WriteEntity(ts.tableHandle,
(isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
WriteEntity.WriteType.INSERT)));
}
} catch(HiveException e) {
throw new SemanticException(e);
}
}
LoadTableDesc loadTableWork;
loadTableWork = new LoadTableDesc(new Path(fromURI),
Utilities.getTableDesc(ts.tableHandle), partSpec, isOverWrite);
if (preservePartitionSpecs){
// Note : preservePartitionSpecs=true implies inheritTableSpecs=false but
// but preservePartitionSpecs=false(default) here is not sufficient enough
// info to set inheritTableSpecs=true
loadTableWork.setInheritTableSpecs(false);
}
Task<? extends Serializable> childTask = TaskFactory.get(new MoveWork(getInputs(),
getOutputs(), loadTableWork, null, true, isLocal), conf);
if (rTask != null) {
rTask.addDependentTask(childTask);
} else {
rTask = childTask;
}
rootTasks.add(rTask);
// The user asked for stats to be collected.
// Some stats like number of rows require a scan of the data
// However, some other stats, like number of files, do not require a complete scan
// Update the stats which do not require a complete scan.
Task<? extends Serializable> statTask = null;
if (conf.getBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER)) {
StatsWork statDesc = new StatsWork(loadTableWork);
statDesc.setNoStatsAggregator(true);
statDesc.setClearAggregatorStats(true);
statDesc.setStatsReliable(conf.getBoolVar(HiveConf.ConfVars.HIVE_STATS_RELIABLE));
statTask = TaskFactory.get(statDesc, conf);
}
// HIVE-3334 has been filed for load file with index auto update
if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVEINDEXAUTOUPDATE)) {
IndexUpdater indexUpdater = new IndexUpdater(loadTableWork, getInputs(), conf);
try {
List<Task<? extends Serializable>> indexUpdateTasks = indexUpdater.generateUpdateTasks();
for (Task<? extends Serializable> updateTask : indexUpdateTasks) {
//LOAD DATA will either have a copy & move or just a move,
// we always want the update to be dependent on the move
childTask.addDependentTask(updateTask);
if (statTask != null) {
updateTask.addDependentTask(statTask);
}
}
} catch (HiveException e) {
console.printInfo("WARNING: could not auto-update stale indexes, indexes are not out of sync");
}
}
else if (statTask != null) {
childTask.addDependentTask(statTask);
}
}
}
| ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.parse;
import org.antlr.runtime.tree.Tree;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.plan.LoadTableDesc;
import org.apache.hadoop.hive.ql.plan.MoveWork;
import org.apache.hadoop.hive.ql.plan.StatsWork;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* LoadSemanticAnalyzer.
*
*/
public class LoadSemanticAnalyzer extends BaseSemanticAnalyzer {
private boolean isLocal;
private boolean isOverWrite;
public LoadSemanticAnalyzer(HiveConf conf) throws SemanticException {
super(conf);
}
public static FileStatus[] matchFilesOrDir(FileSystem fs, Path path)
throws IOException {
FileStatus[] srcs = fs.globStatus(path, new PathFilter() {
@Override
public boolean accept(Path p) {
String name = p.getName();
return name.equals("_metadata") ? true : !name.startsWith("_") && !name.startsWith(".");
}
});
if ((srcs != null) && srcs.length == 1) {
if (srcs[0].isDir()) {
srcs = fs.listStatus(srcs[0].getPath(), new PathFilter() {
@Override
public boolean accept(Path p) {
String name = p.getName();
return !name.startsWith("_") && !name.startsWith(".");
}
});
}
}
return (srcs);
}
private URI initializeFromURI(String fromPath) throws IOException,
URISyntaxException {
URI fromURI = new Path(fromPath).toUri();
String fromScheme = fromURI.getScheme();
String fromAuthority = fromURI.getAuthority();
String path = fromURI.getPath();
// generate absolute path relative to current directory or hdfs home
// directory
if (!path.startsWith("/")) {
if (isLocal) {
path = URIUtil.decode(
new Path(System.getProperty("user.dir"), fromPath).toUri().toString());
} else {
path = new Path(new Path("/user/" + System.getProperty("user.name")),
path).toString();
}
}
// set correct scheme and authority
if (StringUtils.isEmpty(fromScheme)) {
if (isLocal) {
// file for local
fromScheme = "file";
} else {
// use default values from fs.default.name
URI defaultURI = FileSystem.get(conf).getUri();
fromScheme = defaultURI.getScheme();
fromAuthority = defaultURI.getAuthority();
}
}
// if scheme is specified but not authority then use the default authority
if ((!fromScheme.equals("file")) && StringUtils.isEmpty(fromAuthority)) {
URI defaultURI = FileSystem.get(conf).getUri();
fromAuthority = defaultURI.getAuthority();
}
LOG.debug(fromScheme + "@" + fromAuthority + "@" + path);
return new URI(fromScheme, fromAuthority, path, null, null);
}
private void applyConstraints(URI fromURI, URI toURI, Tree ast,
boolean isLocal) throws SemanticException {
// local mode implies that scheme should be "file"
// we can change this going forward
if (isLocal && !fromURI.getScheme().equals("file")) {
throw new SemanticException(ErrorMsg.ILLEGAL_PATH.getMsg(ast,
"Source file system should be \"file\" if \"local\" is specified"));
}
try {
FileStatus[] srcs = matchFilesOrDir(FileSystem.get(fromURI, conf), new Path(fromURI));
if (srcs == null || srcs.length == 0) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(ast,
"No files matching path " + fromURI));
}
for (FileStatus oneSrc : srcs) {
if (oneSrc.isDir()) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(ast,
"source contains directory: " + oneSrc.getPath().toString()));
}
}
} catch (IOException e) {
// Has to use full name to make sure it does not conflict with
// org.apache.commons.lang.StringUtils
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(ast), e);
}
// only in 'local' mode do we copy stuff from one place to another.
// reject different scheme/authority in other cases.
if (!isLocal
&& (!StringUtils.equals(fromURI.getScheme(), toURI.getScheme()) || !StringUtils
.equals(fromURI.getAuthority(), toURI.getAuthority()))) {
String reason = "Move from: " + fromURI.toString() + " to: "
+ toURI.toString() + " is not valid. "
+ "Please check that values for params \"default.fs.name\" and "
+ "\"hive.metastore.warehouse.dir\" do not conflict.";
throw new SemanticException(ErrorMsg.ILLEGAL_PATH.getMsg(ast, reason));
}
}
@Override
public void analyzeInternal(ASTNode ast) throws SemanticException {
isLocal = false;
isOverWrite = false;
Tree fromTree = ast.getChild(0);
Tree tableTree = ast.getChild(1);
if (ast.getChildCount() == 4) {
isLocal = true;
isOverWrite = true;
}
if (ast.getChildCount() == 3) {
if (ast.getChild(2).getText().toLowerCase().equals("local")) {
isLocal = true;
} else {
isOverWrite = true;
}
}
// initialize load path
URI fromURI;
try {
String fromPath = stripQuotes(fromTree.getText());
fromURI = initializeFromURI(fromPath);
} catch (IOException e) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(fromTree, e
.getMessage()), e);
} catch (URISyntaxException e) {
throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(fromTree, e
.getMessage()), e);
}
// initialize destination table/partition
tableSpec ts = new tableSpec(db, conf, (ASTNode) tableTree);
if (ts.tableHandle.isOffline()){
throw new SemanticException(
ErrorMsg.OFFLINE_TABLE_OR_PARTITION.getMsg(":Table " + ts.tableName));
}
if (ts.tableHandle.isView()) {
throw new SemanticException(ErrorMsg.DML_AGAINST_VIEW.getMsg());
}
if (ts.tableHandle.isNonNative()) {
throw new SemanticException(ErrorMsg.LOAD_INTO_NON_NATIVE.getMsg());
}
if(ts.tableHandle.isStoredAsSubDirectories()) {
throw new SemanticException(ErrorMsg.LOAD_INTO_STORED_AS_DIR.getMsg());
}
URI toURI = ((ts.partHandle != null) ? ts.partHandle.getDataLocation()
: ts.tableHandle.getDataLocation()).toUri();
List<FieldSchema> parts = ts.tableHandle.getPartitionKeys();
if ((parts != null && parts.size() > 0)
&& (ts.partSpec == null || ts.partSpec.size() == 0)) {
throw new SemanticException(ErrorMsg.NEED_PARTITION_ERROR.getMsg());
}
// make sure the arguments make sense
applyConstraints(fromURI, toURI, fromTree, isLocal);
inputs.add(new ReadEntity(new Path(fromURI), isLocal));
Task<? extends Serializable> rTask = null;
// create final load/move work
Map<String, String> partSpec = ts.getPartSpec();
if (partSpec == null) {
partSpec = new LinkedHashMap<String, String>();
outputs.add(new WriteEntity(ts.tableHandle,
(isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
WriteEntity.WriteType.INSERT)));
} else {
try{
Partition part = Hive.get().getPartition(ts.tableHandle, partSpec, false);
if (part != null) {
if (part.isOffline()) {
throw new SemanticException(ErrorMsg.OFFLINE_TABLE_OR_PARTITION.
getMsg(ts.tableName + ":" + part.getName()));
}
outputs.add(new WriteEntity(part,
(isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
WriteEntity.WriteType.INSERT)));
} else {
outputs.add(new WriteEntity(ts.tableHandle,
(isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
WriteEntity.WriteType.INSERT)));
}
} catch(HiveException e) {
throw new SemanticException(e);
}
}
LoadTableDesc loadTableWork;
loadTableWork = new LoadTableDesc(new Path(fromURI),
Utilities.getTableDesc(ts.tableHandle), partSpec, isOverWrite);
Task<? extends Serializable> childTask = TaskFactory.get(new MoveWork(getInputs(),
getOutputs(), loadTableWork, null, true, isLocal), conf);
if (rTask != null) {
rTask.addDependentTask(childTask);
} else {
rTask = childTask;
}
rootTasks.add(rTask);
// The user asked for stats to be collected.
// Some stats like number of rows require a scan of the data
// However, some other stats, like number of files, do not require a complete scan
// Update the stats which do not require a complete scan.
Task<? extends Serializable> statTask = null;
if (conf.getBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER)) {
StatsWork statDesc = new StatsWork(loadTableWork);
statDesc.setNoStatsAggregator(true);
statDesc.setClearAggregatorStats(true);
statDesc.setStatsReliable(conf.getBoolVar(HiveConf.ConfVars.HIVE_STATS_RELIABLE));
statTask = TaskFactory.get(statDesc, conf);
}
// HIVE-3334 has been filed for load file with index auto update
if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVEINDEXAUTOUPDATE)) {
IndexUpdater indexUpdater = new IndexUpdater(loadTableWork, getInputs(), conf);
try {
List<Task<? extends Serializable>> indexUpdateTasks = indexUpdater.generateUpdateTasks();
for (Task<? extends Serializable> updateTask : indexUpdateTasks) {
//LOAD DATA will either have a copy & move or just a move,
// we always want the update to be dependent on the move
childTask.addDependentTask(updateTask);
if (statTask != null) {
updateTask.addDependentTask(statTask);
}
}
} catch (HiveException e) {
console.printInfo("WARNING: could not auto-update stale indexes, indexes are not out of sync");
}
}
else if (statTask != null) {
childTask.addDependentTask(statTask);
}
}
}
| HIVE-8719 : LoadSemanticAnalyzer ignores previous partition location if inserting into partition that already exists (Sushanth Sowmyan, reviewed by Alan Gates)
git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1636813 13f79535-47bb-0310-9956-ffa450edef68
| ql/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java | HIVE-8719 : LoadSemanticAnalyzer ignores previous partition location if inserting into partition that already exists (Sushanth Sowmyan, reviewed by Alan Gates) | <ide><path>l/src/java/org/apache/hadoop/hive/ql/parse/LoadSemanticAnalyzer.java
<ide>
<ide> // create final load/move work
<ide>
<add> boolean preservePartitionSpecs = false;
<add>
<ide> Map<String, String> partSpec = ts.getPartSpec();
<ide> if (partSpec == null) {
<ide> partSpec = new LinkedHashMap<String, String>();
<ide> throw new SemanticException(ErrorMsg.OFFLINE_TABLE_OR_PARTITION.
<ide> getMsg(ts.tableName + ":" + part.getName()));
<ide> }
<del> outputs.add(new WriteEntity(part,
<del> (isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
<del> WriteEntity.WriteType.INSERT)));
<add> if (isOverWrite){
<add> outputs.add(new WriteEntity(part, WriteEntity.WriteType.INSERT_OVERWRITE));
<add> } else {
<add> outputs.add(new WriteEntity(part, WriteEntity.WriteType.INSERT));
<add> // If partition already exists and we aren't overwriting it, then respect
<add> // its current location info rather than picking it from the parent TableDesc
<add> preservePartitionSpecs = true;
<add> }
<ide> } else {
<ide> outputs.add(new WriteEntity(ts.tableHandle,
<ide> (isOverWrite ? WriteEntity.WriteType.INSERT_OVERWRITE :
<ide> LoadTableDesc loadTableWork;
<ide> loadTableWork = new LoadTableDesc(new Path(fromURI),
<ide> Utilities.getTableDesc(ts.tableHandle), partSpec, isOverWrite);
<add> if (preservePartitionSpecs){
<add> // Note : preservePartitionSpecs=true implies inheritTableSpecs=false but
<add> // but preservePartitionSpecs=false(default) here is not sufficient enough
<add> // info to set inheritTableSpecs=true
<add> loadTableWork.setInheritTableSpecs(false);
<add> }
<ide>
<ide> Task<? extends Serializable> childTask = TaskFactory.get(new MoveWork(getInputs(),
<ide> getOutputs(), loadTableWork, null, true, isLocal), conf); |
|
JavaScript | agpl-3.0 | aac3a980732cabe12a75256493ef9514d8daf9a9 | 0 | blueoceanideas/metabase,blueoceanideas/metabase,blueoceanideas/metabase,blueoceanideas/metabase,blueoceanideas/metabase | import d3 from "d3";
import inflection from "inflection";
import moment from "moment";
import React from "react";
import { isDate } from "metabase/lib/schema_metadata";
const PRECISION_NUMBER_FORMATTER = d3.format(".2r");
const FIXED_NUMBER_FORMATTER = d3.format(",.f");
const FIXED_NUMBER_FORMATTER_NO_COMMA = d3.format(".f");
const DECIMAL_DEGREES_FORMATTER = d3.format(".08f");
export function formatNumber(number, options) {
options = { comma: true, ...options}
if (number > -1 && number < 1) {
// numbers between 1 and -1 round to 2 significant digits with extra 0s stripped off
return PRECISION_NUMBER_FORMATTER(number).replace(/\.?0+$/, "");
} else {
// anything else rounds to at most 2 decimal points
if (options.comma) {
return FIXED_NUMBER_FORMATTER(d3.round(number, 2));
} else {
return FIXED_NUMBER_FORMATTER_NO_COMMA(d3.round(number, 2));
}
}
}
export function formatScalar(scalar) {
if (typeof scalar === "number") {
return formatNumber(scalar, { comma: true });
} else {
return String(scalar);
}
}
function formatMajorMinor(major, minor, options = {}) {
options = { jsx: false, majorWidth: 3, ...options };
if (options.jsx) {
return (
<span>
<span style={{ minWidth: options.majorWidth + "em" }} className="inline-block text-right text-bold">{major}</span>
{" - "}
<span>{minor}</span>
</span>
);
} else {
return `${major} - ${minor}`;
}
}
export function formatTimeWithUnit(value, unit, options = {}) {
let m = moment.parseZone(value);
if (options.utcOffset != null) {
m.utcOffset(options.utcOffset);
}
switch (unit) {
case "hour": // 12 AM - January 1, 2015
return formatMajorMinor(m.format("h A"), m.format("MMMM D, YYYY"), options);
case "day": // January 1, 2015
return m.format("MMMM D, YYYY");
case "week": // 1st - 2015
// force 'en' locale for now since our weeks currently always start on Sundays
m = m.locale("en");
return formatMajorMinor(m.format("wo"), m.format("gggg"), options);
case "month": // January 2015
return options.jsx ?
<div><span className="text-bold">{m.format("MMMM")}</span> {m.format("YYYY")}</div> :
m.format("MMMM") + " " + m.format("YYYY");
case "year": // 2015
return String(value);
case "quarter": // Q1 - 2015
return formatMajorMinor(m.format("[Q]Q"), m.format("YYYY"), { ...options, majorWidth: 0 });
case "hour-of-day": // 12 AM
return moment().hour(value).format("h A");
case "day-of-week": // Sunday
return moment().day(value - 1).format("dddd");
case "week-of-year": // 1st
return moment().week(value).format("wo");
case "month-of-year": // January
return moment().month(value - 1).format("MMMM");
}
return String(value);
}
export function formatValue(value, column, options = {}) {
options = { jsx: false, ...options };
if (value == undefined) {
return null
} else if (column && column.unit != null) {
return formatTimeWithUnit(value, column.unit, options);
} else if (isDate(column) || moment.isDate(value) || moment.isMoment(value) || moment(value, ["YYYY-MM-DD'T'HH:mm:ss.SSSZ"], true).isValid()) {
return moment.parseZone(value).format("LLLL");
} else if (typeof value === "string") {
return value;
} else if (typeof value === "number") {
if (column && (column.special_type === "latitude" || column.special_type === "longitude")) {
return DECIMAL_DEGREES_FORMATTER(value)
} else {
// don't show comma unless it's a number special_type (and eventually currency, etc)
let comma = column && column.special_type === "number";
return formatNumber(value, { comma, ...options });
}
} else if (typeof value === "object") {
// no extra whitespace for table cells
return JSON.stringify(value);
} else {
return String(value);
}
}
export function singularize(...args) {
return inflection.singularize(...args);
}
export function pluralize(...args) {
return inflection.pluralize(...args);
}
export function capitalize(...args) {
return inflection.capitalize(...args);
}
export function inflect(...args) {
return inflection.inflect(...args);
}
export function titleize(...args) {
return inflection.titleize(...args);
}
export function humanize(...args) {
return inflection.humanize(...args);
}
// Removes trailing "id" from field names
export function stripId(name) {
return name && name.replace(/ id$/i, "");
}
export function assignUserColors(userIds, currentUserId, colorClasses = ['bg-brand', 'bg-purple', 'bg-error', 'bg-green', 'bg-gold', 'bg-grey-2']) {
let assignments = {};
const currentUserColor = colorClasses[0];
const otherUserColors = colorClasses.slice(1);
let otherUserColorIndex = 0;
for (let userId of userIds) {
if (!(userId in assignments)) {
if (userId === currentUserId) {
assignments[userId] = currentUserColor;
} else if (userId != null) {
assignments[userId] = otherUserColors[otherUserColorIndex++ % otherUserColors.length];
}
}
}
return assignments;
}
| frontend/src/lib/formatting.js | import d3 from "d3";
import inflection from "inflection";
import moment from "moment";
import React from "react";
const PRECISION_NUMBER_FORMATTER = d3.format(".2r");
const FIXED_NUMBER_FORMATTER = d3.format(",.f");
const FIXED_NUMBER_FORMATTER_NO_COMMA = d3.format(".f");
const DECIMAL_DEGREES_FORMATTER = d3.format(".08f");
export function formatNumber(number, options) {
options = { comma: true, ...options}
if (number > -1 && number < 1) {
// numbers between 1 and -1 round to 2 significant digits with extra 0s stripped off
return PRECISION_NUMBER_FORMATTER(number).replace(/\.?0+$/, "");
} else {
// anything else rounds to at most 2 decimal points
if (options.comma) {
return FIXED_NUMBER_FORMATTER(d3.round(number, 2));
} else {
return FIXED_NUMBER_FORMATTER_NO_COMMA(d3.round(number, 2));
}
}
}
export function formatScalar(scalar) {
if (typeof scalar === "number") {
return formatNumber(scalar, { comma: true });
} else {
return String(scalar);
}
}
function formatMajorMinor(major, minor, options = {}) {
options = { jsx: false, majorWidth: 3, ...options };
if (options.jsx) {
return (
<span>
<span style={{ minWidth: options.majorWidth + "em" }} className="inline-block text-right text-bold">{major}</span>
{" - "}
<span>{minor}</span>
</span>
);
} else {
return `${major} - ${minor}`;
}
}
export function formatTimeWithUnit(value, unit, options = {}) {
let m = moment.parseZone(value);
if (options.utcOffset != null) {
m.utcOffset(options.utcOffset);
}
switch (unit) {
case "hour": // 12 AM - January 1, 2015
return formatMajorMinor(m.format("h A"), m.format("MMMM D, YYYY"), options);
case "day": // January 1, 2015
return m.format("MMMM D, YYYY");
case "week": // 1st - 2015
// force 'en' locale for now since our weeks currently always start on Sundays
m = m.locale("en");
return formatMajorMinor(m.format("wo"), m.format("gggg"), options);
case "month": // January 2015
return options.jsx ?
<div><span className="text-bold">{m.format("MMMM")}</span> {m.format("YYYY")}</div> :
m.format("MMMM") + " " + m.format("YYYY");
case "year": // 2015
return String(value);
case "quarter": // Q1 - 2015
return formatMajorMinor(m.format("[Q]Q"), m.format("YYYY"), { ...options, majorWidth: 0 });
case "hour-of-day": // 12 AM
return moment().hour(value).format("h A");
case "day-of-week": // Sunday
return moment().day(value - 1).format("dddd");
case "week-of-year": // 1st
return moment().week(value).format("wo");
case "month-of-year": // January
return moment().month(value - 1).format("MMMM");
}
return String(value);
}
export function formatValue(value, column, options = {}) {
options = { jsx: false, ...options };
if (value == undefined) {
return null
} else if (column && column.unit != null) {
return formatTimeWithUnit(value, column.unit, options);
} else if (moment.isDate(value) || moment.isMoment(value) || moment(value, ["YYYY-MM-DD'T'HH:mm:ss.SSSZ"]).isValid()) {
return moment.parseZone(value).format("LLLL");
} else if (typeof value === "string") {
return value;
} else if (typeof value === "number") {
if (column && (column.special_type === "latitude" || column.special_type === "longitude")) {
return DECIMAL_DEGREES_FORMATTER(value)
} else {
// don't show comma unless it's a number special_type (and eventually currency, etc)
let comma = column && column.special_type === "number";
return formatNumber(value, { comma, ...options });
}
} else if (typeof value === "object") {
// no extra whitespace for table cells
return JSON.stringify(value);
} else {
return String(value);
}
}
export function singularize(...args) {
return inflection.singularize(...args);
}
export function pluralize(...args) {
return inflection.pluralize(...args);
}
export function capitalize(...args) {
return inflection.capitalize(...args);
}
export function inflect(...args) {
return inflection.inflect(...args);
}
export function titleize(...args) {
return inflection.titleize(...args);
}
export function humanize(...args) {
return inflection.humanize(...args);
}
// Removes trailing "id" from field names
export function stripId(name) {
return name && name.replace(/ id$/i, "");
}
export function assignUserColors(userIds, currentUserId, colorClasses = ['bg-brand', 'bg-purple', 'bg-error', 'bg-green', 'bg-gold', 'bg-grey-2']) {
let assignments = {};
const currentUserColor = colorClasses[0];
const otherUserColors = colorClasses.slice(1);
let otherUserColorIndex = 0;
for (let userId of userIds) {
if (!(userId in assignments)) {
if (userId === currentUserId) {
assignments[userId] = currentUserColor;
} else if (userId != null) {
assignments[userId] = otherUserColors[otherUserColorIndex++ % otherUserColors.length];
}
}
}
return assignments;
}
| we have the column metadata to tell us if the column is a date, so lets use it.
| frontend/src/lib/formatting.js | we have the column metadata to tell us if the column is a date, so lets use it. | <ide><path>rontend/src/lib/formatting.js
<ide> import inflection from "inflection";
<ide> import moment from "moment";
<ide> import React from "react";
<add>
<add>import { isDate } from "metabase/lib/schema_metadata";
<ide>
<ide> const PRECISION_NUMBER_FORMATTER = d3.format(".2r");
<ide> const FIXED_NUMBER_FORMATTER = d3.format(",.f");
<ide> return null
<ide> } else if (column && column.unit != null) {
<ide> return formatTimeWithUnit(value, column.unit, options);
<del> } else if (moment.isDate(value) || moment.isMoment(value) || moment(value, ["YYYY-MM-DD'T'HH:mm:ss.SSSZ"]).isValid()) {
<add> } else if (isDate(column) || moment.isDate(value) || moment.isMoment(value) || moment(value, ["YYYY-MM-DD'T'HH:mm:ss.SSSZ"], true).isValid()) {
<ide> return moment.parseZone(value).format("LLLL");
<ide> } else if (typeof value === "string") {
<ide> return value; |
|
Java | mit | c8c6c833e688ecbc19487f7ece014e812467d879 | 0 | simple-elf/selenide,simple-elf/selenide,codeborne/selenide,codeborne/selenide,simple-elf/selenide,codeborne/selenide,simple-elf/selenide | package integration;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ex.ElementNotFound;
import com.codeborne.selenide.ex.ElementShouldNot;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.InvalidSelectorException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import static com.codeborne.selenide.Condition.*;
import static com.codeborne.selenide.Configuration.baseUrl;
import static com.codeborne.selenide.Selectors.*;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.WebDriverRunner.*;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
public class SelenideMethodsTest extends IntegrationTest {
@Before
public void openTestPageWithJQuery() {
openFile("page_with_selects_without_jquery.html");
}
@Test
public void userCanCheckIfElementExists() {
assertTrue($(By.name("domain")).exists());
assertTrue($("#theHiddenElement").exists());
assertFalse($(By.name("non-existing-element")).exists());
}
@Test
public void userCanCheckIfElementExistsAndVisible() {
assertTrue($(By.name("domain")).isDisplayed());
assertFalse($("#theHiddenElement").isDisplayed());
assertFalse($(By.name("non-existing-element")).isDisplayed());
$("#theHiddenElement").shouldBe(hidden);
$("#theHiddenElement").should(disappear);
$("#theHiddenElement").waitUntil(disappears, 1000);
$("#theHiddenElement").should(exist);
$("#theHiddenElement").shouldBe(present);
$("#theHiddenElement").waitUntil(present, 1000);
$(".non-existing-element").should(not(exist));
$(".non-existing-element").shouldNot(exist);
$(".non-existing-element").shouldNotBe(present);
$(".non-existing-element").waitUntil(not(present), 1000);
$(".non-existing-element").waitWhile(present, 1000);
}
@Test
public void userCanCheckIfElementIsReadonly() {
$(By.name("username")).shouldBe(readonly);
$(By.name("password")).shouldNotBe(readonly);
}
@Test
public void toStringMethodShowsElementDetails() {
assertEquals("<h1>Page without JQuery</h1>", $("h1").toString());
assertEquals("<h2>Dropdown list</h2>", $("h2").toString());
assertTrue($(By.name("rememberMe")).toString().contains("<input name=rememberMe"));
assertTrue($(By.name("rememberMe")).toString().contains("type=checkbox></input>"));
assertEquals("<option value=livemail.ru selected:true>@livemail.ru</option>",
$(By.name("domain")).find("option").toString());
assertTrue($(byText("Want to see ajax in action?")).toString().contains("<a href="));
assertTrue($(byText("Want to see ajax in action?")).toString().contains(">Want to see ajax in action?</a>"));
}
@Test
public void userCanFindElementByAttribute() {
assertEquals("select", $(byAttribute("name", "domain")).getTagName());
assertEquals("@мыло.ру", $(byAttribute("value", "мыло.ру")).getText());
assertEquals("div", $(byAttribute("id", "radioButtons")).getTagName());
assertEquals(4, $$(byAttribute("type", "radio")).size());
assertEquals("username", $(byAttribute("readonly", "readonly")).getAttribute("name"));
assertEquals("meta", $(byAttribute("http-equiv", "Content-Type")).getTagName());
}
@Test
public void userCanGetAttr() {
assertEquals("username", $(by("readonly", "readonly")).attr("name"));
}
@Test
public void userCanGetNameAttribute() {
assertEquals("username", $(by("readonly", "readonly")).name());
}
@Test
public void userCanGetDataAttributes() {
assertEquals("111", $(byValue("livemail.ru")).getAttribute("data-mailServerId"));
assertEquals("111", $(byValue("livemail.ru")).data("mailServerId"));
assertEquals("222A", $(byText("@myrambler.ru")).data("mailServerId"));
assertEquals("33333B", $(byValue("rusmail.ru")).data("mailServerId"));
assertEquals("111АБВГД", $(byText("@мыло.ру")).data("mailServerId"));
}
@Test
public void userCanGetInnerHtmlOfElement() {
assertEquals("@livemail.ru", $(byValue("livemail.ru")).innerHtml());
assertEquals("@myrambler.ru", $(byText("@myrambler.ru")).innerHtml());
assertEquals("@мыло.ру", $(byText("@мыло.ру")).innerHtml());
assertEquals("Dropdown list", $("h2").innerHtml());
if (isHtmlUnit()) {
assertEquals("<span></span> l'a\n baskerville", $("#baskerville").innerHtml().trim().toLowerCase());
assertEquals("username: <span class=name>bob smith</span> last login: <span class=last-login>01.01.1970</span>",
$("#status").innerHtml().trim().toLowerCase());
}
else {
assertEquals("<span></span> L'a\n Baskerville", $("#baskerville").innerHtml().trim());
assertEquals("Username: <span class=\"name\">Bob Smith</span> Last login: <span class=\"last-login\">01.01.1970</span>",
$("#status").innerHtml().trim());
}
}
@Test
public void userCanGetTextAndHtmlOfHiddenElement() {
assertEquals("видишь суслика? и я не вижу. <b>а он есть</b>!",
$("#theHiddenElement").innerHtml().trim().toLowerCase());
assertEquals("Видишь суслика? И я не вижу. А он есть!",
$("#theHiddenElement").innerText().trim());
}
@Test
public void userCanSearchElementByDataAttribute() {
assumeFalse(isChrome() || isHtmlUnit() || isPhantomjs());
assertEquals("111", $(by("data-mailServerId", "111")).data("mailServerId"));
assertEquals("222A", $(by("data-mailServerId", "222A")).data("mailServerId"));
assertEquals("33333B", $(by("data-mailServerId", "33333B")).data("mailServerId"));
assertEquals("111АБВГД", $(by("data-mailServerId", "111АБВГД")).data("mailServerId"));
}
@Test
public void userCanSearchElementByTitleAttribute() {
assertEquals("fieldset", $(byTitle("Login form")).getTagName());
}
@Test
public void userCanSetValueToTextfield() {
$(By.name("password")).setValue("john");
$(By.name("password")).val("sherlyn");
$(By.name("password")).shouldBe(focused);
$(By.name("password")).shouldHave(value("sherlyn"));
$(By.name("password")).waitUntil(hasValue("sherlyn"), 1000);
assertEquals("sherlyn", $(By.name("password")).val());
}
@Test
public void userCanAppendValueToTextfield() {
$(By.name("password")).val("Sherlyn");
$(By.name("password")).append(" theron");
$(By.name("password")).shouldHave(value("Sherlyn theron"));
assertEquals("Sherlyn theron", $(By.name("password")).val());
}
@Test
public void userCanPressEnter() {
assertEquals(-1, url().indexOf("#submitted-form"));
$(By.name("password")).val("Going to press ENTER").pressEnter();
assertTrue(url().contains("#submitted-form"));
}
@Test
public void userCanPressTab() {
$("#username-blur-counter").shouldHave(text("___"));
$("#username").sendKeys(" x ");
$("#username").pressTab();
if (!isHtmlUnit()) {
// fails in HtmlUnit and Chrome for unknown reason
$("#password").shouldBe(focused);
$("#username-mirror").shouldHave(text(" x "));
if (!isChrome()) {
$("#username-blur-counter").shouldHave(text("blur: 1"));
}
}
}
@Test
public void userCanCheckIfElementContainsText() {
assertEquals("Page without JQuery", $("h1").text());
assertEquals("Dropdown list", $("h2").text());
assertEquals("@livemail.ru", $(By.name("domain")).find("option").text());
assertEquals("Radio buttons\nЯ идиот Я тупица Я готов I don't speak Russian", $("#radioButtons").text());
$("h1").shouldHave(text("Page "));
$("h2").shouldHave(text("Dropdown list"));
$(By.name("domain")).find("option").shouldHave(text("vemail.r"));
$("#radioButtons").shouldHave(text("buttons\nЯ идиот Я тупица"));
}
@Test
public void userCanCheckIfElementHasExactText() {
$("h1").shouldHave(exactText("Page without JQuery"));
$("h2").shouldHave(exactText("Dropdown list"));
$(By.name("domain")).find("option").shouldHave(text("@livemail.ru"));
$("#radioButtons").shouldHave(text("Radio buttons\n" +
"Я идиот Я тупица Я готов I don't speak Russian"));
}
@Test
public void elementIsEmptyIfTextAndValueAreBothEmpty() {
$("br").shouldBe(empty);
$("h2").shouldNotBe(empty);
$(By.name("password")).shouldBe(empty);
$("#login").shouldNotBe(empty);
$("#empty-text-area").shouldBe(empty);
$("#text-area").shouldNotBe(empty);
}
@Test @Ignore
public void userCanUploadFiles() {
$("#file_upload").uploadFromClasspath("some-file.txt");
}
@Test
public void userCanGetOriginalWebElement() {
WebElement selenideElement = $(By.name("domain")).toWebElement();
WebElement seleniumElement = getWebDriver().findElement(By.name("domain"));
assertSame(seleniumElement.getClass(), selenideElement.getClass());
assertEquals(seleniumElement.getTagName(), selenideElement.getTagName());
assertEquals(seleniumElement.getText(), selenideElement.getText());
}
@Test
public void userCanFollowLinks() {
$(By.linkText("Want to see ajax in action?")).followLink();
// $(By.linkText("Want to see ajax in action?")).click();
assertTrue("Actual URL is: " + url(), url().contains("long_ajax_request.html"));
}
@Test
public void userCanSelectCheckbox() {
$(By.name("rememberMe")).shouldNotBe(selected);
$(By.name("rememberMe")).click();
$(By.name("rememberMe")).shouldBe(selected);
assertEquals("<input name=rememberMe value=on type=checkbox selected:true></input>",
$(By.name("rememberMe")).toString());
}
@Test
public void userCanUseSeleniumActions() {
$(By.name("rememberMe")).shouldNotBe(selected);
actions().click($(By.name("rememberMe"))).build().perform();
$(By.name("rememberMe")).shouldBe(selected);
}
@Test(expected = ElementNotFound.class)
public void shouldNotThrowsElementNotFound() {
$(byText("Unexisting text")).shouldNotBe(hidden);
}
@Test(expected = ElementShouldNot.class)
public void shouldNotThrowsElementMatches() {
$(byText("Bob")).shouldNotHave(cssClass("firstname"));
}
@Test
public void userCanCheckCssClass() {
$(byText("Bob")).shouldHave(cssClass("firstname"));
$(byText("Dilan")).shouldHave(cssClass("lastname"));
$(byText("25")).shouldHave(cssClass("age"));
$(byText("First name")).shouldNotHave(cssClass("anything"));
}
@Test
public void userCanGetPageTitle() {
assertEquals("long ajax request", title());
}
@Test
public void userCanCheckElementId() {
$("#multirowTable").shouldHave(id("multirowTable"));
$("#login").shouldHave(id("login"));
$(By.id("theHiddenElement")).shouldHave(id("theHiddenElement"));
$("h3").shouldHave(id("username-mirror"));
}
@Test
public void userCanCheckElementName() {
$("select").shouldHave(name("domain"));
$(by("type", "radio")).shouldHave(name("me"));
$(by("type", "checkbox")).shouldHave(name("rememberMe"));
$("#username").shouldHave(name("username"));
}
@Test
public void userCanCheckElementType() {
$("#login").shouldHave(type("submit"));
$(By.name("me")).shouldHave(type("radio"));
$(By.name("rememberMe")).shouldHave(type("checkbox"));
}
@Test
public void userCanFindFirstMatchingSubElement() {
$(By.name("domain")).find("option").shouldHave(value("livemail.ru"));
$(By.name("domain")).$("option").shouldHave(value("livemail.ru"));
}
@Test
public void findWaitsUntilParentAppears() {
$("#container").find("#dynamic-content2").shouldBe(visible);
}
@Test
public void findWaitsUntilElementMatchesCondition() {
$("#dynamic-content-container").find("#dynamic-content2").shouldBe(visible);
}
@Test
public void userCanListMatchingSubElements() {
$("#multirowTable").findAll(byText("Chack")).shouldHaveSize(2);
$("#multirowTable").$$(byText("Chack")).shouldHaveSize(2);
$("#multirowTable tr").findAll(byText("Chack")).shouldHaveSize(1);
$("#multirowTable tr").$$(byText("Chack")).shouldHaveSize(1);
}
@Test
public void errorMessageShouldContainUrlIfBrowserFailedToOpenPage() {
try {
baseUrl = "http://localhost:8080";
open("www.yandex.ru");
} catch (WebDriverException e) {
assertTrue(e.getAdditionalInformation().contains("selenide.baseUrl: http://localhost:8080"));
assertTrue(e.getAdditionalInformation().contains("selenide.url: http://localhost:8080www.yandex.ru"));
}
}
@Test
public void userCanRightClickOnElement() {
$(By.name("password")).contextClick();
$("#login").click();
$("#login").contextClick();
$(By.name("domain")).find("option").click();
$(By.name("domain")).find("option").contextClick();
}
@Test
public void userCanCheckConditions() {
assertTrue($("#login").is(visible));
assertTrue($("#multirowTable").has(text("Chack")));
assertFalse($(".non-existing-element").has(text("Ninja")));
assertFalse($("#multirowTable").has(text("Ninja")));
}
@Test(expected = InvalidSelectorException.class)
public void checkFailsForInvalidSelector() {
$("//input[:attr='al]").is(visible);
}
@Test
public void userCanCheckCheckbox() {
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
}
@Test
public void userCanUnCheckCheckbox() {
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
$(By.name("rememberMe")).setSelected(false);
$(By.name("rememberMe")).shouldNotBe(selected);
$(By.name("rememberMe")).setSelected(false);
$(By.name("rememberMe")).shouldNotBe(selected);
}
@Test
public void userCanUseOrCondition() {
Condition one_of_conditions = or("baskerville", text("Basker"), text("Walle"));
$("#baskerville").shouldBe(one_of_conditions);
Condition all_of_conditions = or("baskerville", text("Basker"), text("rville"));
$("#baskerville").shouldBe(all_of_conditions);
Condition none_of_conditions = or("baskerville", text("pasker"), text("wille"));
$("#baskerville").shouldNotBe(none_of_conditions);
}
@Test
public void canCheckJavaScriptErrors() {
assumeFalse(isFirefox()); // window.onerror does not work in Firefox for unknown reason :(
openFile("page_with_js_errors.html");
assertNoJavascriptErrors();
$(byText("Generate JS Error")).click();
assertEquals(1, getJavascriptErrors().size());
String jsError = getJavascriptErrors().get(0);
assertTrue(jsError, jsError.contains("ReferenceError"));
assertTrue(jsError, jsError.contains("$"));
assertTrue(jsError, jsError.contains("/page_with_js_errors.html"));
}
}
| src/test/java/integration/SelenideMethodsTest.java | package integration;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ex.ElementNotFound;
import com.codeborne.selenide.ex.ElementShouldNot;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.InvalidSelectorException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import static com.codeborne.selenide.Condition.*;
import static com.codeborne.selenide.Configuration.baseUrl;
import static com.codeborne.selenide.Selectors.*;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.WebDriverRunner.*;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
public class SelenideMethodsTest extends IntegrationTest {
@Before
public void openTestPageWithJQuery() {
openFile("page_with_selects_without_jquery.html");
}
@Test
public void userCanCheckIfElementExists() {
assertTrue($(By.name("domain")).exists());
assertTrue($("#theHiddenElement").exists());
assertFalse($(By.name("non-existing-element")).exists());
}
@Test
public void userCanCheckIfElementExistsAndVisible() {
assertTrue($(By.name("domain")).isDisplayed());
assertFalse($("#theHiddenElement").isDisplayed());
assertFalse($(By.name("non-existing-element")).isDisplayed());
$("#theHiddenElement").shouldBe(hidden);
$("#theHiddenElement").should(disappear);
$("#theHiddenElement").waitUntil(disappears, 1000);
$("#theHiddenElement").should(exist);
$("#theHiddenElement").shouldBe(present);
$("#theHiddenElement").waitUntil(present, 1000);
$(".non-existing-element").should(not(exist));
$(".non-existing-element").shouldNot(exist);
$(".non-existing-element").shouldNotBe(present);
$(".non-existing-element").waitUntil(not(present), 1000);
$(".non-existing-element").waitWhile(present, 1000);
}
@Test
public void userCanCheckIfElementIsReadonly() {
$(By.name("username")).shouldBe(readonly);
$(By.name("password")).shouldNotBe(readonly);
}
@Test
public void toStringMethodShowsElementDetails() {
assertEquals("<h1>Page without JQuery</h1>", $("h1").toString());
assertEquals("<h2>Dropdown list</h2>", $("h2").toString());
assertTrue($(By.name("rememberMe")).toString().contains("<input name=rememberMe"));
assertTrue($(By.name("rememberMe")).toString().contains("type=checkbox></input>"));
assertEquals("<option value=livemail.ru selected:true>@livemail.ru</option>",
$(By.name("domain")).find("option").toString());
assertTrue($(byText("Want to see ajax in action?")).toString().contains("<a href="));
assertTrue($(byText("Want to see ajax in action?")).toString().contains(">Want to see ajax in action?</a>"));
}
@Test
public void userCanFindElementByAttribute() {
assertEquals("select", $(byAttribute("name", "domain")).getTagName());
assertEquals("@мыло.ру", $(byAttribute("value", "мыло.ру")).getText());
assertEquals("div", $(byAttribute("id", "radioButtons")).getTagName());
assertEquals(4, $$(byAttribute("type", "radio")).size());
assertEquals("username", $(byAttribute("readonly", "readonly")).getAttribute("name"));
assertEquals("meta", $(byAttribute("http-equiv", "Content-Type")).getTagName());
}
@Test
public void userCanGetAttr() {
assertEquals("username", $(by("readonly", "readonly")).attr("name"));
}
@Test
public void userCanGetNameAttribute() {
assertEquals("username", $(by("readonly", "readonly")).name());
}
@Test
public void userCanGetDataAttributes() {
assertEquals("111", $(byValue("livemail.ru")).getAttribute("data-mailServerId"));
assertEquals("111", $(byValue("livemail.ru")).data("mailServerId"));
assertEquals("222A", $(byText("@myrambler.ru")).data("mailServerId"));
assertEquals("33333B", $(byValue("rusmail.ru")).data("mailServerId"));
assertEquals("111АБВГД", $(byText("@мыло.ру")).data("mailServerId"));
}
@Test
public void userCanGetInnerHtmlOfElement() {
assertEquals("@livemail.ru", $(byValue("livemail.ru")).innerHtml());
assertEquals("@myrambler.ru", $(byText("@myrambler.ru")).innerHtml());
assertEquals("@мыло.ру", $(byText("@мыло.ру")).innerHtml());
assertEquals("Dropdown list", $("h2").innerHtml());
if (isHtmlUnit()) {
assertEquals("<span></span> l'a\n baskerville", $("#baskerville").innerHtml().trim().toLowerCase());
assertEquals("username: <span class=name>bob smith</span> last login: <span class=last-login>01.01.1970</span>",
$("#status").innerHtml().trim().toLowerCase());
}
else {
assertEquals("<span></span> L'a\n Baskerville", $("#baskerville").innerHtml().trim());
assertEquals("Username: <span class=\"name\">Bob Smith</span> Last login: <span class=\"last-login\">01.01.1970</span>",
$("#status").innerHtml().trim());
}
}
@Test
public void userCanGetTextAndHtmlOfHiddenElement() {
assertEquals("видишь суслика? и я не вижу. <b>а он есть</b>!",
$("#theHiddenElement").innerHtml().trim().toLowerCase());
assertEquals("Видишь суслика? И я не вижу. А он есть!",
$("#theHiddenElement").innerText().trim());
}
@Test
public void userCanSearchElementByDataAttribute() {
assumeFalse(isChrome() || isHtmlUnit() || isPhantomjs());
assertEquals("111", $(by("data-mailServerId", "111")).data("mailServerId"));
assertEquals("222A", $(by("data-mailServerId", "222A")).data("mailServerId"));
assertEquals("33333B", $(by("data-mailServerId", "33333B")).data("mailServerId"));
assertEquals("111АБВГД", $(by("data-mailServerId", "111АБВГД")).data("mailServerId"));
}
@Test
public void userCanSearchElementByTitleAttribute() {
assertEquals("fieldset", $(byTitle("Login form")).getTagName());
}
@Test
public void userCanSetValueToTextfield() {
$(By.name("password")).setValue("john");
$(By.name("password")).val("sherlyn");
$(By.name("password")).shouldBe(focused);
$(By.name("password")).shouldHave(value("sherlyn"));
$(By.name("password")).waitUntil(hasValue("sherlyn"), 1000);
assertEquals("sherlyn", $(By.name("password")).val());
}
@Test
public void userCanAppendValueToTextfield() {
$(By.name("password")).val("Sherlyn");
$(By.name("password")).append(" theron");
$(By.name("password")).shouldHave(value("Sherlyn theron"));
assertEquals("Sherlyn theron", $(By.name("password")).val());
}
@Test
public void userCanPressEnter() {
assertEquals(-1, url().indexOf("#submitted-form"));
$(By.name("password")).val("Going to press ENTER").pressEnter();
assertTrue(url().contains("#submitted-form"));
}
@Test
public void userCanPressTab() {
$("#username-blur-counter").shouldHave(text("___"));
$("#username").sendKeys(" x ");
$("#username").pressTab();
if (!isHtmlUnit()) {
// fails in HtmlUnit and Chrome for unknown reason
$("#password").shouldBe(focused);
$("#username-mirror").shouldHave(text(" x "));
// if (!isChrome()) {
$("#username-blur-counter").shouldHave(text("blur: 1"));
// }
}
}
@Test
public void userCanCheckIfElementContainsText() {
assertEquals("Page without JQuery", $("h1").text());
assertEquals("Dropdown list", $("h2").text());
assertEquals("@livemail.ru", $(By.name("domain")).find("option").text());
assertEquals("Radio buttons\nЯ идиот Я тупица Я готов I don't speak Russian", $("#radioButtons").text());
$("h1").shouldHave(text("Page "));
$("h2").shouldHave(text("Dropdown list"));
$(By.name("domain")).find("option").shouldHave(text("vemail.r"));
$("#radioButtons").shouldHave(text("buttons\nЯ идиот Я тупица"));
}
@Test
public void userCanCheckIfElementHasExactText() {
$("h1").shouldHave(exactText("Page without JQuery"));
$("h2").shouldHave(exactText("Dropdown list"));
$(By.name("domain")).find("option").shouldHave(text("@livemail.ru"));
$("#radioButtons").shouldHave(text("Radio buttons\n" +
"Я идиот Я тупица Я готов I don't speak Russian"));
}
@Test
public void elementIsEmptyIfTextAndValueAreBothEmpty() {
$("br").shouldBe(empty);
$("h2").shouldNotBe(empty);
$(By.name("password")).shouldBe(empty);
$("#login").shouldNotBe(empty);
$("#empty-text-area").shouldBe(empty);
$("#text-area").shouldNotBe(empty);
}
@Test @Ignore
public void userCanUploadFiles() {
$("#file_upload").uploadFromClasspath("some-file.txt");
}
@Test
public void userCanGetOriginalWebElement() {
WebElement selenideElement = $(By.name("domain")).toWebElement();
WebElement seleniumElement = getWebDriver().findElement(By.name("domain"));
assertSame(seleniumElement.getClass(), selenideElement.getClass());
assertEquals(seleniumElement.getTagName(), selenideElement.getTagName());
assertEquals(seleniumElement.getText(), selenideElement.getText());
}
@Test
public void userCanFollowLinks() {
$(By.linkText("Want to see ajax in action?")).followLink();
// $(By.linkText("Want to see ajax in action?")).click();
assertTrue("Actual URL is: " + url(), url().contains("long_ajax_request.html"));
}
@Test
public void userCanSelectCheckbox() {
$(By.name("rememberMe")).shouldNotBe(selected);
$(By.name("rememberMe")).click();
$(By.name("rememberMe")).shouldBe(selected);
assertEquals("<input name=rememberMe value=on type=checkbox selected:true></input>",
$(By.name("rememberMe")).toString());
}
@Test
public void userCanUseSeleniumActions() {
$(By.name("rememberMe")).shouldNotBe(selected);
actions().click($(By.name("rememberMe"))).build().perform();
$(By.name("rememberMe")).shouldBe(selected);
}
@Test(expected = ElementNotFound.class)
public void shouldNotThrowsElementNotFound() {
$(byText("Unexisting text")).shouldNotBe(hidden);
}
@Test(expected = ElementShouldNot.class)
public void shouldNotThrowsElementMatches() {
$(byText("Bob")).shouldNotHave(cssClass("firstname"));
}
@Test
public void userCanCheckCssClass() {
$(byText("Bob")).shouldHave(cssClass("firstname"));
$(byText("Dilan")).shouldHave(cssClass("lastname"));
$(byText("25")).shouldHave(cssClass("age"));
$(byText("First name")).shouldNotHave(cssClass("anything"));
}
@Test
public void userCanGetPageTitle() {
assertEquals("long ajax request", title());
}
@Test
public void userCanCheckElementId() {
$("#multirowTable").shouldHave(id("multirowTable"));
$("#login").shouldHave(id("login"));
$(By.id("theHiddenElement")).shouldHave(id("theHiddenElement"));
$("h3").shouldHave(id("username-mirror"));
}
@Test
public void userCanCheckElementName() {
$("select").shouldHave(name("domain"));
$(by("type", "radio")).shouldHave(name("me"));
$(by("type", "checkbox")).shouldHave(name("rememberMe"));
$("#username").shouldHave(name("username"));
}
@Test
public void userCanCheckElementType() {
$("#login").shouldHave(type("submit"));
$(By.name("me")).shouldHave(type("radio"));
$(By.name("rememberMe")).shouldHave(type("checkbox"));
}
@Test
public void userCanFindFirstMatchingSubElement() {
$(By.name("domain")).find("option").shouldHave(value("livemail.ru"));
$(By.name("domain")).$("option").shouldHave(value("livemail.ru"));
}
@Test
public void findWaitsUntilParentAppears() {
$("#container").find("#dynamic-content2").shouldBe(visible);
}
@Test
public void findWaitsUntilElementMatchesCondition() {
$("#dynamic-content-container").find("#dynamic-content2").shouldBe(visible);
}
@Test
public void userCanListMatchingSubElements() {
$("#multirowTable").findAll(byText("Chack")).shouldHaveSize(2);
$("#multirowTable").$$(byText("Chack")).shouldHaveSize(2);
$("#multirowTable tr").findAll(byText("Chack")).shouldHaveSize(1);
$("#multirowTable tr").$$(byText("Chack")).shouldHaveSize(1);
}
@Test
public void errorMessageShouldContainUrlIfBrowserFailedToOpenPage() {
try {
baseUrl = "http://localhost:8080";
open("www.yandex.ru");
} catch (WebDriverException e) {
assertTrue(e.getAdditionalInformation().contains("selenide.baseUrl: http://localhost:8080"));
assertTrue(e.getAdditionalInformation().contains("selenide.url: http://localhost:8080www.yandex.ru"));
}
}
@Test
public void userCanRightClickOnElement() {
$(By.name("password")).contextClick();
$("#login").click();
$("#login").contextClick();
$(By.name("domain")).find("option").click();
$(By.name("domain")).find("option").contextClick();
}
@Test
public void userCanCheckConditions() {
assertTrue($("#login").is(visible));
assertTrue($("#multirowTable").has(text("Chack")));
assertFalse($(".non-existing-element").has(text("Ninja")));
assertFalse($("#multirowTable").has(text("Ninja")));
}
@Test(expected = InvalidSelectorException.class)
public void checkFailsForInvalidSelector() {
$("//input[:attr='al]").is(visible);
}
@Test
public void userCanCheckCheckbox() {
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
}
@Test
public void userCanUnCheckCheckbox() {
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
$(By.name("rememberMe")).setSelected(false);
$(By.name("rememberMe")).shouldNotBe(selected);
$(By.name("rememberMe")).setSelected(false);
$(By.name("rememberMe")).shouldNotBe(selected);
}
@Test
public void userCanUseOrCondition() {
Condition one_of_conditions = or("baskerville", text("Basker"), text("Walle"));
$("#baskerville").shouldBe(one_of_conditions);
Condition all_of_conditions = or("baskerville", text("Basker"), text("rville"));
$("#baskerville").shouldBe(all_of_conditions);
Condition none_of_conditions = or("baskerville", text("pasker"), text("wille"));
$("#baskerville").shouldNotBe(none_of_conditions);
}
@Test
public void canCheckJavaScriptErrors() {
assumeFalse(isFirefox()); // window.onerror does not work in Firefox for unknown reason :(
openFile("page_with_js_errors.html");
assertNoJavascriptErrors();
$(byText("Generate JS Error")).click();
assertEquals(1, getJavascriptErrors().size());
String jsError = getJavascriptErrors().get(0);
assertTrue(jsError, jsError.contains("ReferenceError"));
assertTrue(jsError, jsError.contains("$"));
assertTrue(jsError, jsError.contains("/page_with_js_errors.html"));
}
}
| Hope to make "userCanPressTab" test more stable
| src/test/java/integration/SelenideMethodsTest.java | Hope to make "userCanPressTab" test more stable | <ide><path>rc/test/java/integration/SelenideMethodsTest.java
<ide> // fails in HtmlUnit and Chrome for unknown reason
<ide> $("#password").shouldBe(focused);
<ide> $("#username-mirror").shouldHave(text(" x "));
<del>// if (!isChrome()) {
<add> if (!isChrome()) {
<ide> $("#username-blur-counter").shouldHave(text("blur: 1"));
<del>// }
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | e30a45a6ff321285d2a1f0f2b4cf21b96c8b7dee | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.maintenance;
import com.yahoo.component.annotation.Inject;
import com.yahoo.component.AbstractComponent;
import com.yahoo.concurrent.maintenance.Maintainer;
import com.yahoo.config.provision.Deployer;
import com.yahoo.config.provision.HostLivenessTracker;
import com.yahoo.config.provision.InfraDeployer;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.Zone;
import com.yahoo.jdisc.Metric;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.autoscale.MetricsFetcher;
import com.yahoo.vespa.hosted.provision.provisioning.ProvisionServiceProvider;
import com.yahoo.vespa.service.monitor.ServiceMonitor;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A component which sets up all the node repo maintenance jobs.
*
* @author bratseth
*/
public class NodeRepositoryMaintenance extends AbstractComponent {
private final List<Maintainer> maintainers = new CopyOnWriteArrayList<>();
@SuppressWarnings("unused")
@Inject
public NodeRepositoryMaintenance(NodeRepository nodeRepository, Deployer deployer, InfraDeployer infraDeployer,
HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor,
Zone zone, Metric metric,
ProvisionServiceProvider provisionServiceProvider, FlagSource flagSource,
MetricsFetcher metricsFetcher) {
DefaultTimes defaults = new DefaultTimes(zone, deployer);
PeriodicApplicationMaintainer periodicApplicationMaintainer = new PeriodicApplicationMaintainer(deployer, metric, nodeRepository, defaults.redeployMaintainerInterval,
defaults.periodicRedeployInterval, flagSource);
InfrastructureProvisioner infrastructureProvisioner = new InfrastructureProvisioner(nodeRepository, infraDeployer, defaults.infrastructureProvisionInterval, metric);
maintainers.add(periodicApplicationMaintainer);
maintainers.add(infrastructureProvisioner);
maintainers.add(new NodeFailer(deployer, nodeRepository, defaults.failGrace, defaults.nodeFailerInterval, defaults.throttlePolicy, metric));
maintainers.add(new NodeHealthTracker(hostLivenessTracker, serviceMonitor, nodeRepository, defaults.nodeFailureStatusUpdateInterval, metric));
maintainers.add(new ExpeditedChangeApplicationMaintainer(deployer, metric, nodeRepository, defaults.expeditedChangeRedeployInterval));
maintainers.add(new ReservationExpirer(nodeRepository, defaults.reservationExpiry, metric));
maintainers.add(new RetiredExpirer(nodeRepository, deployer, metric, defaults.retiredInterval, defaults.retiredExpiry));
maintainers.add(new InactiveExpirer(nodeRepository, defaults.inactiveExpiry, Map.of(NodeType.config, defaults.inactiveConfigServerExpiry,
NodeType.controller, defaults.inactiveControllerExpiry),
metric));
maintainers.add(new FailedExpirer(nodeRepository, zone, defaults.failedExpirerInterval, metric));
maintainers.add(new DirtyExpirer(nodeRepository, defaults.dirtyExpiry, metric));
maintainers.add(new ProvisionedExpirer(nodeRepository, defaults.provisionedExpiry, metric));
maintainers.add(new NodeRebooter(nodeRepository, flagSource, metric));
maintainers.add(new MetricsReporter(nodeRepository, metric, serviceMonitor, periodicApplicationMaintainer::pendingDeployments, defaults.metricsInterval));
maintainers.add(new SpareCapacityMaintainer(deployer, nodeRepository, metric, defaults.spareCapacityMaintenanceInterval));
maintainers.add(new OsUpgradeActivator(nodeRepository, defaults.osUpgradeActivatorInterval, metric));
maintainers.add(new Rebalancer(deployer, nodeRepository, metric, defaults.rebalancerInterval));
maintainers.add(new NodeMetricsDbMaintainer(nodeRepository, metricsFetcher, defaults.nodeMetricsCollectionInterval, metric));
maintainers.add(new AutoscalingMaintainer(nodeRepository, deployer, metric, defaults.autoscalingInterval));
maintainers.add(new ScalingSuggestionsMaintainer(nodeRepository, defaults.scalingSuggestionsInterval, metric));
maintainers.add(new SwitchRebalancer(nodeRepository, defaults.switchRebalancerInterval, metric, deployer));
provisionServiceProvider.getLoadBalancerService()
.map(lbService -> new LoadBalancerExpirer(nodeRepository, defaults.loadBalancerExpirerInterval, lbService, metric))
.ifPresent(maintainers::add);
provisionServiceProvider.getHostProvisioner()
.map(hostProvisioner -> new DynamicProvisioningMaintainer(nodeRepository, defaults.dynamicProvisionerInterval, hostProvisioner, flagSource, metric))
.ifPresent(maintainers::add);
provisionServiceProvider.getHostProvisioner()
.map(hostProvisioner -> new HostRetirer(nodeRepository, defaults.hostRetirerInterval, metric, hostProvisioner))
.ifPresent(maintainers::add);
// The DuperModel is filled with infrastructure applications by the infrastructure provisioner, so explicitly run that now
infrastructureProvisioner.maintainButThrowOnException();
}
@Override
public void deconstruct() {
maintainers.forEach(Maintainer::shutdown);
maintainers.forEach(Maintainer::awaitShutdown);
}
private static class DefaultTimes {
/** Minimum time to wait between deployments by periodic application maintainer*/
private final Duration periodicRedeployInterval;
/** Time between each run of maintainer that does periodic redeployment */
private final Duration redeployMaintainerInterval;
/** Applications are redeployed after manual operator changes within this time period */
private final Duration expeditedChangeRedeployInterval;
/** The time a node must be continuously unresponsive before it is failed */
private final Duration failGrace;
private final Duration reservationExpiry;
private final Duration inactiveExpiry;
private final Duration inactiveConfigServerExpiry;
private final Duration inactiveControllerExpiry;
private final Duration retiredExpiry;
private final Duration failedExpirerInterval;
private final Duration dirtyExpiry;
private final Duration provisionedExpiry;
private final Duration spareCapacityMaintenanceInterval;
private final Duration metricsInterval;
private final Duration nodeFailerInterval;
private final Duration nodeFailureStatusUpdateInterval;
private final Duration retiredInterval;
private final Duration infrastructureProvisionInterval;
private final Duration loadBalancerExpirerInterval;
private final Duration dynamicProvisionerInterval;
private final Duration osUpgradeActivatorInterval;
private final Duration rebalancerInterval;
private final Duration nodeMetricsCollectionInterval;
private final Duration autoscalingInterval;
private final Duration scalingSuggestionsInterval;
private final Duration switchRebalancerInterval;
private final Duration hostRetirerInterval;
private final NodeFailer.ThrottlePolicy throttlePolicy;
DefaultTimes(Zone zone, Deployer deployer) {
autoscalingInterval = Duration.ofMinutes(5);
dynamicProvisionerInterval = Duration.ofMinutes(3);
failedExpirerInterval = Duration.ofMinutes(10);
failGrace = Duration.ofMinutes(30);
infrastructureProvisionInterval = Duration.ofMinutes(3);
loadBalancerExpirerInterval = Duration.ofMinutes(5);
metricsInterval = Duration.ofMinutes(1);
nodeFailerInterval = Duration.ofMinutes(15);
nodeFailureStatusUpdateInterval = Duration.ofMinutes(2);
nodeMetricsCollectionInterval = Duration.ofMinutes(1);
expeditedChangeRedeployInterval = Duration.ofMinutes(3);
// Vespa upgrade frequency is higher in CD so (de)activate OS upgrades more frequently as well
osUpgradeActivatorInterval = zone.system().isCd() ? Duration.ofSeconds(30) : Duration.ofMinutes(5);
periodicRedeployInterval = Duration.ofMinutes(60);
provisionedExpiry = zone.getCloud().dynamicProvisioning() ? Duration.ofMinutes(40) : Duration.ofHours(4);
rebalancerInterval = Duration.ofMinutes(120);
redeployMaintainerInterval = Duration.ofMinutes(1);
// Need to be long enough for deployment to be finished for all config model versions
reservationExpiry = deployer.serverDeployTimeout();
scalingSuggestionsInterval = Duration.ofMinutes(31);
spareCapacityMaintenanceInterval = Duration.ofMinutes(30);
switchRebalancerInterval = Duration.ofHours(1);
throttlePolicy = NodeFailer.ThrottlePolicy.hosted;
inactiveConfigServerExpiry = Duration.ofMinutes(5);
inactiveControllerExpiry = Duration.ofMinutes(5);
hostRetirerInterval = Duration.ofMinutes(30);
if (zone.environment().isProduction() && ! zone.system().isCd()) {
inactiveExpiry = Duration.ofHours(4); // enough time for the application owner to discover and redeploy
retiredInterval = Duration.ofMinutes(15);
dirtyExpiry = Duration.ofHours(2); // enough time to clean the node
retiredExpiry = Duration.ofDays(4); // give up migrating data after 4 days
} else {
// long enough that nodes aren't reused immediately and delete can happen on all config servers
// with time enough to clean up even with ZK connection issues on config servers
inactiveExpiry = Duration.ofMinutes(1);
retiredInterval = Duration.ofMinutes(1);
dirtyExpiry = Duration.ofMinutes(30);
retiredExpiry = Duration.ofDays(1);
}
}
}
}
| node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.maintenance;
import com.yahoo.component.annotation.Inject;
import com.yahoo.component.AbstractComponent;
import com.yahoo.concurrent.maintenance.Maintainer;
import com.yahoo.config.provision.Deployer;
import com.yahoo.config.provision.HostLivenessTracker;
import com.yahoo.config.provision.InfraDeployer;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.Zone;
import com.yahoo.jdisc.Metric;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.autoscale.MetricsFetcher;
import com.yahoo.vespa.hosted.provision.provisioning.ProvisionServiceProvider;
import com.yahoo.vespa.service.monitor.ServiceMonitor;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A component which sets up all the node repo maintenance jobs.
*
* @author bratseth
*/
public class NodeRepositoryMaintenance extends AbstractComponent {
private final List<Maintainer> maintainers = new CopyOnWriteArrayList<>();
@SuppressWarnings("unused")
@Inject
public NodeRepositoryMaintenance(NodeRepository nodeRepository, Deployer deployer, InfraDeployer infraDeployer,
HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor,
Zone zone, Metric metric,
ProvisionServiceProvider provisionServiceProvider, FlagSource flagSource,
MetricsFetcher metricsFetcher) {
DefaultTimes defaults = new DefaultTimes(zone, deployer);
PeriodicApplicationMaintainer periodicApplicationMaintainer = new PeriodicApplicationMaintainer(deployer, metric, nodeRepository, defaults.redeployMaintainerInterval,
defaults.periodicRedeployInterval, flagSource);
InfrastructureProvisioner infrastructureProvisioner = new InfrastructureProvisioner(nodeRepository, infraDeployer, defaults.infrastructureProvisionInterval, metric);
maintainers.add(periodicApplicationMaintainer);
maintainers.add(infrastructureProvisioner);
maintainers.add(new NodeFailer(deployer, nodeRepository, defaults.failGrace, defaults.nodeFailerInterval, defaults.throttlePolicy, metric));
maintainers.add(new NodeHealthTracker(hostLivenessTracker, serviceMonitor, nodeRepository, defaults.nodeFailureStatusUpdateInterval, metric));
maintainers.add(new ExpeditedChangeApplicationMaintainer(deployer, metric, nodeRepository, defaults.expeditedChangeRedeployInterval));
maintainers.add(new ReservationExpirer(nodeRepository, defaults.reservationExpiry, metric));
maintainers.add(new RetiredExpirer(nodeRepository, deployer, metric, defaults.retiredInterval, defaults.retiredExpiry));
maintainers.add(new InactiveExpirer(nodeRepository, defaults.inactiveExpiry, Map.of(NodeType.config, defaults.inactiveConfigServerExpiry,
NodeType.controller, defaults.inactiveControllerExpiry),
metric));
maintainers.add(new FailedExpirer(nodeRepository, zone, defaults.failedExpirerInterval, metric));
maintainers.add(new DirtyExpirer(nodeRepository, defaults.dirtyExpiry, metric));
maintainers.add(new ProvisionedExpirer(nodeRepository, defaults.provisionedExpiry, metric));
maintainers.add(new NodeRebooter(nodeRepository, flagSource, metric));
maintainers.add(new MetricsReporter(nodeRepository, metric, serviceMonitor, periodicApplicationMaintainer::pendingDeployments, defaults.metricsInterval));
maintainers.add(new SpareCapacityMaintainer(deployer, nodeRepository, metric, defaults.spareCapacityMaintenanceInterval));
maintainers.add(new OsUpgradeActivator(nodeRepository, defaults.osUpgradeActivatorInterval, metric));
maintainers.add(new Rebalancer(deployer, nodeRepository, metric, defaults.rebalancerInterval));
maintainers.add(new NodeMetricsDbMaintainer(nodeRepository, metricsFetcher, defaults.nodeMetricsCollectionInterval, metric));
maintainers.add(new AutoscalingMaintainer(nodeRepository, deployer, metric, defaults.autoscalingInterval));
maintainers.add(new ScalingSuggestionsMaintainer(nodeRepository, defaults.scalingSuggestionsInterval, metric));
maintainers.add(new SwitchRebalancer(nodeRepository, defaults.switchRebalancerInterval, metric, deployer));
provisionServiceProvider.getLoadBalancerService()
.map(lbService -> new LoadBalancerExpirer(nodeRepository, defaults.loadBalancerExpirerInterval, lbService, metric))
.ifPresent(maintainers::add);
provisionServiceProvider.getHostProvisioner()
.map(hostProvisioner -> new DynamicProvisioningMaintainer(nodeRepository, defaults.dynamicProvisionerInterval, hostProvisioner, flagSource, metric))
.ifPresent(maintainers::add);
provisionServiceProvider.getHostProvisioner()
.map(hostProvisioner -> new HostRetirer(nodeRepository, defaults.hostRetirerInterval, metric, hostProvisioner))
.ifPresent(maintainers::add);
// The DuperModel is filled with infrastructure applications by the infrastructure provisioner, so explicitly run that now
infrastructureProvisioner.maintainButThrowOnException();
}
@Override
public void deconstruct() {
maintainers.forEach(Maintainer::shutdown);
maintainers.forEach(Maintainer::awaitShutdown);
}
private static class DefaultTimes {
/** Minimum time to wait between deployments by periodic application maintainer*/
private final Duration periodicRedeployInterval;
/** Time between each run of maintainer that does periodic redeployment */
private final Duration redeployMaintainerInterval;
/** Applications are redeployed after manual operator changes within this time period */
private final Duration expeditedChangeRedeployInterval;
/** The time a node must be continuously unresponsive before it is failed */
private final Duration failGrace;
private final Duration reservationExpiry;
private final Duration inactiveExpiry;
private final Duration inactiveConfigServerExpiry;
private final Duration inactiveControllerExpiry;
private final Duration retiredExpiry;
private final Duration failedExpirerInterval;
private final Duration dirtyExpiry;
private final Duration provisionedExpiry;
private final Duration spareCapacityMaintenanceInterval;
private final Duration metricsInterval;
private final Duration nodeFailerInterval;
private final Duration nodeFailureStatusUpdateInterval;
private final Duration retiredInterval;
private final Duration infrastructureProvisionInterval;
private final Duration loadBalancerExpirerInterval;
private final Duration dynamicProvisionerInterval;
private final Duration osUpgradeActivatorInterval;
private final Duration rebalancerInterval;
private final Duration nodeMetricsCollectionInterval;
private final Duration autoscalingInterval;
private final Duration scalingSuggestionsInterval;
private final Duration switchRebalancerInterval;
private final Duration hostRetirerInterval;
private final NodeFailer.ThrottlePolicy throttlePolicy;
DefaultTimes(Zone zone, Deployer deployer) {
autoscalingInterval = Duration.ofMinutes(15);
dynamicProvisionerInterval = Duration.ofMinutes(3);
failedExpirerInterval = Duration.ofMinutes(10);
failGrace = Duration.ofMinutes(30);
infrastructureProvisionInterval = Duration.ofMinutes(3);
loadBalancerExpirerInterval = Duration.ofMinutes(5);
metricsInterval = Duration.ofMinutes(1);
nodeFailerInterval = Duration.ofMinutes(15);
nodeFailureStatusUpdateInterval = Duration.ofMinutes(2);
nodeMetricsCollectionInterval = Duration.ofMinutes(1);
expeditedChangeRedeployInterval = Duration.ofMinutes(3);
// Vespa upgrade frequency is higher in CD so (de)activate OS upgrades more frequently as well
osUpgradeActivatorInterval = zone.system().isCd() ? Duration.ofSeconds(30) : Duration.ofMinutes(5);
periodicRedeployInterval = Duration.ofMinutes(60);
provisionedExpiry = zone.getCloud().dynamicProvisioning() ? Duration.ofMinutes(40) : Duration.ofHours(4);
rebalancerInterval = Duration.ofMinutes(120);
redeployMaintainerInterval = Duration.ofMinutes(1);
// Need to be long enough for deployment to be finished for all config model versions
reservationExpiry = deployer.serverDeployTimeout();
scalingSuggestionsInterval = Duration.ofMinutes(31);
spareCapacityMaintenanceInterval = Duration.ofMinutes(30);
switchRebalancerInterval = Duration.ofHours(1);
throttlePolicy = NodeFailer.ThrottlePolicy.hosted;
inactiveConfigServerExpiry = Duration.ofMinutes(5);
inactiveControllerExpiry = Duration.ofMinutes(5);
hostRetirerInterval = Duration.ofMinutes(30);
if (zone.environment().isProduction() && ! zone.system().isCd()) {
inactiveExpiry = Duration.ofHours(4); // enough time for the application owner to discover and redeploy
retiredInterval = Duration.ofMinutes(15);
dirtyExpiry = Duration.ofHours(2); // enough time to clean the node
retiredExpiry = Duration.ofDays(4); // give up migrating data after 4 days
} else {
// long enough that nodes aren't reused immediately and delete can happen on all config servers
// with time enough to clean up even with ZK connection issues on config servers
inactiveExpiry = Duration.ofMinutes(1);
retiredInterval = Duration.ofMinutes(1);
dirtyExpiry = Duration.ofMinutes(30);
retiredExpiry = Duration.ofDays(1);
}
}
}
}
| Autoscaling should happen within 5 minutes
| node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java | Autoscaling should happen within 5 minutes | <ide><path>ode-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java
<ide> private final NodeFailer.ThrottlePolicy throttlePolicy;
<ide>
<ide> DefaultTimes(Zone zone, Deployer deployer) {
<del> autoscalingInterval = Duration.ofMinutes(15);
<add> autoscalingInterval = Duration.ofMinutes(5);
<ide> dynamicProvisionerInterval = Duration.ofMinutes(3);
<ide> failedExpirerInterval = Duration.ofMinutes(10);
<ide> failGrace = Duration.ofMinutes(30); |
|
JavaScript | agpl-3.0 | 1b521b346bf3ba256d0622b8081aaa85037cc52a | 0 | codingisacopingstrategy/aa.core,codingisacopingstrategy/aa.core,codingisacopingstrategy/aa.core,codingisacopingstrategy/aa.core | function post_styles (elt, attr) {
/*
* Updates and posts the annotation style
*/
// RegExp
var HASH_HEADER_RE = /(^|\n)(#{1,2}[^#].*?)#*(\n|$)/;
var STYLE_ATTR_RE = /{:[^}]*}/;
var start;
var end;
var content = "";
var clone = $(elt).clone();
clone.removeClass('section1 section2 ui-droppable ui-draggable ui-resizable ui-draggable-dragging editing highlight drophover');
clone.css({
'display': $(elt).is(":visible") ? "" : "none", // we only want to know if it is hidden or not
'position': '',
});
var $elt = clone;
var about = $.trim($elt.attr('about'));
var id = $.trim($elt.attr('id'));
var style = $.trim($elt.attr('style'));
var class_ = $.trim($elt.attr('class'));
var attr_list = "{: ";
if (about) attr_list += "about='" + about + "' ";
if (style) attr_list += "style='" + style + "' ";
if (class_) attr_list += "class='" + class_ + "' ";
attr_list += "}" ;
var style = attr_list;
var section = $(elt).attr("data-section");
$.get("edit/", {
section: section,
type: 'ajax',
}, function(data) {
// Searches for Header
var header_match = HASH_HEADER_RE.exec(data);
if (header_match) {
// Defines the substring to replace
var style_match = STYLE_ATTR_RE.exec(header_match[0]);
if (style_match) {
start = header_match.index + style_match.index;
end = start + style_match[0].length;
} else {
start = header_match.slice(1,3).join('').length;
end = start;
};
var before = data.substring(0, start);
var after = data.substring(end, data.length)
content = before + style + after;
$.post("edit/", {
content: content,
section: section,
type: 'ajax',
});
}
});
}
function resetTimelines() {
// RESET (ALL) TIMELINES
$(".player").each(function(){
var url = $(this).attr('src') || $("[src]:first", this).attr('src');
$(this).timeline({
show: function (elt) {
$(elt).addClass("active")
.closest('section.section1')
.find('div.wrapper:first')
.autoscrollable("scrollto", elt);
},
hide: function (elt) {
$(elt).removeClass("active");
},
start: function (elt) { return $(elt).attr('data-start') },
end: function (elt) { return $(elt).attr('data-end') }
}).timeline("add", 'section.section1[about="' + url + '"] *[data-start]');
});
}
(function($) {
var TEXTAREA_MIN_PADDING_BOTTOM = 40;
var currentTextArea = undefined; /* used for timecode pasting */
function ffind (selector, context) {
// "filter find", like $.find but it also checks the context element itself
return $(context).filter(selector).add(selector, context);
}
// The refresh event gets fired on body initially
// then on any <section> or other dynamically loaded/created element to "activate" it
$(document).bind("refresh", function (evt) {
//console.log("refreshing", evt.target);
var context = evt.target;
// Draggable Sections
$("section.section1").draggable({
handle: 'h1',
//delay: 100, // avoids unintentional dragging when (un)collpasing
//cursorAt: { left: 0, top: 0, },
snap: ".grid",
snapTolerance: 5,
stop: function () {
var position = $(this).position();
if (position.top < 0) {
$(this).css('top', '0px');
};
if (position.left < 0) {
$(this).css('left', '0px');
};
post_styles(this, 'style');
},
//drag: function (e) {
//if (e.ctrlKey == true) {
//$(this).draggable('option', 'grid', [20, 20]);
//} else {
//$(this).draggable('option', 'grid', false);
//}
//}
}).resizable({
stop: function () { post_styles(this, 'style') },
snap: ".grid",
});
// RENUMBER ALL SECTIONS
$("section:not([data-section='-1'])").each(function (i) {
$(this).attr("data-section", (i+1));
});
// SECTION EDIT LINKS
// Create & insert edit links in every section's Header that trigger the section's "edit" event
ffind('section', context).each(function () {
$("<span>✎</span>").addClass("section_edit_link").click(function () {
$(this).closest("section").trigger("edit");
}).prependTo($(":header:first", this));
var about = $(this).closest("section.section1").attr('about');
$("<span>@</span>").addClass("about").hover(function () {
$('.player[src="' + about + '"], section[about="' + about + '"]').addClass('highlight');
}, function() {
$('.player[src="' + about + '"], section[about="' + about + '"]').removeClass('highlight');
}).prependTo($("h1:first", this));
$(this).children("h1").bind('dblclick', function(e) {
var section = $(this).closest("section");
if (!section.hasClass('editing')) {
section.trigger("collapse");
};
});
var nonhead = $(this).children(":not(:header)");
var wrapped = $("<div class=\"wrapper\"></div>").append(nonhead);
$(this).append(wrapped);
})
// IN-PLACE EDITING
ffind('section', context).bind("collapse", function (evt) {
$(this).toggleClass('collapsed');
post_styles(this, 'class');
})
ffind('section', context).bind("edit", function (evt) {
function edit (data) {
var position = $(that).css("position");
var section_height = Math.min($(window).height() - 28, $(that).height());
var use_height = (position == "absolute") ? section_height : section_height;
var f = $("<div></div>").addClass("section_edit").appendTo(that);
var textarea = $("<textarea></textarea>").css({height: use_height+"px"}).text(data).appendTo(f);
$(that).addClass("editing");
var ok = $("<span>✔</span>").addClass("section_save_link").click(function () {
// console.log("commencing section edit save...");
$.ajax("edit/", {
type: 'post',
data: {
section: $(that).attr("data-section"),
type: 'ajax',
content: textarea.val()
},
success: function (data) {
// console.log("resetting contents of section to: ", data);
var new_content = $(data);
$(that).replaceWith(new_content);
new_content.trigger("refresh");
}
});
}).appendTo($(that).find(':header:first'));
$("<span>✘</span>").addClass("section_cancel_link").click(function () {
// console.log("cancelling section edit save...");
if (new_section) {
// removes the annotation
$(that).remove();
$(this).remove();
ok.remove();
} else {
f.remove();
$(this).remove();
ok.remove();
$(that).removeClass("editing");
}
}).appendTo($(that).find(':header:first'));
}
evt.stopPropagation();
var that = this;
var new_section = false;
if ($(this).attr('data-section') == "-1") {
new_section = true;
edit("# New section");
} else {
$.ajax("edit/", {
data: {
section: $(this).attr("data-section"),
type: 'ajax'
},
success: edit,
});
}
});
// end of IN-PLACE EDITING
/* Connect players to timed sections */
resetTimelines();
/// CLICKABLE TIMECODES
$('span[property="aa:start"],span[property="aa:end"]', context).bind("click", function () {
var t = $.timecode_tosecs_attr($(this).attr("content"));
var about = $(this).parents('*[about]').attr('about');
var player = $('[src="' + about + '"]')[0]
|| $('source[src="' + about + '"]').parent('.player')[0];
if (player) {
player.currentTime = t;
player.play();
}
});
$("span.swatch", context).each(function () {
$(this).draggable({helper: function () {
var $this = $(this);
var $clone = $(this).clone();
$clone.find('select:first').val($this.find('select:first').val());
return $clone.appendTo("body");
}});
});
ffind("section.section2", context).droppable({
accept: ".swatch",
hoverClass: "drophover",
drop: function (evt, ui) {
var $select = $(ui.helper).find('select');
var key = $select.attr("name");
var value = $select.find('option:selected').val();
var s1 = $(this).closest(".section2");
s1.css(key, value);
post_styles(s1, 'style');
}
});
ffind("section.section1", context).droppable({
accept: ".swatch",
hoverClass: "drophover",
drop: function (evt, ui) {
var $select = $(ui.helper).find('select');
var key = $select.attr("name");
var value = $select.find('option:selected').val();
var s1 = $(this).closest(".section1");
s1.css(key, value);
post_styles(s1, 'style');
}
});
});
$(document).ready(function() {
/* INIT */
$(document).trigger("refresh");
/////////////////////
/////////////////////
/////////////////////
// Once-only page inits
$("section.section1 > div.wrapper").autoscrollable();
//$("section.section1").autoscrollable();
/////////////////////////
// SHORTCUTS
// maintain variable currentTextArea
$("section textarea").live("focus", function () {
currentTextArea = this;
}).live("blur", function () {
currentTextArea = undefined;
});
function firstPlayer () {
/*
* returns first playing player (unwrapped) element (if one is playing),
* or just first player otherwise
*/
$(".player").each(function () {
if (!this.paused) return this;
});
var vids = $(".player:first");
if (vids.length) return vids[0];
}
shortcut.add("Ctrl+Shift+Down", function () {
if (currentTextArea) {
var player = firstPlayer();
if (player) {
var ct = $.timecode_fromsecs(player.currentTime, true);
$.insertAtCaret(currentTextArea, ct + " -->", true);
}
}
});
shortcut.add("Ctrl+Shift+Left", function () {
$(".player").each(function () {
this.currentTime = this.currentTime - 5;
});
});
shortcut.add("Ctrl+Shift+Right", function () {
$(".player").each(function () {
this.currentTime = this.currentTime + 5;
});
});
shortcut.add("Ctrl+Shift+Up", function () {
$(".player").each(function () {
var foo = this.paused ? this.play() : this.pause();
});
});
/////////////////////////
// LAYERS
$('div#tabs-2').aalayers({
selector: 'section.section1',
post_reorder: function(event, ui, settings) {
var $this = settings.$container;
$this.find('li')
.reverse()
.each(function(i) {
var target = $(this).find('a').attr('href');
$(target).css('z-index', i);
post_styles($(target), 'style');
});
},
post_toggle: function(event, settings, target) {
target.toggle();
post_styles(target, 'style');
},
});
/////////////////////
// LAYOUT
// FIXME: is it really necessary to set enableCursorHotKey for each
// sidebar?
$("nav#east-pane").tabs();
$('body').layout({
applyDefaultStyles: false,
enableCursorHotkey: false,
east: {
size: 360,
fxSpeed: "slow",
initClosed: true,
enableCursorHotkey: false,
},
south: {
fxName: "slide",
fxSpeed: "slow",
size: 200,
initClosed: true,
enableCursorHotkey: false,
}
});
$("a[title='add']:first").click(function() {
var elt = $('<section><h1>New</h1></section>').addClass('section1').attr('data-section', '-1');
$('article').append(elt);
elt.trigger('refresh').trigger('edit');
});
$("a[title='commit']:first").click(function() {
var message = window.prompt("Summary", "A nice configuration");
if (message) {
$.get("flag/", {
message: "[LAYOUT] " + message,
});
};
});
});
})(jQuery);
//$(document).ready(function() {
//var gutter = 20;
//var width = 200;
//var height= 200;
//var margin = 20;
//console.log($(window).width());
//$('<div></div>').addClass('foo grid').css({
//position: 'absolute',
//top: margin,
//left: margin,
//bottom: margin,
//right: margin,
////backgroundColor: 'blue',
//}).appendTo($('body'));
//var max_column = Math.floor($('.foo').width() / (width + gutter));
//var max_row = Math.floor($('.foo').height() / (height + gutter));
//console.log(max_column);
//for (var i = 0; i < (max_column * max_row); i++) {
//var column = $('<div></div>').addClass('column grid').css({
//width: width,
//float: 'left',
//marginRight: gutter,
//height: "100%",
//border: "1px dotted red",
//height: height,
//marginBottom: gutter,
//}).appendTo('.foo');
//};
//});
| aacore/static/aacore/js/aa.view.js | function post_styles (elt, attr) {
/*
* Updates and posts the annotation style
*/
// RegExp
var HASH_HEADER_RE = /(^|\n)(#{1,2}[^#].*?)#*(\n|$)/;
var STYLE_ATTR_RE = /{:[^}]*}/;
var start;
var end;
var content = "";
var clone = $(elt).clone();
clone.removeClass('section1 section2 ui-droppable ui-draggable ui-resizable ui-draggable-dragging editing highlight');
clone.css({
'display': $(elt).is(":visible") ? "" : "none", // we only want to know if it is hidden or not
'position': '',
});
var $elt = clone;
var about = $.trim($elt.attr('about'));
var id = $.trim($elt.attr('id'));
var style = $.trim($elt.attr('style'));
var class_ = $.trim($elt.attr('class'));
var attr_list = "{: ";
if (about) attr_list += "about='" + about + "' ";
if (style) attr_list += "style='" + style + "' ";
if (class_) attr_list += "class='" + class_ + "' ";
attr_list += "}" ;
var style = attr_list;
var section = $(elt).attr("data-section");
$.get("edit/", {
section: section,
type: 'ajax',
}, function(data) {
// Searches for Header
var header_match = HASH_HEADER_RE.exec(data);
if (header_match) {
// Defines the substring to replace
var style_match = STYLE_ATTR_RE.exec(header_match[0]);
if (style_match) {
start = header_match.index + style_match.index;
end = start + style_match[0].length;
} else {
start = header_match.slice(1,3).join('').length;
end = start;
};
var before = data.substring(0, start);
var after = data.substring(end, data.length)
content = before + style + after;
$.post("edit/", {
content: content,
section: section,
type: 'ajax',
});
}
});
}
function resetTimelines() {
// RESET (ALL) TIMELINES
$(".player").each(function(){
var url = $(this).attr('src') || $("[src]:first", this).attr('src');
$(this).timeline({
show: function (elt) {
$(elt).addClass("active")
.closest('section.section1')
.find('div.wrapper:first')
.autoscrollable("scrollto", elt);
},
hide: function (elt) {
$(elt).removeClass("active");
},
start: function (elt) { return $(elt).attr('data-start') },
end: function (elt) { return $(elt).attr('data-end') }
}).timeline("add", 'section.section1[about="' + url + '"] *[data-start]');
});
}
(function($) {
var TEXTAREA_MIN_PADDING_BOTTOM = 40;
var currentTextArea = undefined; /* used for timecode pasting */
function ffind (selector, context) {
// "filter find", like $.find but it also checks the context element itself
return $(context).filter(selector).add(selector, context);
}
// The refresh event gets fired on body initially
// then on any <section> or other dynamically loaded/created element to "activate" it
$(document).bind("refresh", function (evt) {
//console.log("refreshing", evt.target);
var context = evt.target;
// Draggable Sections
$("section.section1").draggable({
handle: 'h1',
delay: 100, // avoids unintentional dragging when (un)collpasing
stop: function () { post_styles(this, 'style') }
}).resizable({
stop: function () { post_styles(this, 'style') }
});
// RENUMBER ALL SECTIONS
$("section:not([data-section='-1'])").each(function (i) {
$(this).attr("data-section", (i+1));
});
// SECTION EDIT LINKS
// Create & insert edit links in every section's Header that trigger the section's "edit" event
ffind('section', context).each(function () {
$("<span>✎</span>").addClass("section_edit_link").click(function () {
$(this).closest("section").trigger("edit");
}).prependTo($(":header:first", this));
var about = $(this).closest("section.section1").attr('about');
$("<span>@</span>").addClass("about").hover(function () {
$('.player[src="' + about + '"], section[about="' + about + '"]').addClass('highlight');
}, function() {
$('.player[src="' + about + '"], section[about="' + about + '"]').removeClass('highlight');
}).prependTo($("h1:first", this));
$(this).children("h1").bind('dblclick', function(e) {
var section = $(this).closest("section");
if (!section.hasClass('editing')) {
section.trigger("collapse");
};
});
var nonhead = $(this).children(":not(:header)");
var wrapped = $("<div class=\"wrapper\"></div>").append(nonhead);
$(this).append(wrapped);
})
// IN-PLACE EDITING
ffind('section', context).bind("collapse", function (evt) {
$(this).toggleClass('collapsed');
post_styles(this, 'class');
})
ffind('section', context).bind("edit", function (evt) {
function edit (data) {
var position = $(that).css("position");
var section_height = Math.min($(window).height() - 28, $(that).height());
var use_height = (position == "absolute") ? section_height : section_height;
var f = $("<div></div>").addClass("section_edit").appendTo(that);
var textarea = $("<textarea></textarea>").css({height: use_height+"px"}).text(data).appendTo(f);
$(that).addClass("editing");
var ok = $("<span>✔</span>").addClass("section_save_link").click(function () {
// console.log("commencing section edit save...");
$.ajax("edit/", {
type: 'post',
data: {
section: $(that).attr("data-section"),
type: 'ajax',
content: textarea.val()
},
success: function (data) {
// console.log("resetting contents of section to: ", data);
var new_content = $(data);
$(that).replaceWith(new_content);
new_content.trigger("refresh");
}
});
}).appendTo($(that).find(':header:first'));
$("<span>✘</span>").addClass("section_cancel_link").click(function () {
// console.log("cancelling section edit save...");
if (new_section) {
// removes the annotation
$(that).remove();
$(this).remove();
ok.remove();
} else {
f.remove();
$(this).remove();
ok.remove();
$(that).removeClass("editing");
}
}).appendTo($(that).find(':header:first'));
}
evt.stopPropagation();
var that = this;
var new_section = false;
if ($(this).attr('data-section') == "-1") {
new_section = true;
edit("# New section");
} else {
$.ajax("edit/", {
data: {
section: $(this).attr("data-section"),
type: 'ajax'
},
success: edit,
});
}
});
// end of IN-PLACE EDITING
/* Connect players to timed sections */
resetTimelines();
/// CLICKABLE TIMECODES
$('span[property="aa:start"],span[property="aa:end"]', context).bind("click", function () {
var t = $.timecode_tosecs_attr($(this).attr("content"));
var about = $(this).parents('*[about]').attr('about');
var player = $('[src="' + about + '"]')[0]
|| $('source[src="' + about + '"]').parent('.player')[0];
if (player) {
player.currentTime = t;
player.play();
}
});
$("span.swatch", context).each(function () {
$(this).draggable({helper: function () {
var $this = $(this);
var $clone = $(this).clone();
$clone.find('select:first').val($this.find('select:first').val());
return $clone.appendTo("body");
}});
});
ffind("section.section2", context).droppable({
accept: ".swatch",
hoverClass: "drophover",
drop: function (evt, ui) {
var $select = $(ui.helper).find('select');
var key = $select.attr("name");
var value = $select.find('option:selected').val();
var s1 = $(this).closest(".section2");
s1.css(key, value);
post_styles(s1, 'style');
}
});
ffind("section.section1", context).droppable({
accept: ".swatch",
hoverClass: "drophover",
drop: function (evt, ui) {
var $select = $(ui.helper).find('select');
var key = $select.attr("name");
var value = $select.find('option:selected').val();
var s1 = $(this).closest(".section1");
s1.css(key, value);
post_styles(s1, 'style');
}
});
});
$(document).ready(function() {
/* INIT */
$(document).trigger("refresh");
/////////////////////
/////////////////////
/////////////////////
// Once-only page inits
$("section.section1 > div.wrapper").autoscrollable();
//$("section.section1").autoscrollable();
/////////////////////////
// SHORTCUTS
// maintain variable currentTextArea
$("section textarea").live("focus", function () {
currentTextArea = this;
}).live("blur", function () {
currentTextArea = undefined;
});
function firstPlayer () {
/*
* returns first playing player (unwrapped) element (if one is playing),
* or just first player otherwise
*/
$(".player").each(function () {
if (!this.paused) return this;
});
var vids = $(".player:first");
if (vids.length) return vids[0];
}
shortcut.add("Ctrl+Shift+Down", function () {
if (currentTextArea) {
var player = firstPlayer();
if (player) {
var ct = $.timecode_fromsecs(player.currentTime, true);
$.insertAtCaret(currentTextArea, ct + " -->", true);
}
}
});
shortcut.add("Ctrl+Shift+Left", function () {
$(".player").each(function () {
this.currentTime = this.currentTime - 5;
});
});
shortcut.add("Ctrl+Shift+Right", function () {
$(".player").each(function () {
this.currentTime = this.currentTime + 5;
});
});
shortcut.add("Ctrl+Shift+Up", function () {
$(".player").each(function () {
var foo = this.paused ? this.play() : this.pause();
});
});
/////////////////////////
// LAYERS
$('div#tabs-2').aalayers({
selector: 'section.section1',
post_reorder: function(event, ui, settings) {
var $this = settings.$container;
$this.find('li')
.reverse()
.each(function(i) {
var target = $(this).find('a').attr('href');
$(target).css('z-index', i);
post_styles($(target), 'style');
});
},
post_toggle: function(event, settings, target) {
target.toggle();
post_styles(target, 'style');
},
});
/////////////////////
// LAYOUT
// FIXME: is it really necessary to set enableCursorHotKey for each
// sidebar?
$("nav#east-pane").tabs();
$('body').layout({
applyDefaultStyles: false,
enableCursorHotkey: false,
east: {
size: 360,
fxSpeed: "slow",
initClosed: true,
enableCursorHotkey: false,
},
south: {
fxName: "slide",
fxSpeed: "slow",
size: 200,
initClosed: true,
enableCursorHotkey: false,
}
});
$("a[title='add']:first").click(function() {
var elt = $('<section><h1>New</h1></section>').addClass('section1').attr('data-section', '-1');
$('article').append(elt);
elt.trigger('refresh').trigger('edit');
});
$("a[title='commit']:first").click(function() {
var message = window.prompt("Summary", "A nice configuration");
if (message) {
$.get("flag/", {
message: "[LAYOUT] " + message,
});
};
});
});
})(jQuery);
| Added a class to the list of classes to exclude from persistence
| aacore/static/aacore/js/aa.view.js | Added a class to the list of classes to exclude from persistence | <ide><path>acore/static/aacore/js/aa.view.js
<ide> var content = "";
<ide>
<ide> var clone = $(elt).clone();
<del> clone.removeClass('section1 section2 ui-droppable ui-draggable ui-resizable ui-draggable-dragging editing highlight');
<add> clone.removeClass('section1 section2 ui-droppable ui-draggable ui-resizable ui-draggable-dragging editing highlight drophover');
<ide> clone.css({
<ide> 'display': $(elt).is(":visible") ? "" : "none", // we only want to know if it is hidden or not
<ide> 'position': '',
<ide> // Draggable Sections
<ide> $("section.section1").draggable({
<ide> handle: 'h1',
<del> delay: 100, // avoids unintentional dragging when (un)collpasing
<del> stop: function () { post_styles(this, 'style') }
<add> //delay: 100, // avoids unintentional dragging when (un)collpasing
<add> //cursorAt: { left: 0, top: 0, },
<add> snap: ".grid",
<add> snapTolerance: 5,
<add> stop: function () {
<add> var position = $(this).position();
<add> if (position.top < 0) {
<add> $(this).css('top', '0px');
<add> };
<add> if (position.left < 0) {
<add> $(this).css('left', '0px');
<add> };
<add> post_styles(this, 'style');
<add> },
<add> //drag: function (e) {
<add> //if (e.ctrlKey == true) {
<add> //$(this).draggable('option', 'grid', [20, 20]);
<add> //} else {
<add> //$(this).draggable('option', 'grid', false);
<add> //}
<add> //}
<ide> }).resizable({
<del> stop: function () { post_styles(this, 'style') }
<add> stop: function () { post_styles(this, 'style') },
<add> snap: ".grid",
<ide> });
<ide>
<ide> // RENUMBER ALL SECTIONS
<ide>
<ide> });
<ide> })(jQuery);
<add>
<add>
<add>//$(document).ready(function() {
<add>//var gutter = 20;
<add>//var width = 200;
<add>//var height= 200;
<add>//var margin = 20;
<add>
<add>//console.log($(window).width());
<add>
<add>//$('<div></div>').addClass('foo grid').css({
<add> //position: 'absolute',
<add> //top: margin,
<add> //left: margin,
<add> //bottom: margin,
<add> //right: margin,
<add> ////backgroundColor: 'blue',
<add>//}).appendTo($('body'));
<add>
<add>
<add>//var max_column = Math.floor($('.foo').width() / (width + gutter));
<add>//var max_row = Math.floor($('.foo').height() / (height + gutter));
<add>//console.log(max_column);
<add>//for (var i = 0; i < (max_column * max_row); i++) {
<add> //var column = $('<div></div>').addClass('column grid').css({
<add> //width: width,
<add> //float: 'left',
<add> //marginRight: gutter,
<add> //height: "100%",
<add> //border: "1px dotted red",
<add> //height: height,
<add> //marginBottom: gutter,
<add> //}).appendTo('.foo');
<add>//};
<add>//}); |
|
JavaScript | mit | 7f773f49fa1531bc64712d5e1ab1bc94ba7f8bfa | 0 | amyzou/RubeWorks,amyzou/RubeWorks | /* mainGrid
*
* while making list, needs to check for :
* object type
*
* when animating, keeps running object state
*/
/*-----------------Main RubJect Controller Class-----------------*/
/*
Workflow:
1. Add starting objects with the method; this puts the starting objects on a list
so we keep track of starting points. What we
2. When the person switches to run mode, iterate through all starting objects,
create chain for all, append freefalls when needed in this stage
//Todo: a function that adds freefall onto things if applicable
//todo: make lazy updates: only update runlist when there are changes between now and then
*/
function RubeJectController(){
var objectList = new Array();
var objectCounter = 0;
var startingObjectList = new Array();
var startingObjectCounter = 0;
var PlaceObjectIntoSpace = function(objectID){
//retrieve blocklist for object and then add it
}
var RemoveObjectFromSpace = function(objectID){
//delete object from space grid
}
//method to add object
this.AddObject = function(RubeJect, IsStartingObject){
this.objectList[objectCounter] = RubeJect;
//occupy space on mainGrid
if (IsStartingObject)
{
startingObjectList[startingObjectCounter] = new Array();
startingObjectList[startingObjectCounter][0] = objectCounter;
startingObjectCounter ++;
}
objectCounter ++;
};
this.ModifyObject_Delete = function(objectID){
//todo: add null checks everywhere for if an object is deleted
RemoveObjectFromSpace(objectID);
}
this.ModifyObject_Move = function(objectID, newLocation){
//todo
RemoveObjectFromSpace(objectID);
}
this.ModifyObject_Rotate = function(objectID, newRotation){
//todo
RemoveObjectFromSpace(objectID);
//ask to rotate
}
//method for chaining - used recursively
var CreateChainLink = function(list, currPosInList){
//obtain outface
//obtain infaces of objects next to outface
//match up, put down link, and call create chain on the next object
//if none, free fall to last place
};
//method to create chains in run mode
this.CreateChains = function(){
for (var i = 0; i < startingObjectCounter; i++)
{
CreateChainLink(startingObjectList[i], 0);
}
};
/*-----------------For testing purposes-----------------*/
this.PrintAllObjects = function(){
for (var i = 0; i <objectCounter; i++)
{
console.log("Object " + i + " is a(n) " + objectList[i].name );
}
};
this.PrintAllStartingObjects = function(){
for (var i = 0; i <startingObjectCounter; i++)
{
console.log("Starting Object " + i + " is a(n) " + startingObjectList[i][0].name );
}
};
this.PrintAllChains = function(){
for (var i = 0; i <startingObjectCounter; i++)
{
console.log("Chain " + i);
console.log("Starting Object " + i + " is a(n) " + startingObjectList[i][0].name );
for (var k = 1, len = startingObjectList[i].len; k < len; k++ )
{
console.log("The " + k + "th object is a(n) " + startingObjectList[i][k].name );
}
}
};
}
| app/assets/javascripts/controller.js | /* contoller creates linked list by:
* objectID
*
* while making list, needs to check for :
* object type
*
* when animating, keeps running object state
*/
/*-----------------Main RubJect Controller Class-----------------*/
/*
Workflow:
1. Add starting objects with the method; this puts the starting objects on a list
so we keep track of starting points. What we
2. When the person switches to run mode, iterate through all starting objects,
create chain for all, append freefalls when needed in this stage
//Todo: a function that adds freefall onto things if applicable
//todo: make lazy updates: only update runlist when there are changes between now and then
*/
function RubeJectController(){
var objectList = new Array();
var objectCounter = 0;
var startingObjectList = new Array();
var startingObjectCounter = 0;
//todo: finish 3d gridspace tracking
var objectGrid = new Array();
objectGrid[0] = new Array();
//method to add object
this.AddObject = function(RubeJect, IsStartingObject){
this.objectList[objectCounter] = RubeJect;
//occupy space here
if (IsStartingObject)
{
startingObjectList[startingObjectCounter] = new Array();
startingObjectList[startingObjectCounter][0] = objectCounter;
startingObjectCounter ++;
}
objectCounter ++;
};
//method for chaining - used recursively
var CreateChainLink = function(list, currPosInList){
//obtain outface
//obtain infaces of objects next to outface
//match up, put down link, and call create chain on the next object
//if none, free fall to last place
};
//method to create chains in run mode
this.CreateChains = function(){
for (var i = 0; i < startingObjectCounter; i++)
{
CreateChainLink(startingObjectList[i], 0);
}
};
/*-----------------For testing purposes-----------------*/
this.PrintAllObjects = function(){
for (var i = 0; i <objectCounter; i++)
{
console.log("Object " + i + " is a(n) " + objectList[i].name );
}
};
this.PrintAllStartingObjects = function(){
for (var i = 0; i <startingObjectCounter; i++)
{
console.log("Starting Object " + i + " is a(n) " + startingObjectList[i][0].name );
}
};
this.PrintAllChains = function(){
for (var i = 0; i <startingObjectCounter; i++)
{
console.log("Chain " + i);
console.log("Starting Object " + i + " is a(n) " + startingObjectList[i][0].name );
for (var k = 1, len = startingObjectList[i].len; k < len; k++ )
{
console.log("The " + k + "th object is a(n) " + startingObjectList[i][k].name );
}
}
};
}
| misc controller stuffs
| app/assets/javascripts/controller.js | misc controller stuffs | <ide><path>pp/assets/javascripts/controller.js
<del> /* contoller creates linked list by:
<del> * objectID
<add> /* mainGrid
<ide> *
<ide> * while making list, needs to check for :
<ide> * object type
<ide> var startingObjectList = new Array();
<ide> var startingObjectCounter = 0;
<ide>
<del> //todo: finish 3d gridspace tracking
<del> var objectGrid = new Array();
<del> objectGrid[0] = new Array();
<add> var PlaceObjectIntoSpace = function(objectID){
<add> //retrieve blocklist for object and then add it
<add> }
<add>
<add> var RemoveObjectFromSpace = function(objectID){
<add> //delete object from space grid
<add> }
<ide>
<ide> //method to add object
<ide> this.AddObject = function(RubeJect, IsStartingObject){
<ide> this.objectList[objectCounter] = RubeJect;
<del> //occupy space here
<add> //occupy space on mainGrid
<ide>
<ide> if (IsStartingObject)
<ide> {
<ide> }
<ide> objectCounter ++;
<ide> };
<add>
<add> this.ModifyObject_Delete = function(objectID){
<add> //todo: add null checks everywhere for if an object is deleted
<add> RemoveObjectFromSpace(objectID);
<add> }
<add>
<add> this.ModifyObject_Move = function(objectID, newLocation){
<add> //todo
<add> RemoveObjectFromSpace(objectID);
<add> }
<add>
<add> this.ModifyObject_Rotate = function(objectID, newRotation){
<add> //todo
<add> RemoveObjectFromSpace(objectID);
<add> //ask to rotate
<add>
<add> }
<ide>
<ide> //method for chaining - used recursively
<ide> var CreateChainLink = function(list, currPosInList){ |
|
Java | apache-2.0 | 22c45e10a2bb9c21a25a353a585b173700b46dd4 | 0 | cdljsj/cat,xiaojiaqi/cat,jialinsun/cat,TonyChai24/cat,wyzssw/cat,unidal/cat,cdljsj/cat,unidal/cat,gspandy/cat,wuqiangxjtu/cat,xiaojiaqi/cat,howepeng/cat,itnihao/cat,gspandy/cat,dadarom/cat,howepeng/cat,wuqiangxjtu/cat,unidal/cat,javachengwc/cat,wuqiangxjtu/cat,ddviplinux/cat,chqlb/cat,wyzssw/cat,wuqiangxjtu/cat,ddviplinux/cat,itnihao/cat,dadarom/cat,xiaojiaqi/cat,unidal/cat,javachengwc/cat,xiaojiaqi/cat,itnihao/cat,gspandy/cat,dadarom/cat,bryanchou/cat,jialinsun/cat,cdljsj/cat,JacksonSha/cat,chqlb/cat,chqlb/cat,howepeng/cat,dianping/cat,wuqiangxjtu/cat,redbeans2015/cat,JacksonSha/cat,dadarom/cat,jialinsun/cat,dadarom/cat,bryanchou/cat,chqlb/cat,chinaboard/cat,wuqiangxjtu/cat,unidal/cat,michael8335/cat,JacksonSha/cat,michael8335/cat,xiaojiaqi/cat,ddviplinux/cat,TonyChai24/cat,JacksonSha/cat,dadarom/cat,TonyChai24/cat,xiaojiaqi/cat,javachengwc/cat,ddviplinux/cat,TonyChai24/cat,gspandy/cat,bryanchou/cat,dianping/cat,javachengwc/cat,JacksonSha/cat,TonyChai24/cat,dianping/cat,ddviplinux/cat,bryanchou/cat,redbeans2015/cat,michael8335/cat,cdljsj/cat,dianping/cat,redbeans2015/cat,jialinsun/cat,dianping/cat,redbeans2015/cat,michael8335/cat,javachengwc/cat,chinaboard/cat,gspandy/cat,chinaboard/cat,redbeans2015/cat,bryanchou/cat,chqlb/cat,cdljsj/cat,TonyChai24/cat,chinaboard/cat,howepeng/cat,wyzssw/cat,javachengwc/cat,redbeans2015/cat,JacksonSha/cat,cdljsj/cat,howepeng/cat,howepeng/cat,chinaboard/cat,itnihao/cat,dianping/cat,chqlb/cat,chinaboard/cat,bryanchou/cat,wyzssw/cat,jialinsun/cat,michael8335/cat,ddviplinux/cat,itnihao/cat,dianping/cat,gspandy/cat,michael8335/cat,wyzssw/cat,itnihao/cat,jialinsun/cat,wyzssw/cat,unidal/cat | package com.dianping.cat.system.page.config;
public enum JspFile {
PROJECT_ALL("/jsp/system/project/project.jsp"),
PROJECT_UPATE("/jsp/system/project/projectUpdate.jsp"),
AGGREGATION_ALL("/jsp/system/aggregation/aggregation.jsp"),
AGGREGATION_UPATE("/jsp/system/aggregation/aggregationUpdate.jsp"),
URL_PATTERN_ALL("/jsp/system/urlPattern/urlPattern.jsp"),
URL_PATTERN_UPATE("/jsp/system/urlPattern/urlPatternUpdate.jsp"),
TOPOLOGY_GRAPH_NODE_CONFIG_ADD_OR_UPDATE("/jsp/system/topology/topologyGraphNodeConfigAdd.jsp"),
TOPOLOGY_GRAPH_NODE_CONFIG_LIST("/jsp/system/topology/topologyGraphNodeConfigs.jsp"),
TOPOLOGY_GRAPH_EDGE_CONFIG_ADD_OR_UPDATE("/jsp/system/topology/topologyGraphEdgeConfigAdd.jsp"),
TOPOLOGY_GRAPH_EDGE_CONFIG_LIST("/jsp/system/topology/topologyGraphEdgeConfigs.jsp"),
TOPOLOGY_GRAPH_PRODUCT_LINE("/jsp/system/productLine/topologyProductLines.jsp"),
TOPOLOGY_GRAPH_PRODUCT_ADD_OR_UPDATE("/jsp/system/productLine/topologyProductLineAdd.jsp"),
METRIC_CONFIG_ADD_OR_UPDATE("/jsp/system/metric/metricConfigAdd.jsp"),
METRIC_CONFIG_ADD_OR_UPDATE_SUBMIT("/jsp/system/metric/metricConfigs.jsp"),
METRIC_CONFIG_LIST("/jsp/system/metric/metricConfigs.jsp"),
METRIC_RULE_CONFIG_UPDATE("/jsp/system/metricRule/metricRuleConfig.jsp"),
EXCEPTION_THRESHOLD("/jsp/system/exceptionThreshold/exceptionThreshold.jsp"),
EXCEPTION_THRESHOLD_CONFIG("/jsp/system/exceptionThreshold/exceptionThresholdConfig.jsp"),
BUG_CONFIG_UPDATE("/jsp/system/bug/bugConfig.jsp"),
UTILIZATION_CONFIG_UPDATE("/jsp/system/utilization/utilizationConfig.jsp"),
DOMAIN_GROUP_CONFIG_UPDATE("/jsp/system/domainGroup/domainGroupConfig.jsp"),
METRIC_GROUP_CONFIG_UPDATE("/jsp/system/metricGroup/metricGroupConfig.jsp"),
METRIC_AGGREGATION_CONFIG_UPDATE("/jsp/system/metricAggregation/metricAggregationConfig.jsp");
private String m_path;
private JspFile(String path) {
m_path = path;
}
public String getPath() {
return m_path;
}
}
| cat-home/src/main/java/com/dianping/cat/system/page/config/JspFile.java | package com.dianping.cat.system.page.config;
public enum JspFile {
PROJECT_ALL("/jsp/system/project/project.jsp"),
PROJECT_UPATE("/jsp/system/project/projectUpdate.jsp"),
AGGREGATION_ALL("/jsp/system/aggregation/aggregation.jsp"),
AGGREGATION_UPATE("/jsp/system/aggregation/aggregationUpdate.jsp"),
URL_PATTERN_ALL("/jsp/system/urlPattern/urlPattern.jsp"),
URL_PATTERN_UPATE("/jsp/system/urlPattern/urlPatternUpdate.jsp"),
TOPOLOGY_GRAPH_NODE_CONFIG_ADD_OR_UPDATE("/jsp/system/topology/topologyGraphNodeConfigAdd.jsp"),
TOPOLOGY_GRAPH_NODE_CONFIG_LIST("/jsp/system/topology/topologyGraphNodeConfigs.jsp"),
TOPOLOGY_GRAPH_EDGE_CONFIG_ADD_OR_UPDATE("/jsp/system/topology/topologyGraphEdgeConfigAdd.jsp"),
TOPOLOGY_GRAPH_EDGE_CONFIG_LIST("/jsp/system/topology/topologyGraphEdgeConfigs.jsp"),
TOPOLOGY_GRAPH_PRODUCT_LINE("/jsp/system/productLine/topologyProductLines.jsp"),
TOPOLOGY_GRAPH_PRODUCT_ADD_OR_UPDATE("/jsp/system/productLine/topologyProductLineAdd.jsp"),
METRIC_CONFIG_ADD_OR_UPDATE("/jsp/system/metric/metricConfigAdd.jsp"),
METRIC_CONFIG_ADD_OR_UPDATE_SUBMIT("/jsp/system/metric/metricConfigs.jsp"),
METRIC_CONFIG_LIST("/jsp/system/metric/metricConfigs.jsp"),
METRIC_RULE_CONFIG_UPDATE("/jsp/system/metricRule/metricRuleConfig.jsp"),
EXCEPTION_THRESHOLD("/jsp/system/exception/exceptionThreshold.jsp"),
EXCEPTION_THRESHOLD_CONFIG("/jsp/system/exception/exceptionThresholdConfig.jsp"),
BUG_CONFIG_UPDATE("/jsp/system/bug/bugConfig.jsp"),
UTILIZATION_CONFIG_UPDATE("/jsp/system/utilization/utilizationConfig.jsp"),
DOMAIN_GROUP_CONFIG_UPDATE("/jsp/system/domainGroup/domainGroupConfig.jsp"),
METRIC_GROUP_CONFIG_UPDATE("/jsp/system/metricGroup/metricGroupConfig.jsp"),
METRIC_AGGREGATION_CONFIG_UPDATE("/jsp/system/metricAggregation/metricAggregationConfig.jsp");
private String m_path;
private JspFile(String path) {
m_path = path;
}
public String getPath() {
return m_path;
}
}
| fix jsp config
| cat-home/src/main/java/com/dianping/cat/system/page/config/JspFile.java | fix jsp config | <ide><path>at-home/src/main/java/com/dianping/cat/system/page/config/JspFile.java
<ide>
<ide> METRIC_RULE_CONFIG_UPDATE("/jsp/system/metricRule/metricRuleConfig.jsp"),
<ide>
<del> EXCEPTION_THRESHOLD("/jsp/system/exception/exceptionThreshold.jsp"),
<add> EXCEPTION_THRESHOLD("/jsp/system/exceptionThreshold/exceptionThreshold.jsp"),
<ide>
<del> EXCEPTION_THRESHOLD_CONFIG("/jsp/system/exception/exceptionThresholdConfig.jsp"),
<add> EXCEPTION_THRESHOLD_CONFIG("/jsp/system/exceptionThreshold/exceptionThresholdConfig.jsp"),
<ide>
<ide> BUG_CONFIG_UPDATE("/jsp/system/bug/bugConfig.jsp"),
<ide> |
|
Java | epl-1.0 | 17c410ba6a378f062acb13e269d0ea94fa0d5aea | 0 | jenkinsci/coverity-plugin,jenkinsci/coverity-plugin,jenkinsci/coverity-plugin,jenkinsci/coverity-plugin | /*******************************************************************************
* Copyright (c) 2016 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
*******************************************************************************/
package jenkins.plugins.coverity;
import com.coverity.ws.v9.*;
import hudson.model.Hudson;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Represents one Coverity Integrity Manager server. Abstracts functions like getting streams and defects.
*/
public class CIMInstance {
public static final String COVERITY_V9_NAMESPACE = "http://ws.coverity.com/v9";
public static final String CONFIGURATION_SERVICE_V9_WSDL = "/ws/v9/configurationservice?wsdl";
public static final String DEFECT_SERVICE_V9_WSDL = "/ws/v9/defectservice?wsdl";
/**
* Pattern to ignore streams - this is used to filter out internal DA streams, which are irrelevant to this plugin
*/
public static final String STREAM_NAME_IGNORE_PATTERN = "__internal_.*";
/**
* The id for this instance, used as a key in CoverityPublisher
*/
private final String name;
/**
* The host name for the CIM server
*/
private final String host;
/**
* The port for the CIM server (this is the HTTP port and not the data port)
*/
private final int port;
/**
* The commit port for the CIM server. This is only for cov-commit-defects.
*/
private final int dataPort;
/**
* Username for connecting to the CIM server
*/
private final String user;
/**
* Password for connecting to the CIM server
*/
private final String password;
/**
* Use SSL
*/
private final boolean useSSL;
/**
* cached webservice port for Defect service
*/
private transient DefectServiceService defectServiceService;
/**
* cached webservice port for Configuration service
*/
private transient ConfigurationServiceService configurationServiceService;
@DataBoundConstructor
public CIMInstance(String name, String host, int port, String user, String password, boolean useSSL, int dataPort) {
this.name = name;
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.useSSL = useSSL;
this.dataPort = dataPort;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getName() {
return name;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public boolean isUseSSL() {
return useSSL;
}
public int getDataPort() {
return dataPort;
}
/**
* The root URL for the CIM instance
*
* @return a url
* @throws MalformedURLException should not happen if host is valid
*/
public URL getURL() throws MalformedURLException {
return new URL(isUseSSL() ? "https" : "http", host, port, "/");
}
/**
* Returns a Defect service client using v9 web services.
*/
public DefectService getDefectService() throws IOException {
synchronized(this) {
if(defectServiceService == null) {
defectServiceService = new DefectServiceService(
new URL(getURL(), DEFECT_SERVICE_V9_WSDL),
new QName(COVERITY_V9_NAMESPACE, "DefectServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
DefectService defectService = defectServiceService.getDefectServicePort();
attachAuthenticationHandler((BindingProvider) defectService);
return defectService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
/**
* Attach an authentication handler to the web service, that uses the configured user and password
*/
private void attachAuthenticationHandler(BindingProvider service) {
service.getBinding().setHandlerChain(Arrays.<Handler>asList(new ClientAuthenticationHandlerWSS(user, password)));
}
/**
* Returns a Configuration service client using v9 web services.
*/
public ConfigurationService getConfigurationService() throws IOException {
synchronized(this) {
if(configurationServiceService == null) {
// Create a Web Services port to the server
configurationServiceService = new ConfigurationServiceService(
new URL(getURL(), CONFIGURATION_SERVICE_V9_WSDL),
new QName(COVERITY_V9_NAMESPACE, "ConfigurationServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
ConfigurationService configurationService = configurationServiceService.getConfigurationServicePort();
attachAuthenticationHandler((BindingProvider) configurationService);
return configurationService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
public List<MergedDefectDataObj> getDefects(String streamId, List<Long> defectIds) throws IOException, CovRemoteServiceException_Exception {
MergedDefectFilterSpecDataObj filterSpec = new MergedDefectFilterSpecDataObj();
StreamIdDataObj stream = new StreamIdDataObj();
stream.setName(streamId);
List<StreamIdDataObj> streamList = new ArrayList<StreamIdDataObj>();
streamList.add(stream);
PageSpecDataObj pageSpec = new PageSpecDataObj();
pageSpec.setPageSize(2500);
SnapshotScopeSpecDataObj snapshotScopeSpecDataObj = new SnapshotScopeSpecDataObj();
List<MergedDefectDataObj> result = new ArrayList<MergedDefectDataObj>();
int defectCount = 0;
MergedDefectsPageDataObj defects = null;
do {
pageSpec.setStartIndex(defectCount);
defects = getDefectService().getMergedDefectsForStreams(streamList, filterSpec, pageSpec, snapshotScopeSpecDataObj);
for(MergedDefectDataObj defect : defects.getMergedDefects()) {
if(defectIds.contains(defect.getCid())) {
result.add(defect);
}
}
defectCount += defects.getMergedDefects().size();
} while(defectCount < defects.getTotalNumberOfRecords());
return result;
}
public ProjectDataObj getProject(String projectId) throws IOException, CovRemoteServiceException_Exception {
ProjectFilterSpecDataObj filterSpec = new ProjectFilterSpecDataObj();
filterSpec.setNamePattern(projectId);
List<ProjectDataObj> projects = getConfigurationService().getProjects(filterSpec);
if(projects.size() == 0) {
return null;
} else {
return projects.get(0);
}
}
private transient Map<String, Long> projectKeys;
public Long getProjectKey(String projectId) throws IOException, CovRemoteServiceException_Exception {
if(projectKeys == null) {
projectKeys = new ConcurrentHashMap<String, Long>();
}
Long result = projectKeys.get(projectId);
if(result == null) {
result = getProject(projectId).getProjectKey();
projectKeys.put(projectId, result);
}
return result;
}
public List<ProjectDataObj> getProjects() throws IOException, CovRemoteServiceException_Exception {
return getConfigurationService().getProjects(new ProjectFilterSpecDataObj());
}
public List<StreamDataObj> getStaticStreams(String projectId) throws IOException, CovRemoteServiceException_Exception {
/*
to get a list of all static streams for one project,
- get a list of streams for the project
- get a list of all static streams
- compute the intersection
there should be a better way, but I can't see it.
you can't filter on project, and StreamDataObj does not have project or type information
*/
ProjectDataObj project = getProject(projectId);
List<StreamDataObj> result = new ArrayList<StreamDataObj>();
if (project != null){
for(StreamDataObj stream : project.getStreams()) {
if(!stream.getId().getName().matches(STREAM_NAME_IGNORE_PATTERN)) {
result.add(stream);
}
}
}
return result;
}
/**
* Returns a StreamDataObj for a given streamId. This object must be not null in order to avoid null pointer exceptions.
* If the stream is not found an exception explaining the issue is raised.
*/
public StreamDataObj getStream(String streamId) throws IOException, CovRemoteServiceException_Exception {
StreamFilterSpecDataObj filter = new StreamFilterSpecDataObj();
filter.setNamePattern(streamId);
List<StreamDataObj> streams = getConfigurationService().getStreams(filter);
if(streams == null || streams.isEmpty()) {
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
StreamDataObj streamDataObj = streams.get(0);
if(streamDataObj == null){
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
return streams.get(0);
}
}
}
public FormValidation doCheck() throws IOException {
try {
URL url = getURL();
int responseCode = getURLResponseCode(new URL(url, CONFIGURATION_SERVICE_V9_WSDL));
if(responseCode != 200) {
return FormValidation.error("Connected successfully, but Coverity web services were not detected.");
}
getConfigurationService().getServerTime();
if (!checkUserPermission()){
return FormValidation.error("\"" + user + "\" does not enough permission!");
}
return FormValidation.ok("Successfully connected to the instance.");
} catch(UnknownHostException e) {
return FormValidation.error("Host name unknown");
} catch(ConnectException e) {
return FormValidation.error("Connection refused");
} catch(SocketException e) {
return FormValidation.error("Error connecting to CIM. Please check your connection settings.");
} catch(Throwable e) {
String javaVersion = System.getProperty("java.version");
if(javaVersion.startsWith("1.6.0_")) {
int patch = Integer.parseInt(javaVersion.substring(javaVersion.indexOf('_') + 1));
if(patch < 26) {
return FormValidation.error(e, "Please use Java 1.6.0_26 or later to run Jenkins.");
}
}
return FormValidation.error(e, "An unexpected error occurred.");
}
}
private FormValidation error(Throwable t) {
if(Hudson.getInstance().hasPermission(Hudson.ADMINISTER)) {
return FormValidation.error(t, t.getMessage());
} else {
return FormValidation.error(t.getMessage());
}
}
private int getURLResponseCode(URL url) throws IOException {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
conn.getInputStream();
return conn.getResponseCode();
} catch(FileNotFoundException e) {
return 404;
}
}
public String getCimInstanceCheckers() {
List<String> checkers = new ArrayList<String>();
try {
checkers.addAll(this.getConfigurationService().getCheckerNames());
} catch(Exception e) {
}
Collections.sort(checkers);
return StringUtils.join(checkers, '\n');
}
private boolean checkUserPermission() throws IOException, com.coverity.ws.v9.CovRemoteServiceException_Exception{
boolean canCommit = false;
boolean canAccessWs = false;
boolean canViewIssues = false;
UserDataObj userData = getConfigurationService().getUser(user);
if (userData != null){
if (userData.isSuperUser()){
return true;
}
for (RoleAssignmentDataObj role : userData.getRoleAssignments()){
RoleDataObj roleData = getConfigurationService().getRole(role.getRoleId());
if (roleData != null){
for (PermissionDataObj permission : roleData.getPermissionDataObjs()){
if (permission.getPermissionValue().equalsIgnoreCase("commitToStream")){
canCommit = true;
} else if (permission.getPermissionValue().equalsIgnoreCase("accessWS")){
canAccessWs = true;
} else if (permission.getPermissionValue().equalsIgnoreCase("viewDefects")){
canViewIssues = true;
}
if (canCommit && canAccessWs && canViewIssues){
return true;
}
}
}
}
}
return false;
}
}
| src/main/java/jenkins/plugins/coverity/CIMInstance.java | /*******************************************************************************
* Copyright (c) 2016 Synopsys, Inc
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Synopsys, Inc - initial implementation and documentation
*******************************************************************************/
package jenkins.plugins.coverity;
import com.coverity.ws.v9.*;
import hudson.model.Hudson;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Represents one Coverity Integrity Manager server. Abstracts functions like getting streams and defects.
*/
public class CIMInstance {
public static final String COVERITY_V9_NAMESPACE = "http://ws.coverity.com/v9";
public static final String CONFIGURATION_SERVICE_V9_WSDL = "/ws/v9/configurationservice?wsdl";
public static final String DEFECT_SERVICE_V9_WSDL = "/ws/v9/defectservice?wsdl";
/**
* Pattern to ignore streams - this is used to filter out internal DA streams, which are irrelevant to this plugin
*/
public static final String STREAM_NAME_IGNORE_PATTERN = "__internal_.*";
/**
* The id for this instance, used as a key in CoverityPublisher
*/
private final String name;
/**
* The host name for the CIM server
*/
private final String host;
/**
* The port for the CIM server (this is the HTTP port and not the data port)
*/
private final int port;
/**
* The commit port for the CIM server. This is only for cov-commit-defects.
*/
private final int dataPort;
/**
* Username for connecting to the CIM server
*/
private final String user;
/**
* Password for connecting to the CIM server
*/
private final String password;
/**
* Use SSL
*/
private final boolean useSSL;
/**
* cached webservice port for Defect service
*/
private transient DefectServiceService defectServiceService;
/**
* cached webservice port for Configuration service
*/
private transient ConfigurationServiceService configurationServiceService;
@DataBoundConstructor
public CIMInstance(String name, String host, int port, String user, String password, boolean useSSL, int dataPort) {
this.name = name;
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.useSSL = useSSL;
this.dataPort = dataPort;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getName() {
return name;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public boolean isUseSSL() {
return useSSL;
}
public int getDataPort() {
return dataPort;
}
/**
* The root URL for the CIM instance
*
* @return a url
* @throws MalformedURLException should not happen if host is valid
*/
public URL getURL() throws MalformedURLException {
return new URL(isUseSSL() ? "https" : "http", host, port, "/");
}
/**
* Returns a Defect service client using v9 web services.
*/
public DefectService getDefectService() throws IOException {
synchronized(this) {
if(defectServiceService == null) {
defectServiceService = new DefectServiceService(
new URL(getURL(), DEFECT_SERVICE_V9_WSDL),
new QName(COVERITY_V9_NAMESPACE, "DefectServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
DefectService defectService = defectServiceService.getDefectServicePort();
attachAuthenticationHandler((BindingProvider) defectService);
return defectService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
/**
* Attach an authentication handler to the web service, that uses the configured user and password
*/
private void attachAuthenticationHandler(BindingProvider service) {
service.getBinding().setHandlerChain(Arrays.<Handler>asList(new ClientAuthenticationHandlerWSS(user, password)));
}
/**
* Returns a Configuration service client using v9 web services.
*/
public ConfigurationService getConfigurationService() throws IOException {
synchronized(this) {
if(configurationServiceService == null) {
// Create a Web Services port to the server
configurationServiceService = new ConfigurationServiceService(
new URL(getURL(), CONFIGURATION_SERVICE_V9_WSDL),
new QName(COVERITY_V9_NAMESPACE, "ConfigurationServiceService"));
}
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
ConfigurationService configurationService = configurationServiceService.getConfigurationServicePort();
attachAuthenticationHandler((BindingProvider) configurationService);
return configurationService;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
public List<MergedDefectDataObj> getDefects(String streamId, List<Long> defectIds) throws IOException, CovRemoteServiceException_Exception {
MergedDefectFilterSpecDataObj filterSpec = new MergedDefectFilterSpecDataObj();
StreamIdDataObj stream = new StreamIdDataObj();
stream.setName(streamId);
List<StreamIdDataObj> streamList = new ArrayList<StreamIdDataObj>();
streamList.add(stream);
PageSpecDataObj pageSpec = new PageSpecDataObj();
pageSpec.setPageSize(2500);
SnapshotScopeSpecDataObj snapshotScopeSpecDataObj = new SnapshotScopeSpecDataObj();
List<MergedDefectDataObj> result = new ArrayList<MergedDefectDataObj>();
int defectCount = 0;
MergedDefectsPageDataObj defects = null;
do {
pageSpec.setStartIndex(defectCount);
defects = getDefectService().getMergedDefectsForStreams(streamList, filterSpec, pageSpec, snapshotScopeSpecDataObj);
for(MergedDefectDataObj defect : defects.getMergedDefects()) {
if(defectIds.contains(defect.getCid())) {
result.add(defect);
}
}
defectCount += defects.getMergedDefects().size();
} while(defectCount < defects.getTotalNumberOfRecords());
return result;
}
public ProjectDataObj getProject(String projectId) throws IOException, CovRemoteServiceException_Exception {
ProjectFilterSpecDataObj filterSpec = new ProjectFilterSpecDataObj();
filterSpec.setNamePattern(projectId);
List<ProjectDataObj> projects = getConfigurationService().getProjects(filterSpec);
if(projects.size() == 0) {
return null;
} else {
return projects.get(0);
}
}
private transient Map<String, Long> projectKeys;
public Long getProjectKey(String projectId) throws IOException, CovRemoteServiceException_Exception {
if(projectKeys == null) {
projectKeys = new ConcurrentHashMap<String, Long>();
}
Long result = projectKeys.get(projectId);
if(result == null) {
result = getProject(projectId).getProjectKey();
projectKeys.put(projectId, result);
}
return result;
}
public List<ProjectDataObj> getProjects() throws IOException, CovRemoteServiceException_Exception {
return getConfigurationService().getProjects(new ProjectFilterSpecDataObj());
}
public List<StreamDataObj> getStaticStreams(String projectId) throws IOException, CovRemoteServiceException_Exception {
/*
to get a list of all static streams for one project,
- get a list of streams for the project
- get a list of all static streams
- compute the intersection
there should be a better way, but I can't see it.
you can't filter on project, and StreamDataObj does not have project or type information
*/
ProjectDataObj project = getProject(projectId);
List<StreamDataObj> result = new ArrayList<StreamDataObj>();
if (project != null){
for(StreamDataObj stream : project.getStreams()) {
if(!stream.getId().getName().matches(STREAM_NAME_IGNORE_PATTERN)) {
result.add(stream);
}
}
}
return result;
}
/**
* Returns a StreamDataObj for a given streamId. This object must be not null in order to avoid null pointer exceptions.
* If the stream is not found an exception explaining the issue is raised.
*/
public StreamDataObj getStream(String streamId) throws IOException, CovRemoteServiceException_Exception {
StreamFilterSpecDataObj filter = new StreamFilterSpecDataObj();
filter.setNamePattern(streamId);
List<StreamDataObj> streams = getConfigurationService().getStreams(filter);
if(streams == null || streams.isEmpty()) {
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
StreamDataObj streamDataObj = streams.get(0);
if(streamDataObj == null){
throw new IOException("An error occurred while retrieving streams for the given project. Could not find stream: " + streamId);
} else {
return streams.get(0);
}
}
}
public FormValidation doCheck() throws IOException {
try {
URL url = getURL();
int responseCode = getURLResponseCode(new URL(url, CONFIGURATION_SERVICE_V9_WSDL));
if(responseCode != 200) {
return FormValidation.error("Connected successfully, but Coverity web services were not detected.");
}
getConfigurationService().getServerTime();
return FormValidation.ok("Successfully connected to the instance.");
} catch(UnknownHostException e) {
return FormValidation.error("Host name unknown");
} catch(ConnectException e) {
return FormValidation.error("Connection refused");
} catch(SocketException e) {
return FormValidation.error("Error connecting to CIM. Please check your connection settings.");
} catch(Throwable e) {
String javaVersion = System.getProperty("java.version");
if(javaVersion.startsWith("1.6.0_")) {
int patch = Integer.parseInt(javaVersion.substring(javaVersion.indexOf('_') + 1));
if(patch < 26) {
return FormValidation.error(e, "Please use Java 1.6.0_26 or later to run Jenkins.");
}
}
return FormValidation.error(e, "An unexpected error occurred.");
}
}
private FormValidation error(Throwable t) {
if(Hudson.getInstance().hasPermission(Hudson.ADMINISTER)) {
return FormValidation.error(t, t.getMessage());
} else {
return FormValidation.error(t.getMessage());
}
}
private int getURLResponseCode(URL url) throws IOException {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
conn.getInputStream();
return conn.getResponseCode();
} catch(FileNotFoundException e) {
return 404;
}
}
public String getCimInstanceCheckers() {
List<String> checkers = new ArrayList<String>();
try {
checkers.addAll(this.getConfigurationService().getCheckerNames());
} catch(Exception e) {
}
Collections.sort(checkers);
return StringUtils.join(checkers, '\n');
}
}
| Initial work done for checking the user permission during the validation of the connection.
| src/main/java/jenkins/plugins/coverity/CIMInstance.java | Initial work done for checking the user permission during the validation of the connection. | <ide><path>rc/main/java/jenkins/plugins/coverity/CIMInstance.java
<ide> return FormValidation.error("Connected successfully, but Coverity web services were not detected.");
<ide> }
<ide> getConfigurationService().getServerTime();
<add>
<add> if (!checkUserPermission()){
<add> return FormValidation.error("\"" + user + "\" does not enough permission!");
<add> }
<add>
<ide> return FormValidation.ok("Successfully connected to the instance.");
<ide> } catch(UnknownHostException e) {
<ide> return FormValidation.error("Host name unknown");
<ide> return StringUtils.join(checkers, '\n');
<ide> }
<ide>
<add> private boolean checkUserPermission() throws IOException, com.coverity.ws.v9.CovRemoteServiceException_Exception{
<add>
<add> boolean canCommit = false;
<add> boolean canAccessWs = false;
<add> boolean canViewIssues = false;
<add>
<add> UserDataObj userData = getConfigurationService().getUser(user);
<add> if (userData != null){
<add>
<add> if (userData.isSuperUser()){
<add> return true;
<add> }
<add>
<add> for (RoleAssignmentDataObj role : userData.getRoleAssignments()){
<add> RoleDataObj roleData = getConfigurationService().getRole(role.getRoleId());
<add> if (roleData != null){
<add> for (PermissionDataObj permission : roleData.getPermissionDataObjs()){
<add> if (permission.getPermissionValue().equalsIgnoreCase("commitToStream")){
<add> canCommit = true;
<add> } else if (permission.getPermissionValue().equalsIgnoreCase("accessWS")){
<add> canAccessWs = true;
<add> } else if (permission.getPermissionValue().equalsIgnoreCase("viewDefects")){
<add> canViewIssues = true;
<add> }
<add>
<add> if (canCommit && canAccessWs && canViewIssues){
<add> return true;
<add> }
<add> }
<add> }
<add> }
<add> }
<add> return false;
<add> }
<ide> } |
|
Java | apache-2.0 | 127054f6c1d1c63fa775c99a9eb5ca176f72ec9c | 0 | evanx/vellumcore | /*
* Source https://github.com/evanx by @evanxsummers
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file to
you under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the
License. You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package vellum.crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author evan.summers
*/
public class Passwords {
static final Logger logger = LoggerFactory.getLogger(Passwords.class);
public static final int HASH_MILLIS = 200;
public static final String ALGORITHM = "PBKDF2WithHmacSHA1";
public static final int ITERATION_COUNT = 30000;
public static final int KEY_SIZE = 160;
public static final int SALT_LENGTH = 16;
public static final int ENCODED_SALT_LENGTH = 24;
public static byte[] generateSalt() {
byte[] salt = new byte[SALT_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
return salt;
}
public static byte[] hashPassword(char[] password, byte[] salt)
throws GeneralSecurityException {
return hashPassword(password, salt, ITERATION_COUNT, KEY_SIZE);
}
public static byte[] hashPassword(char[] password, byte[] salt,
int iterationCount, int keySize) throws GeneralSecurityException {
long timestamp = System.currentTimeMillis();
try {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterationCount, keySize);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
return factory.generateSecret(spec).getEncoded();
} catch (IllegalArgumentException e) {
throw new GeneralSecurityException("key size " + keySize, e);
} finally {
long duration = System.currentTimeMillis() - timestamp;
if (duration < HASH_MILLIS) {
logger.warn("hashPassword {}ms", duration);
}
}
}
public static boolean matches(char[] password, byte[] passwordHash, byte[] salt)
throws GeneralSecurityException {
return matches(password, passwordHash, salt, ITERATION_COUNT, KEY_SIZE);
}
public static boolean matches(char[] password, byte[] passwordHash, byte[] salt,
int iterationCount, int keySize) throws GeneralSecurityException {
return Arrays.equals(passwordHash, hashPassword(password, salt,
iterationCount, keySize));
}
}
| src/vellum/crypto/Passwords.java | /*
* Source https://github.com/evanx by @evanxsummers
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file to
you under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the
License. You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package vellum.crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
*
* @author evan.summers
*/
public class Passwords {
public static final int HASH_MILLIS = 200; // log hashing if slowing than this
public static final String ALGORITHM = "PBKDF2WithHmacSHA1";
public static final int ITERATION_COUNT = 30000;
public static final int KEY_SIZE = 160;
public static final int SALT_LENGTH = 16;
public static final int ENCODED_SALT_LENGTH = 24;
public static byte[] generateSalt() {
byte[] salt = new byte[SALT_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
return salt;
}
public static byte[] hashPassword(char[] password, byte[] salt)
throws GeneralSecurityException {
return hashPassword(password, salt, ITERATION_COUNT, KEY_SIZE);
}
public static byte[] hashPassword(char[] password, byte[] salt,
int iterationCount, int keySize) throws GeneralSecurityException {
try {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterationCount, keySize);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
return factory.generateSecret(spec).getEncoded();
} catch (IllegalArgumentException e) {
throw new GeneralSecurityException("key size " + keySize, e);
}
}
public static boolean matches(char[] password, byte[] passwordHash, byte[] salt)
throws GeneralSecurityException {
return matches(password, passwordHash, salt, ITERATION_COUNT, KEY_SIZE);
}
public static boolean matches(char[] password, byte[] passwordHash, byte[] salt,
int iterationCount, int keySize) throws GeneralSecurityException {
return Arrays.equals(passwordHash, hashPassword(password, salt,
iterationCount, keySize));
}
}
| logger if password hashing too slow, so that iteration count can be increased before deployed | src/vellum/crypto/Passwords.java | logger if password hashing too slow, so that iteration count can be increased before deployed | <ide><path>rc/vellum/crypto/Passwords.java
<ide> import java.util.Arrays;
<ide> import javax.crypto.SecretKeyFactory;
<ide> import javax.crypto.spec.PBEKeySpec;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide>
<ide> /**
<ide> *
<ide> * @author evan.summers
<ide> */
<ide> public class Passwords {
<del>
<del> public static final int HASH_MILLIS = 200; // log hashing if slowing than this
<add> static final Logger logger = LoggerFactory.getLogger(Passwords.class);
<add>
<add> public static final int HASH_MILLIS = 200;
<ide> public static final String ALGORITHM = "PBKDF2WithHmacSHA1";
<ide> public static final int ITERATION_COUNT = 30000;
<ide> public static final int KEY_SIZE = 160;
<ide>
<ide> public static byte[] hashPassword(char[] password, byte[] salt,
<ide> int iterationCount, int keySize) throws GeneralSecurityException {
<add> long timestamp = System.currentTimeMillis();
<ide> try {
<ide> PBEKeySpec spec = new PBEKeySpec(password, salt, iterationCount, keySize);
<ide> SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
<ide> return factory.generateSecret(spec).getEncoded();
<ide> } catch (IllegalArgumentException e) {
<ide> throw new GeneralSecurityException("key size " + keySize, e);
<add> } finally {
<add> long duration = System.currentTimeMillis() - timestamp;
<add> if (duration < HASH_MILLIS) {
<add> logger.warn("hashPassword {}ms", duration);
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 059f1d27c998024fc07d7b56d5603c2c4a790d36 | 0 | JUGDortmund/Tar,JUGDortmund/Tar,JUGDortmund/Tar | package de.maredit.tar.listeners;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import de.maredit.tar.Main;
import de.maredit.tar.models.User;
import de.maredit.tar.models.Vacation;
import de.maredit.tar.repositories.CommentItemRepository;
import de.maredit.tar.repositories.ProtocolItemRepository;
import de.maredit.tar.repositories.StateItemRepository;
import de.maredit.tar.repositories.UserRepository;
import de.maredit.tar.repositories.VacationRepository;
import de.maredit.tar.services.LdapService;
import de.maredit.tar.tasks.UserSyncTask;
import de.svenkubiak.embeddedmongodb.EmbeddedMongo;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@ActiveProfiles("test")
public class ContextListenerTest {
@Autowired
private UserRepository userRepository;
@Autowired
private VacationRepository vacationRepository;
@Autowired
private ProtocolItemRepository protocolItemRepository;
@Autowired
private CommentItemRepository commentItemRepository;
@Autowired
private StateItemRepository stateItemRepository;
@Autowired
private UserSyncTask userSyncTask;
@Autowired
private LdapService ldapServcie;
private ContextRefreshedEvent event = Mockito.mock(ContextRefreshedEvent.class);
private UserSyncTask mockedUserSyncTask = Mockito.mock(UserSyncTask.class);
private ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
private Environment environment = Mockito.mock(Environment.class);
@BeforeClass
public static void init() {
EmbeddedMongo.DB.port(28018).start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void preloadData() {
when(event.getApplicationContext()).thenReturn(applicationContext);
when(event.getApplicationContext().getBean(UserSyncTask.class)).thenReturn(mockedUserSyncTask);
when(event.getApplicationContext().getEnvironment()).thenReturn(environment);
when(event.getApplicationContext().getEnvironment().getProperty("spring.data.mongodb.preload",
Boolean.class)).thenReturn(true);
when(event.getApplicationContext().getBean(UserRepository.class)).thenReturn(userRepository);
when(event.getApplicationContext().getBean(VacationRepository.class)).thenReturn(vacationRepository);
when(event.getApplicationContext().getBean(ProtocolItemRepository.class)).thenReturn(protocolItemRepository);
when(event.getApplicationContext().getBean(CommentItemRepository.class)).thenReturn(commentItemRepository);
when(event.getApplicationContext().getBean(StateItemRepository.class)).thenReturn(stateItemRepository);
when(event.getApplicationContext().getBean(LdapService.class)).thenReturn(ldapServcie);
this.userSyncTask.syncLdapUser();
List<User> users = userRepository.findAll();
assertNotNull(users);
assertTrue(users.size() > 0);
ContextListener contextListener = new ContextListener();
contextListener.onApplicationEvent(event);
List<Vacation> vacations = vacationRepository.findAll();
assertNotNull(vacations);
assertTrue(vacations.size() > 0);
}
@AfterClass
public static void shutdown() {
EmbeddedMongo.DB.stop();
}
} | src/test/java/de/maredit/tar/listeners/ContextListenerTest.java | package de.maredit.tar.listeners;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import de.maredit.tar.Main;
import de.maredit.tar.models.User;
import de.maredit.tar.models.Vacation;
import de.maredit.tar.repositories.UserRepository;
import de.maredit.tar.repositories.VacationRepository;
import de.maredit.tar.services.LdapService;
import de.maredit.tar.tasks.UserSyncTask;
import de.svenkubiak.embeddedmongodb.EmbeddedMongo;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@ActiveProfiles("test")
public class ContextListenerTest {
@Autowired
private UserRepository userRepository;
@Autowired
private VacationRepository vacationRepository;
@Autowired
private UserSyncTask userSyncTask;
@Autowired
private LdapService ldapServcie;
private ContextRefreshedEvent event = Mockito.mock(ContextRefreshedEvent.class);
private UserSyncTask mockedUserSyncTask = Mockito.mock(UserSyncTask.class);
private ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
private Environment environment = Mockito.mock(Environment.class);
@BeforeClass
public static void init() {
EmbeddedMongo.DB.port(28018).start();
}
@Test
public void preloadData() {
when(event.getApplicationContext()).thenReturn(applicationContext);
when(event.getApplicationContext().getBean(UserSyncTask.class)).thenReturn(mockedUserSyncTask);
when(event.getApplicationContext().getEnvironment()).thenReturn(environment);
when(event.getApplicationContext().getEnvironment().getProperty("spring.data.mongodb.preload", Boolean.class)).thenReturn(true);
when(event.getApplicationContext().getBean(UserRepository.class)).thenReturn(userRepository);
when(event.getApplicationContext().getBean(VacationRepository.class)).thenReturn( vacationRepository);
when(event.getApplicationContext().getBean(LdapService.class)).thenReturn(ldapServcie);
this.userSyncTask.syncLdapUser();
List<User> users = userRepository.findAll();
assertNotNull(users);
assertTrue(users.size() > 0);
ContextListener contextListener = new ContextListener();
contextListener.onApplicationEvent(event);
List<Vacation> vacations = vacationRepository.findAll();
assertNotNull(vacations);
assertTrue(vacations.size() > 0);
}
@AfterClass
public static void shutdown() {
EmbeddedMongo.DB.stop();
}
} | TAR-115: fixed test
| src/test/java/de/maredit/tar/listeners/ContextListenerTest.java | TAR-115: fixed test | <ide><path>rc/test/java/de/maredit/tar/listeners/ContextListenerTest.java
<ide> import de.maredit.tar.Main;
<ide> import de.maredit.tar.models.User;
<ide> import de.maredit.tar.models.Vacation;
<add>import de.maredit.tar.repositories.CommentItemRepository;
<add>import de.maredit.tar.repositories.ProtocolItemRepository;
<add>import de.maredit.tar.repositories.StateItemRepository;
<ide> import de.maredit.tar.repositories.UserRepository;
<ide> import de.maredit.tar.repositories.VacationRepository;
<ide> import de.maredit.tar.services.LdapService;
<ide>
<ide> @Autowired
<ide> private VacationRepository vacationRepository;
<del>
<add>
<add> @Autowired
<add> private ProtocolItemRepository protocolItemRepository;
<add>
<add> @Autowired
<add> private CommentItemRepository commentItemRepository;
<add>
<add> @Autowired
<add> private StateItemRepository stateItemRepository;
<add>
<ide> @Autowired
<ide> private UserSyncTask userSyncTask;
<ide>
<ide> @BeforeClass
<ide> public static void init() {
<ide> EmbeddedMongo.DB.port(28018).start();
<add> try {
<add> Thread.sleep(2000);
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<ide> }
<ide>
<ide> @Test
<ide> when(event.getApplicationContext()).thenReturn(applicationContext);
<ide> when(event.getApplicationContext().getBean(UserSyncTask.class)).thenReturn(mockedUserSyncTask);
<ide> when(event.getApplicationContext().getEnvironment()).thenReturn(environment);
<del> when(event.getApplicationContext().getEnvironment().getProperty("spring.data.mongodb.preload", Boolean.class)).thenReturn(true);
<add> when(event.getApplicationContext().getEnvironment().getProperty("spring.data.mongodb.preload",
<add> Boolean.class)).thenReturn(true);
<ide> when(event.getApplicationContext().getBean(UserRepository.class)).thenReturn(userRepository);
<del> when(event.getApplicationContext().getBean(VacationRepository.class)).thenReturn( vacationRepository);
<add> when(event.getApplicationContext().getBean(VacationRepository.class)).thenReturn(vacationRepository);
<add> when(event.getApplicationContext().getBean(ProtocolItemRepository.class)).thenReturn(protocolItemRepository);
<add> when(event.getApplicationContext().getBean(CommentItemRepository.class)).thenReturn(commentItemRepository);
<add> when(event.getApplicationContext().getBean(StateItemRepository.class)).thenReturn(stateItemRepository);
<ide> when(event.getApplicationContext().getBean(LdapService.class)).thenReturn(ldapServcie);
<ide>
<ide> this.userSyncTask.syncLdapUser(); |
|
Java | apache-2.0 | 4e4f545c11ccb39cb1589b54ce384995fee6b015 | 0 | longkuitt67/sou-zhou-bian | package com.example.souzhoubian;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.*;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private static final int SUCCESS = 0;
private static final int ERROR_SERVER = 1;
private static final int ERROR_DATA_FORMAT = 2;
private ListView listView;
private ImageButton ic_action_map;
private ImageButton mainBackButton;
private ArrayList<HashMap<String, ?>> data = new ArrayList<HashMap<String, ?>>();
private View mapview;
private boolean flag = true;
private BMapManager bMapManager;
public static final String strKey = "AB0f4e783ab452277aa2d7deb9517554";
private MapView mapView;
private MapController mapController;
private LayoutInflater layoutInflater;
private View mapPopWindow;
private PoiOverlay<OverlayItem> itemItemizedOverlay;
private MyLocationOverlay myLocationOverlay;
private ImageButton refreshBar;
private AlertDialog loginDialog;
private SimpleAdapter simpleAdapter;
private LinearLayout jump;
private TextView showTextView;
int selectedFruitIndex = 0;
private ImageButton contentButton;
List<HashMap<String,String>> list=new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// BMapManager bMapManager = new BMapManager(this);
// bMapManager.init("20deb62852b3e32be20f587e798849db",null);
bMapManager = new BMapManager(this);
boolean initResult = bMapManager.init(strKey, new MKGeneralListener() {
@Override
public void onGetNetworkState(int iError) {
if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
Toast.makeText(MyActivity.this, "您的网络出错啦!", Toast.LENGTH_LONG).show();
} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
Toast.makeText(MyActivity.this, "输入正确的检索条件!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onGetPermissionState(int iError) {
if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
Toast.makeText(MyActivity.this, "请在 DemoApplication.java文件输入正确的授权Key!", Toast.LENGTH_LONG).show();
}
}
});
if (!initResult) {
Toast.makeText(MapApplication.getInstance().getApplicationContext(), "BMapManager 初始化错误!", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.main);
mapview = findViewById(R.id.mapparent);
layoutInflater = LayoutInflater.from(this);
mapView = (MapView) findViewById(R.id.bmapView);
mapView.setBuiltInZoomControls(false);
//卫星图层
mapView.setSatellite(false);
//交通图层
mapView.setTraffic(false);
mapController = mapView.getController();
//控制缩放等级
mapController.setZoom(14);
//移动到经纬度点
final GeoPoint geoPoint = new GeoPoint((int) (34.25934463685013 * 1E6), (int) (108.94721031188965 * 1E6));
//设置中心点
mapController.setCenter(geoPoint);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mapController.animateTo(geoPoint);
}
}, 5000);
Drawable marker = getResources().getDrawable(R.drawable.ic_loc_normal);
itemItemizedOverlay = new PoiOverlay<OverlayItem>(marker, mapView);
for (int i = 0; i < 10; i++) {
GeoPoint point = new GeoPoint(geoPoint.getLatitudeE6() + i * 10000, geoPoint.getLongitudeE6() + i * 10000);
OverlayItem overlayItem = new OverlayItem(point, "我是标题 " + i, "黄记煌三汁焖锅 " + i);
itemItemizedOverlay.addItem(overlayItem);
}
mapView.getOverlays().add(itemItemizedOverlay);
// layoutInflater = getLayoutInflater();
//添加弹出窗口
mapPopWindow = layoutInflater.inflate(R.layout.map_pop_window, null);
mapPopWindow.setVisibility(View.GONE);
mapView.addView(mapPopWindow);
myLocationOverlay = new MyLocationOverlay(getResources().getDrawable(R.drawable.ic_loc_normal), mapView);
mapView.getOverlays().add(myLocationOverlay);
Map();
ProgressBar();
mainBack();
DetailMapView();
listView();
JsonTask("https://api.weibo.com/2/location/pois/search/by_geo.json?q=理想国际大厦&access_token=2.0049soLEchqxNE76806c7cb8ype3hB&coordinate=116.322479%2C39.980781");
}
public void JsonTask(String url) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("加载中...");
final String url_name = url;
AsyncTask<Integer, Integer, Integer> task = new AsyncTask<Integer, Integer, Integer>() {
@Override
protected Integer doInBackground(Integer... integers) {
try {
String result = requestServerData(url_name);
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = (JSONArray) jsonObject.get("poilist");
for(int i=0;i<jsonArray.length();i++){
HashMap<String,String>data=new HashMap<String, String>();
JSONObject o = (JSONObject) jsonArray.get(i);
data.put("name",o.getString("name"));
data.put("address",o.getString("address"));
data.put("distance", o.getString("distance"));
Log.d("","name"+o.getString("name"));
Log.d("","address"+o.getString("address"));
Log.d("","distance"+o.getString("distance"));
list.add(data);
}
} catch (IOException e) {
Log.e("", "Request server data error", e);
return ERROR_SERVER;
} catch (JSONException e) {
Log.e("", "Format data error", e);
return ERROR_DATA_FORMAT;
}
return SUCCESS;
}
;
@Override
protected void onPreExecute() {
progressDialog.show();
}
@Override
protected void onPostExecute(Integer result) {
progressDialog.dismiss();
simpleAdapter.notifyDataSetChanged();
//
// if (result == SUCCESS) {
// //跳转到展示界面
// gotoDetail(downloadPath, ImageViewerActivity.IMAGE_SOURCE_TEMP);
//
// } else if (result == ERROR_SERVER) {
// showServerErrorMessage();
// } else if (result == ERROR_DATA_FORMAT) {
// showDataErrorMessage();
// }
}
};
task.execute(0);
}
private void showServerErrorMessage() {
Toast.makeText(this, "请求数据失败", Toast.LENGTH_LONG).show();
}
private void showDataErrorMessage() {
Toast.makeText(this, "数据格式错误", Toast.LENGTH_LONG).show();
}
private String requestServerData(String url) throws IOException {
//请求服务器
HttpGet request = new HttpGet(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
String resultStr = EntityUtils.toString(response.getEntity(), "UTF-8");
return resultStr;
}
public void DetailMapView() {
jump = (LinearLayout) findViewById(R.id.Jump);
jump.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MyActivity.this, DetailActivity.class);
startActivity(intent);
}
});
}
public void ProgressBar() {
refreshBar = (ImageButton) findViewById(R.id.refreshButtonOnActivity);
refreshBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
LayoutInflater inflater = LayoutInflater.from(MyActivity.this);
View progress = inflater.inflate(R.layout.progressbar, null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
progress.setLayoutParams(params);
builder.setView(progress);
loginDialog = builder.create();
loginDialog.show();
}
});
}
public void Map() {
ic_action_map = (ImageButton) findViewById(R.id.mapButton);
ic_action_map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (flag) {
// ic_action_map.setVisibility(View.GONE);
// contentButton.setVisibility(View.VISIBLE);
ic_action_map.setImageResource(R.drawable.ic_action_list);
listView.setVisibility(View.GONE);
mapview.setVisibility(View.VISIBLE);
flag = false;
} else {
// ic_action_map.setVisibility(View.VISIBLE);
// contentButton.setVisibility(View.GONE);
ic_action_map.setImageResource(R.drawable.ic_action_map);
mapview.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
flag = true;
}
}
});
}
public void Dialog(View v) {
String args[] = new String[]{"1000m内", "2000m内", "3000m内", "4000m内", "5000m内"};
showTextView = (TextView) findViewById(R.id.fanwei);
final Dialog alertDialog = new AlertDialog.Builder(this).
setTitle("选择范围")
.setIcon(android.R.drawable.ic_menu_more)
.setSingleChoiceItems(args, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedFruitIndex = which;
dialog.dismiss();
if (selectedFruitIndex == 0) {
showTextView.setText("范围:1000m内");
} else if (selectedFruitIndex == 1) {
showTextView.setText("范围:2000m内");
} else if (selectedFruitIndex == 2) {
showTextView.setText("范围:3000m内");
} else if (selectedFruitIndex == 3) {
showTextView.setText("范围:4000m内");
} else if (selectedFruitIndex == 4) {
showTextView.setText("范围:5000m内");
}
}
}).create();
alertDialog.show();
}
public void listView() {
listView = (ListView) findViewById(R.id.listView);
simpleAdapter = new SimpleAdapter(this,
list,
R.layout.chat_item,
new String[]{"name", "address", "distance"},
new int[]{R.id.TittleText, R.id.AddressMessage, R.id.fanwei});
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long itemId) {
listView.setVisibility(View.GONE);
mapview.setVisibility(View.VISIBLE);
flag = false;
}
});
}
public void mainBack() {
mainBackButton = (ImageButton) findViewById(R.id.main_back);
mainBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MyActivity.this.finish();
}
});
}
class PoiOverlay<OverlayItem> extends ItemizedOverlay {
public PoiOverlay(Drawable drawable, MapView mapView) {
super(drawable, mapView);
}
@Override
protected boolean onTap(int i) {
Log.d("BaiduMapDemo", "onTap " + i);
com.baidu.mapapi.map.OverlayItem item = itemItemizedOverlay.getItem(i);
GeoPoint point = item.getPoint();
String content = item.getSnippet();
TextView contentTextView = (TextView) mapPopWindow.findViewById(R.id.contentTextView);
contentTextView.setText(content);
contentTextView.setVisibility(View.VISIBLE);
MapView.LayoutParams layoutParam = new MapView.LayoutParams(
//控件宽,继承自ViewGroup.LayoutParams
MapView.LayoutParams.WRAP_CONTENT,
//控件高,继承自ViewGroup.LayoutParams
MapView.LayoutParams.WRAP_CONTENT,
//使控件固定在某个地理位置
point,
0,
-40,
//控件对齐方式
MapView.LayoutParams.BOTTOM_CENTER);
mapPopWindow.setVisibility(View.VISIBLE);
mapPopWindow.setLayoutParams(layoutParam);
mapController.animateTo(point);
return super.onTap(i);
}
@Override
public boolean onTap(GeoPoint geoPoint, MapView mapView) {
Log.d("BaiduMapDemo", "onTap geoPoint " + geoPoint);
mapPopWindow.setVisibility(View.GONE);
return super.onTap(geoPoint, mapView); //To change body of overridden methods use File | Settings | File Templates.
}
}
}
| souzhoubian/src/com/example/souzhoubian/MyActivity.java | package com.example.souzhoubian;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.*;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import java.util.ArrayList;
import java.util.HashMap;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private ListView listView;
private ImageButton ic_action_map;
private ImageButton mainBackButton;
private ArrayList<HashMap<String, ?>> data = new ArrayList<HashMap<String, ?>>();
private View mapview;
private boolean flag=true;
private BMapManager bMapManager;
public static final String strKey = "AB0f4e783ab452277aa2d7deb9517554";
private MapView mapView;
private MapController mapController;
private LayoutInflater layoutInflater;
private View mapPopWindow;
private PoiOverlay<OverlayItem> itemItemizedOverlay;
private MyLocationOverlay myLocationOverlay;
private ImageButton refreshBar;
private AlertDialog loginDialog;
private LinearLayout jump;
private TextView showTextView;
int selectedFruitIndex = 0;
private ImageButton contentButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// BMapManager bMapManager = new BMapManager(this);
// bMapManager.init("20deb62852b3e32be20f587e798849db",null);
bMapManager = new BMapManager(this);
boolean initResult = bMapManager.init(strKey, new MKGeneralListener() {
@Override
public void onGetNetworkState(int iError) {
if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
Toast.makeText(MyActivity.this, "您的网络出错啦!", Toast.LENGTH_LONG).show();
} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
Toast.makeText(MyActivity.this, "输入正确的检索条件!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onGetPermissionState(int iError) {
if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
Toast.makeText(MyActivity.this, "请在 DemoApplication.java文件输入正确的授权Key!", Toast.LENGTH_LONG).show();
}
}
});
if (!initResult) {
Toast.makeText(MapApplication.getInstance().getApplicationContext(), "BMapManager 初始化错误!", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.main);
mapview = findViewById(R.id.mapparent);
layoutInflater = LayoutInflater.from(this);
mapView = (MapView) findViewById(R.id.bmapView);
mapView.setBuiltInZoomControls(false);
//卫星图层
mapView.setSatellite(false);
//交通图层
mapView.setTraffic(false);
mapController = mapView.getController();
//控制缩放等级
mapController.setZoom(14);
//移动到经纬度点
final GeoPoint geoPoint = new GeoPoint((int) (34.25934463685013 * 1E6), (int) (108.94721031188965 * 1E6));
//设置中心点
mapController.setCenter(geoPoint);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mapController.animateTo(geoPoint);
}
}, 5000);
Drawable marker = getResources().getDrawable(R.drawable.ic_loc_normal);
itemItemizedOverlay = new PoiOverlay<OverlayItem>(marker, mapView);
for (int i = 0; i < 10; i++) {
GeoPoint point = new GeoPoint(geoPoint.getLatitudeE6() + i * 10000, geoPoint.getLongitudeE6() + i * 10000);
OverlayItem overlayItem = new OverlayItem(point, "我是标题 " + i, "黄记煌三汁焖锅 " + i);
itemItemizedOverlay.addItem(overlayItem);
}
mapView.getOverlays().add(itemItemizedOverlay);
// layoutInflater = getLayoutInflater();
//添加弹出窗口
mapPopWindow = layoutInflater.inflate(R.layout.map_pop_window, null);
mapPopWindow.setVisibility(View.GONE);
mapView.addView(mapPopWindow);
myLocationOverlay = new MyLocationOverlay(getResources().getDrawable(R.drawable.ic_loc_normal), mapView);
mapView.getOverlays().add(myLocationOverlay);
listView();
Map();
ProgressBar();
mainBack();
DetailMapView();
}
public void DetailMapView(){
jump=(LinearLayout)findViewById(R.id.Jump);
jump.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent();
intent.setClass(MyActivity.this,DetailActivity.class);
startActivity(intent);
}
});
}
public void ProgressBar(){
refreshBar=(ImageButton)findViewById(R.id.refreshButtonOnActivity);
refreshBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
LayoutInflater inflater = LayoutInflater.from(MyActivity.this);
View progress = inflater.inflate(R.layout.progressbar, null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
progress.setLayoutParams(params);
builder.setView(progress);
loginDialog = builder.create();
loginDialog.show();
}
});
}
public void Map(){
ic_action_map=(ImageButton)findViewById(R.id.mapButton);
ic_action_map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (flag) {
// ic_action_map.setVisibility(View.GONE);
// contentButton.setVisibility(View.VISIBLE);
ic_action_map.setImageResource(R.drawable.ic_action_list);
listView.setVisibility(View.GONE);
mapview.setVisibility(View.VISIBLE);
flag = false;
} else {
// ic_action_map.setVisibility(View.VISIBLE);
// contentButton.setVisibility(View.GONE);
ic_action_map.setImageResource(R.drawable.ic_action_map);
mapview.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
flag = true;
}
}
});
}
public void Dialog(View v) {
String args[] = new String[]{"1000m内", "2000m内", "3000m内", "4000m内", "5000m内"};
showTextView=(TextView)findViewById(R.id.fanwei);
final Dialog alertDialog = new AlertDialog.Builder(this).
setTitle("选择范围")
.setIcon(android.R.drawable.ic_menu_more)
.setSingleChoiceItems(args, 0, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
selectedFruitIndex=which;
dialog.dismiss();
if(selectedFruitIndex==0){
showTextView.setText("范围:1000m内");
}else if(selectedFruitIndex==1){
showTextView.setText("范围:2000m内");
} else if(selectedFruitIndex==2){
showTextView.setText("范围:3000m内");
} else if(selectedFruitIndex==3){
showTextView.setText("范围:4000m内");
} else if(selectedFruitIndex==4){
showTextView.setText("范围:5000m内");
}
}
}).create();
alertDialog.show();
}
public void listView() {
listView = (ListView) findViewById(R.id.listView);
for (int i = 0; i < 20; i++) {
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("title", "黄记煌三汁焖锅");
item.put("address", "西安南大街52号南附楼内3层” ");
item.put("fanwei", " 500m");
if (i == 1) {
item.put("title", "香港私家菜天子海鲜火锅 " + i);
item.put("address", "南大街 " + i + " " + i);
item.put("fanwei", "500m");
data.add(item);
continue;
}
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this,
data,
R.layout.chat_item,
new String[]{"title", "address", "fanwei"},
new int[]{R.id.TittleText, R.id.AddressMessage, R.id.fanwei});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long itemId) {
listView.setVisibility(View.GONE);
mapview.setVisibility(View.VISIBLE);
flag = false;
}
});
}
public void mainBack(){
mainBackButton = (ImageButton) findViewById(R.id.main_back);
mainBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MyActivity.this.finish();
}
});
}
class PoiOverlay<OverlayItem> extends ItemizedOverlay {
public PoiOverlay(Drawable drawable, MapView mapView) {
super(drawable, mapView);
}
@Override
protected boolean onTap(int i) {
Log.d("BaiduMapDemo", "onTap " + i);
com.baidu.mapapi.map.OverlayItem item = itemItemizedOverlay.getItem(i);
GeoPoint point = item.getPoint();
String content = item.getSnippet();
TextView contentTextView = (TextView) mapPopWindow.findViewById(R.id.contentTextView);
contentTextView.setText(content);
contentTextView.setVisibility(View.VISIBLE);
MapView.LayoutParams layoutParam = new MapView.LayoutParams(
//控件宽,继承自ViewGroup.LayoutParams
MapView.LayoutParams.WRAP_CONTENT,
//控件高,继承自ViewGroup.LayoutParams
MapView.LayoutParams.WRAP_CONTENT,
//使控件固定在某个地理位置
point,
0,
-40,
//控件对齐方式
MapView.LayoutParams.BOTTOM_CENTER);
mapPopWindow.setVisibility(View.VISIBLE);
mapPopWindow.setLayoutParams(layoutParam);
mapController.animateTo(point);
return super.onTap(i);
}
@Override
public boolean onTap(GeoPoint geoPoint, MapView mapView) {
Log.d("BaiduMapDemo", "onTap geoPoint " + geoPoint);
mapPopWindow.setVisibility(View.GONE);
return super.onTap(geoPoint, mapView); //To change body of overridden methods use File | Settings | File Templates.
}
}
}
| 添加解析json
| souzhoubian/src/com/example/souzhoubian/MyActivity.java | 添加解析json | <ide><path>ouzhoubian/src/com/example/souzhoubian/MyActivity.java
<ide> import android.app.Activity;
<ide> import android.app.AlertDialog;
<ide> import android.app.Dialog;
<add>import android.app.ProgressDialog;
<ide> import android.content.DialogInterface;
<ide> import android.content.Intent;
<ide> import android.graphics.drawable.Drawable;
<add>import android.os.AsyncTask;
<ide> import android.os.Bundle;
<ide> import android.os.Handler;
<ide> import android.util.Log;
<ide> import com.baidu.mapapi.MKGeneralListener;
<ide> import com.baidu.mapapi.map.*;
<ide> import com.baidu.platform.comapi.basestruct.GeoPoint;
<del>
<add>import org.apache.http.HttpResponse;
<add>import org.apache.http.client.methods.HttpGet;
<add>import org.apache.http.impl.client.DefaultHttpClient;
<add>import org.apache.http.util.EntityUtils;
<add>import org.json.JSONArray;
<add>import org.json.JSONException;
<add>import org.json.JSONObject;
<add>
<add>import java.io.IOException;
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<add>import java.util.List;
<ide>
<ide> public class MyActivity extends Activity {
<ide>
<ide> /**
<ide> * Called when the activity is first created.
<ide> */
<del>
<add> private static final int SUCCESS = 0;
<add> private static final int ERROR_SERVER = 1;
<add> private static final int ERROR_DATA_FORMAT = 2;
<ide> private ListView listView;
<ide> private ImageButton ic_action_map;
<ide> private ImageButton mainBackButton;
<ide> private ArrayList<HashMap<String, ?>> data = new ArrayList<HashMap<String, ?>>();
<ide> private View mapview;
<del> private boolean flag=true;
<add> private boolean flag = true;
<ide>
<ide> private BMapManager bMapManager;
<ide> public static final String strKey = "AB0f4e783ab452277aa2d7deb9517554";
<ide> private MyLocationOverlay myLocationOverlay;
<ide> private ImageButton refreshBar;
<ide> private AlertDialog loginDialog;
<add> private SimpleAdapter simpleAdapter;
<ide>
<ide> private LinearLayout jump;
<ide> private TextView showTextView;
<ide> int selectedFruitIndex = 0;
<ide> private ImageButton contentButton;
<add>
<add> List<HashMap<String,String>> list=new ArrayList<HashMap<String, String>>();
<add>
<add>
<ide>
<ide> public void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> }
<ide>
<ide>
<del>
<ide> setContentView(R.layout.main);
<ide> mapview = findViewById(R.id.mapparent);
<ide> layoutInflater = LayoutInflater.from(this);
<ide> mapView.addView(mapPopWindow);
<ide>
<ide>
<del>
<ide> myLocationOverlay = new MyLocationOverlay(getResources().getDrawable(R.drawable.ic_loc_normal), mapView);
<ide> mapView.getOverlays().add(myLocationOverlay);
<ide>
<ide>
<ide>
<del>
<del>
<del>
<del> listView();
<ide> Map();
<ide> ProgressBar();
<ide> mainBack();
<ide>
<ide>
<ide> DetailMapView();
<del> }
<del> public void DetailMapView(){
<del> jump=(LinearLayout)findViewById(R.id.Jump);
<add> listView();
<add>
<add> JsonTask("https://api.weibo.com/2/location/pois/search/by_geo.json?q=理想国际大厦&access_token=2.0049soLEchqxNE76806c7cb8ype3hB&coordinate=116.322479%2C39.980781");
<add>
<add>
<add> }
<add>
<add> public void JsonTask(String url) {
<add> final ProgressDialog progressDialog = new ProgressDialog(this);
<add> progressDialog.setMessage("加载中...");
<add> final String url_name = url;
<add> AsyncTask<Integer, Integer, Integer> task = new AsyncTask<Integer, Integer, Integer>() {
<add> @Override
<add> protected Integer doInBackground(Integer... integers) {
<add> try {
<add>
<add> String result = requestServerData(url_name);
<add> JSONObject jsonObject = new JSONObject(result);
<add> JSONArray jsonArray = (JSONArray) jsonObject.get("poilist");
<add> for(int i=0;i<jsonArray.length();i++){
<add> HashMap<String,String>data=new HashMap<String, String>();
<add> JSONObject o = (JSONObject) jsonArray.get(i);
<add>
<add> data.put("name",o.getString("name"));
<add> data.put("address",o.getString("address"));
<add> data.put("distance", o.getString("distance"));
<add> Log.d("","name"+o.getString("name"));
<add> Log.d("","address"+o.getString("address"));
<add> Log.d("","distance"+o.getString("distance"));
<add> list.add(data);
<add> }
<add> } catch (IOException e) {
<add> Log.e("", "Request server data error", e);
<add>
<add> return ERROR_SERVER;
<add> } catch (JSONException e) {
<add> Log.e("", "Format data error", e);
<add>
<add> return ERROR_DATA_FORMAT;
<add> }
<add>
<add> return SUCCESS;
<add> }
<add>
<add> ;
<add> @Override
<add> protected void onPreExecute() {
<add> progressDialog.show();
<add> }
<add>
<add> @Override
<add> protected void onPostExecute(Integer result) {
<add> progressDialog.dismiss();
<add> simpleAdapter.notifyDataSetChanged();
<add>//
<add>// if (result == SUCCESS) {
<add>// //跳转到展示界面
<add>// gotoDetail(downloadPath, ImageViewerActivity.IMAGE_SOURCE_TEMP);
<add>//
<add>// } else if (result == ERROR_SERVER) {
<add>// showServerErrorMessage();
<add>// } else if (result == ERROR_DATA_FORMAT) {
<add>// showDataErrorMessage();
<add>// }
<add> }
<add> };
<add>
<add> task.execute(0);
<add>
<add> }
<add> private void showServerErrorMessage() {
<add> Toast.makeText(this, "请求数据失败", Toast.LENGTH_LONG).show();
<add> }
<add>
<add> private void showDataErrorMessage() {
<add> Toast.makeText(this, "数据格式错误", Toast.LENGTH_LONG).show();
<add> }
<add> private String requestServerData(String url) throws IOException {
<add> //请求服务器
<add> HttpGet request = new HttpGet(url);
<add>
<add> DefaultHttpClient httpClient = new DefaultHttpClient();
<add>
<add> HttpResponse response = httpClient.execute(request);
<add> String resultStr = EntityUtils.toString(response.getEntity(), "UTF-8");
<add>
<add> return resultStr;
<add> }
<add>
<add> public void DetailMapView() {
<add> jump = (LinearLayout) findViewById(R.id.Jump);
<ide> jump.setOnClickListener(new View.OnClickListener() {
<ide> @Override
<ide> public void onClick(View view) {
<del> Intent intent=new Intent();
<del> intent.setClass(MyActivity.this,DetailActivity.class);
<add> Intent intent = new Intent();
<add> intent.setClass(MyActivity.this, DetailActivity.class);
<ide> startActivity(intent);
<ide> }
<ide> });
<ide> }
<ide>
<del> public void ProgressBar(){
<del> refreshBar=(ImageButton)findViewById(R.id.refreshButtonOnActivity);
<del> refreshBar.setOnClickListener(new View.OnClickListener() {
<add> public void ProgressBar() {
<add> refreshBar = (ImageButton) findViewById(R.id.refreshButtonOnActivity);
<add> refreshBar.setOnClickListener(new View.OnClickListener() {
<ide> @Override
<ide> public void onClick(View view) {
<ide> AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
<ide> }
<ide> });
<ide> }
<del> public void Map(){
<del> ic_action_map=(ImageButton)findViewById(R.id.mapButton);
<add>
<add> public void Map() {
<add> ic_action_map = (ImageButton) findViewById(R.id.mapButton);
<ide> ic_action_map.setOnClickListener(new View.OnClickListener() {
<ide> @Override
<ide> public void onClick(View view) {
<ide> }
<ide> });
<ide> }
<add>
<ide> public void Dialog(View v) {
<ide> String args[] = new String[]{"1000m内", "2000m内", "3000m内", "4000m内", "5000m内"};
<del> showTextView=(TextView)findViewById(R.id.fanwei);
<del> final Dialog alertDialog = new AlertDialog.Builder(this).
<add> showTextView = (TextView) findViewById(R.id.fanwei);
<add> final Dialog alertDialog = new AlertDialog.Builder(this).
<ide> setTitle("选择范围")
<ide> .setIcon(android.R.drawable.ic_menu_more)
<del> .setSingleChoiceItems(args, 0, new DialogInterface.OnClickListener(){
<add> .setSingleChoiceItems(args, 0, new DialogInterface.OnClickListener() {
<ide> @Override
<ide> public void onClick(DialogInterface dialog, int which) {
<del> selectedFruitIndex=which;
<add> selectedFruitIndex = which;
<ide> dialog.dismiss();
<ide>
<del> if(selectedFruitIndex==0){
<add> if (selectedFruitIndex == 0) {
<ide> showTextView.setText("范围:1000m内");
<del> }else if(selectedFruitIndex==1){
<add> } else if (selectedFruitIndex == 1) {
<ide> showTextView.setText("范围:2000m内");
<del> } else if(selectedFruitIndex==2){
<add> } else if (selectedFruitIndex == 2) {
<ide> showTextView.setText("范围:3000m内");
<del> } else if(selectedFruitIndex==3){
<add> } else if (selectedFruitIndex == 3) {
<ide> showTextView.setText("范围:4000m内");
<del> } else if(selectedFruitIndex==4){
<add> } else if (selectedFruitIndex == 4) {
<ide> showTextView.setText("范围:5000m内");
<ide> }
<ide> }
<ide> alertDialog.show();
<ide>
<ide>
<del>
<ide> }
<ide>
<ide> public void listView() {
<ide> listView = (ListView) findViewById(R.id.listView);
<del> for (int i = 0; i < 20; i++) {
<del> HashMap<String, Object> item = new HashMap<String, Object>();
<del> item.put("title", "黄记煌三汁焖锅");
<del> item.put("address", "西安南大街52号南附楼内3层” ");
<del> item.put("fanwei", " 500m");
<del> if (i == 1) {
<del> item.put("title", "香港私家菜天子海鲜火锅 " + i);
<del> item.put("address", "南大街 " + i + " " + i);
<del> item.put("fanwei", "500m");
<del> data.add(item);
<del> continue;
<del> }
<del> data.add(item);
<del> }
<del> SimpleAdapter adapter = new SimpleAdapter(this,
<del> data,
<add>
<add> simpleAdapter = new SimpleAdapter(this,
<add> list,
<ide> R.layout.chat_item,
<del> new String[]{"title", "address", "fanwei"},
<add> new String[]{"name", "address", "distance"},
<ide> new int[]{R.id.TittleText, R.id.AddressMessage, R.id.fanwei});
<ide>
<ide>
<del> listView.setAdapter(adapter);
<add> listView.setAdapter(simpleAdapter);
<ide>
<ide>
<ide> listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
<ide> });
<ide>
<ide> }
<del> public void mainBack(){
<add>
<add> public void mainBack() {
<ide> mainBackButton = (ImageButton) findViewById(R.id.main_back);
<ide> mainBackButton.setOnClickListener(new View.OnClickListener() {
<ide> @Override
<ide> public void onClick(View view) {
<del> MyActivity.this.finish();
<add> MyActivity.this.finish();
<ide>
<ide>
<ide> } |
|
Java | apache-2.0 | error: pathspec 'core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java' did not match any file(s) known to git
| 90cfee4c0108a6aaa05b13c9a9edcd71c94fda68 | 1 | HashEngineering/dashj,HashEngineering/dashj,HashEngineering/darkcoinj,HashEngineering/darkcoinj,HashEngineering/dashj,HashEngineering/darkcoinj,HashEngineering/dashj | package org.bitcoinj.quorums;
import org.bitcoinj.core.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by hashengineering on 5/1/19.
*/
public class LLMQBackgroundThread extends Thread {
private static final Logger log = LoggerFactory.getLogger(LLMQBackgroundThread.class);
Context context;
public LLMQBackgroundThread(Context context) {
this.context = context;
}
int debugTimer = 0;
@Override
public void run() {
Context.propagate(context);
try {
context.signingManager.addRecoveredSignatureListener(context.instantSendManager);
context.signingManager.addRecoveredSignatureListener(context.chainLockHandler);
while (!isInterrupted()) {
boolean didWork = false;
didWork |= context.instantSendManager.processPendingInstantSendLocks();
didWork |= context.signingManager.processPendingRecoveredSigs();
context.signingManager.cleanup();
if (!didWork) {
Thread.sleep(100);
} else {
debugTimer++;
if(debugTimer % 100 == 0) {
log.info(context.instantSendManager.toString());
}
}
}
} catch (InterruptedException x) {
//let the thread stop
context.signingManager.removeRecoveredSignatureListener(context.instantSendManager);
context.signingManager.removeRecoveredSignatureListener(context.chainLockHandler);
}
}
}
| core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java | Add LLMQBackgroundThread that handles InstantSendLocks and RecoveredSigs
Signed-off-by: HashEngineering <[email protected]>
| core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java | Add LLMQBackgroundThread that handles InstantSendLocks and RecoveredSigs | <ide><path>ore/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java
<add>package org.bitcoinj.quorums;
<add>
<add>import org.bitcoinj.core.Context;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<add>
<add>/**
<add> * Created by hashengineering on 5/1/19.
<add> */
<add>public class LLMQBackgroundThread extends Thread {
<add> private static final Logger log = LoggerFactory.getLogger(LLMQBackgroundThread.class);
<add>
<add> Context context;
<add> public LLMQBackgroundThread(Context context) {
<add> this.context = context;
<add> }
<add>
<add> int debugTimer = 0;
<add>
<add> @Override
<add> public void run() {
<add> Context.propagate(context);
<add> try {
<add> context.signingManager.addRecoveredSignatureListener(context.instantSendManager);
<add> context.signingManager.addRecoveredSignatureListener(context.chainLockHandler);
<add> while (!isInterrupted()) {
<add> boolean didWork = false;
<add>
<add> didWork |= context.instantSendManager.processPendingInstantSendLocks();
<add>
<add> didWork |= context.signingManager.processPendingRecoveredSigs();
<add>
<add> context.signingManager.cleanup();
<add>
<add>
<add>
<add> if (!didWork) {
<add> Thread.sleep(100);
<add> } else {
<add> debugTimer++;
<add> if(debugTimer % 100 == 0) {
<add> log.info(context.instantSendManager.toString());
<add> }
<add> }
<add> }
<add> } catch (InterruptedException x) {
<add> //let the thread stop
<add> context.signingManager.removeRecoveredSignatureListener(context.instantSendManager);
<add> context.signingManager.removeRecoveredSignatureListener(context.chainLockHandler);
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | 0827205249079f2c5bacd5d5f975a53f07acbfdf | 0 | asedunov/intellij-community,adedayo/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,slisson/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fnouama/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,caot/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,vvv1559/intellij-community,kool79/intellij-community,Lekanich/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,kdwink/intellij-community,kool79/intellij-community,kdwink/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,jagguli/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,samthor/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ahb0327/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,signed/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,FHannes/intellij-community,diorcety/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,signed/intellij-community,apixandru/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,FHannes/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,supersven/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,slisson/intellij-community,samthor/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,signed/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,izonder/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,jagguli/intellij-community,holmes/intellij-community,kdwink/intellij-community,diorcety/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,suncycheng/intellij-community,caot/intellij-community,asedunov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,samthor/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,semonte/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,fitermay/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ibinti/intellij-community,allotria/intellij-community,fnouama/intellij-community,caot/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,petteyg/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,supersven/intellij-community,semonte/intellij-community,semonte/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,slisson/intellij-community,nicolargo/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,holmes/intellij-community,supersven/intellij-community,asedunov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,caot/intellij-community,robovm/robovm-studio,holmes/intellij-community,fitermay/intellij-community,petteyg/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,dslomov/intellij-community,signed/intellij-community,kdwink/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,samthor/intellij-community,allotria/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,supersven/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,gnuhub/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,diorcety/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,petteyg/intellij-community,kool79/intellij-community,signed/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,izonder/intellij-community,kdwink/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,diorcety/intellij-community,adedayo/intellij-community,blademainer/intellij-community,signed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,kdwink/intellij-community,slisson/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,kool79/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,da1z/intellij-community,jagguli/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,supersven/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,da1z/intellij-community,tmpgit/intellij-community,caot/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,samthor/intellij-community,samthor/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,holmes/intellij-community,xfournet/intellij-community,xfournet/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,allotria/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,diorcety/intellij-community,signed/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,blademainer/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,nicolargo/intellij-community,kool79/intellij-community,holmes/intellij-community,izonder/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,adedayo/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,FHannes/intellij-community,amith01994/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,robovm/robovm-studio,clumsy/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,semonte/intellij-community,ibinti/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,kdwink/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,slisson/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,petteyg/intellij-community,apixandru/intellij-community,slisson/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ibinti/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,blademainer/intellij-community,vladmm/intellij-community,kdwink/intellij-community,supersven/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ibinti/intellij-community,xfournet/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fitermay/intellij-community,diorcety/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,fnouama/intellij-community,kool79/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,supersven/intellij-community,signed/intellij-community,semonte/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,xfournet/intellij-community,caot/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,caot/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,caot/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,allotria/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,kool79/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,robovm/robovm-studio,asedunov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,vladmm/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,samthor/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,clumsy/intellij-community,semonte/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community | package com.intellij.structuralsearch.plugin.ui;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.template.impl.Variable;
import com.intellij.find.FindProgressIndicator;
import com.intellij.find.FindSettings;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.scopeChooser.ScopeChooserCombo;
import com.intellij.lang.Language;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.plugin.StructuralSearchPlugin;
import com.intellij.structuralsearch.plugin.replace.ui.NavigateSearchResultsDialog;
import com.intellij.structuralsearch.plugin.ui.actions.DoSearchAction;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.usages.*;
import com.intellij.util.Alarm;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NonNls;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
// Class to show the user the request for search
@SuppressWarnings({"RefusedBequest", "AssignmentToStaticFieldFromInstanceMethod"})
public class SearchDialog extends DialogWrapper implements ConfigurationCreator {
protected SearchContext searchContext;
// text for search
protected Editor searchCriteriaEdit;
// options of search scope
private ScopeChooserCombo myScopeChooserCombo;
private JCheckBox searchIncrementally;
private JCheckBox recursiveMatching;
//private JCheckBox distinctResults;
private JCheckBox caseSensitiveMatch;
private JCheckBox maxMatchesSwitch;
private JTextField maxMatches;
private JComboBox fileTypes;
private JLabel status;
private JLabel statusText;
protected SearchModel model;
private JCheckBox openInNewTab;
private Alarm myAlarm;
public static final String USER_DEFINED = SSRBundle.message("new.template.defaultname");
protected final ExistingTemplatesComponent existingTemplatesComponent;
private boolean useLastConfiguration;
private static boolean ourOpenInNewTab;
private static boolean ourUseMaxCount;
@NonNls private static String ourFileType = "java";
private final boolean myShowScopePanel;
private final boolean myRunFindActionOnClose;
private boolean myDoingOkAction;
public SearchDialog(SearchContext searchContext) {
this(searchContext, true, true);
}
public SearchDialog(SearchContext searchContext, boolean showScope, boolean runFindActionOnClose) {
super(searchContext.getProject(), true);
myShowScopePanel = showScope;
myRunFindActionOnClose = runFindActionOnClose;
this.searchContext = (SearchContext)searchContext.clone();
setTitle(getDefaultTitle());
if (runFindActionOnClose) {
setOKButtonText(SSRBundle.message("ssdialog.find.botton"));
setOKButtonIcon(IconLoader.getIcon("/actions/find.png"));
getOKAction().putValue(Action.MNEMONIC_KEY, new Integer('F'));
}
existingTemplatesComponent = ExistingTemplatesComponent.getInstance(this.searchContext.getProject());
model = new SearchModel(createConfiguration());
myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
init();
}
protected UsageViewContext createUsageViewContext(Configuration configuration) {
return new UsageViewContext(searchContext, configuration);
}
public void setUseLastConfiguration(boolean useLastConfiguration) {
this.useLastConfiguration = useLastConfiguration;
}
protected boolean isChanged(Configuration configuration) {
if (configuration.getMatchOptions().getSearchPattern() == null) return false;
return !searchCriteriaEdit.getDocument().getText().equals(configuration.getMatchOptions().getSearchPattern());
}
public void setSearchPattern(final Configuration config) {
model.setShadowConfig(config);
setValuesFromConfig(config);
initiateValidation();
}
protected Editor createEditor(final SearchContext searchContext) {
PsiElement element = searchContext.getFile();
if (element != null && !useLastConfiguration) {
final Editor selectedEditor = FileEditorManager.getInstance(searchContext.getProject()).getSelectedTextEditor();
if (selectedEditor != null) {
int caretPosition = selectedEditor.getCaretModel().getOffset();
PsiElement positionedElement = searchContext.getFile().findElementAt(caretPosition);
if (positionedElement == null) {
positionedElement = searchContext.getFile().findElementAt(caretPosition + 1);
}
if (positionedElement != null) {
element = PsiTreeUtil.getParentOfType(
positionedElement,
PsiClass.class, PsiCodeBlock.class
);
}
}
}
final PsiManager psimanager = PsiManager.getInstance(searchContext.getProject());
PsiCodeFragment file = psimanager.getElementFactory().createCodeBlockCodeFragment("", element, true);
Document doc = PsiDocumentManager.getInstance(searchContext.getProject()).getDocument(file);
DaemonCodeAnalyzer.getInstance(searchContext.getProject()).setHighlightingEnabled(file, false);
Editor editor = UIUtil.createEditor(doc, searchContext.getProject(), true, true);
editor.getDocument().addDocumentListener(new DocumentListener() {
public void beforeDocumentChange(final DocumentEvent event) {}
public void documentChanged(final DocumentEvent event) {
initiateValidation();
}
});
return editor;
}
private void initiateValidation() {
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run() {
if (!doValidate()) {
getOKAction().setEnabled(false);
} else {
getOKAction().setEnabled(true);
reportMessage(null,null);
}
}
}
);
}
}
);
}
catch (Exception e) {
e.printStackTrace();
}
}
}, 500);
}
protected void buildOptions(JPanel searchOptions) {
searchIncrementally = new JCheckBox(SSRBundle.message("find.with.prompt.checkbox"), false);
if (isSearchOnDemandEnabled()) {
searchOptions.add(
UIUtil.createOptionLine(searchIncrementally)
);
}
recursiveMatching = new JCheckBox(SSRBundle.message("recursive.matching.checkbox"), true);
if (isRecursiveSearchEnabled()) {
searchOptions.add(
UIUtil.createOptionLine(recursiveMatching)
);
}
//searchOptions.add(
// UIUtil.createOptionLine(
// distinctResults = new JCheckBox("Distinct results",false)
// )
//);
//
//distinctResults.setMnemonic('D');
caseSensitiveMatch = new JCheckBox(SSRBundle.message("case.sensitive.checkbox"), true);
searchOptions.add(UIUtil.createOptionLine(caseSensitiveMatch));
searchOptions.add(
UIUtil.createOptionLine(
new JComponent[]{
maxMatchesSwitch = new JCheckBox(SSRBundle.message("maximum.matches.checkbox"), false),
maxMatches = new JTextField(
Integer.toString(
MatchOptions.DEFAULT_MAX_MATCHES_COUNT
),
3
),
(JComponent)Box.createHorizontalGlue()
}
)
);
maxMatches.setMaximumSize(new Dimension(50, 25));
//noinspection HardCodedStringLiteral
fileTypes = new JComboBox(new String[]{"java", "xml", "html"});
if (ourSupportDifferentFileTypes) {
final JLabel jLabel = new JLabel(SSRBundle.message("search.dialog.file.type.label"));
searchOptions.add(
UIUtil.createOptionLine(
new JComponent[]{
jLabel,
fileTypes,
(JComponent)Box.createHorizontalGlue()
}
)
);
jLabel.setLabelFor(fileTypes);
}
final PsiFile file = searchContext.getFile();
if (file != null) {
Language contextLanguage = null;
if (searchContext.getEditor() != null) {
final PsiElement psiElement = file.findElementAt(searchContext.getEditor().getCaretModel().getOffset());
contextLanguage = psiElement != null ? psiElement.getParent().getLanguage():null;
}
if (file.getFileType() == StdFileTypes.HTML ||
( file.getFileType() == StdFileTypes.JSP &&
contextLanguage == StdLanguages.HTML
)
) {
ourFileType = "html";
}
else if (file.getFileType() == StdFileTypes.XHTML ||
( file.getFileType() == StdFileTypes.JSPX &&
contextLanguage == StdLanguages.HTML
)) {
ourFileType = "xml";
}
else {
ourFileType = "java";
}
}
fileTypes.setSelectedItem(ourFileType);
fileTypes.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) initiateValidation();
}
});
}
protected boolean isRecursiveSearchEnabled() {
return true;
}
public void setValuesFromConfig(Configuration configuration) {
//searchCriteriaEdit.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, configuration);
setDialogTitle(configuration);
final MatchOptions matchOptions = configuration.getMatchOptions();
UIUtil.setContent(
searchCriteriaEdit,
matchOptions.getSearchPattern(),
0,
searchCriteriaEdit.getDocument().getTextLength(),
searchContext.getProject()
);
model.getConfig().getMatchOptions().setSearchPattern(
matchOptions.getSearchPattern()
);
recursiveMatching.setSelected(
isRecursiveSearchEnabled() && matchOptions.isRecursiveSearch()
);
caseSensitiveMatch.setSelected(
matchOptions.isCaseSensitiveMatch()
);
//distinctResults.setSelected(matchOptions.isDistinct());
if (matchOptions.getMaxMatchesCount() != Integer.MAX_VALUE) {
maxMatches.setText(String.valueOf(matchOptions.getMaxMatchesCount()));
}
model.getConfig().getMatchOptions().clearVariableConstraints();
if (matchOptions.hasVariableConstraints()) {
for (Iterator<String> i = matchOptions.getVariableConstraintNames(); i.hasNext();) {
final MatchVariableConstraint constraint = (MatchVariableConstraint)matchOptions.getVariableConstraint(i.next()).clone();
model.getConfig().getMatchOptions().addVariableConstraint(constraint);
if (isReplaceDialog()) constraint.setPartOfSearchResults(false);
}
}
searchIncrementally.setSelected(configuration.isSearchOnDemand());
fileTypes.setSelectedItem(configuration.getMatchOptions().getFileType().getName().toLowerCase());
}
private void setDialogTitle(final Configuration configuration) {
setTitle(getDefaultTitle() + " - " + configuration.getName());
}
public Configuration createConfiguration() {
SearchConfiguration configuration = new SearchConfiguration();
configuration.setName(USER_DEFINED);
return configuration;
}
protected void addOrReplaceSelection(final String selection) {
addOrReplaceSelectionForEditor(selection, searchCriteriaEdit);
}
protected final void addOrReplaceSelectionForEditor(final String selection, Editor editor) {
UIUtil.setContent(editor, selection, 0, -1, searchContext.getProject());
editor.getSelectionModel().setSelection(
0,
selection.length()
);
}
protected void runAction(final Configuration config, final SearchContext searchContext) {
if (searchIncrementally.isSelected()) {
NavigateSearchResultsDialog resultsDialog = createResultsNavigator(searchContext, config);
DoSearchAction.execute(searchContext.getProject(), resultsDialog, config);
}
else {
createUsageView(searchContext, config);
}
}
protected NavigateSearchResultsDialog createResultsNavigator(final SearchContext searchContext, Configuration config) {
return new NavigateSearchResultsDialog(searchContext.getProject(), false);
}
protected void createUsageView(final SearchContext searchContext, final Configuration config) {
UsageViewManager manager = UsageViewManager.getInstance(searchContext.getProject());
final UsageViewContext context = createUsageViewContext(config);
final UsageViewPresentation presentation = new UsageViewPresentation();
presentation.setOpenInNewTab(openInNewTab.isSelected());
presentation.setScopeText(config.getMatchOptions().getScope().getDisplayName());
context.configure(presentation);
final FindUsagesProcessPresentation processPresentation = new FindUsagesProcessPresentation();
processPresentation.setShowNotFoundMessage(true);
processPresentation.setShowPanelIfOnlyOneUsage(true);
processPresentation.setProgressIndicatorFactory(
new Factory<ProgressIndicator>() {
public ProgressIndicator create() {
return new FindProgressIndicator(searchContext.getProject(), presentation.getScopeText()) {
public void cancel() {
context.getCommand().stopAsyncSearch();
super.cancel();
}
};
}
}
);
processPresentation.addNotFoundAction(
new AbstractAction(SSRBundle.message("edit.query.button.description")) {
{
putValue(FindUsagesProcessPresentation.NAME_WITH_MNEMONIC_KEY, SSRBundle.message("edit.query.button"));
}
public void actionPerformed(ActionEvent e) {
UIUtil.invokeAction(config, searchContext);
}
}
);
manager.searchAndShowUsages(
new UsageTarget[]{
context.getTarget()
},
new Factory<UsageSearcher>() {
public UsageSearcher create() {
return new UsageSearcher() {
public void generate(final Processor<Usage> processor) {
context.getCommand().findUsages(processor);
}
};
}
},
processPresentation,
presentation,
new UsageViewManager.UsageViewStateListener() {
public void usageViewCreated(UsageView usageView) {
context.setUsageView(usageView);
configureActions(context);
}
public void findingUsagesFinished(final UsageView usageView) {
}
}
);
}
protected void configureActions(final UsageViewContext context) {
context.getUsageView().addButtonToLowerPane(
new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIUtil.invokeAction(context.getConfiguration(), searchContext);
}
});
}
},
SSRBundle.message("edit.query.button.description")
);
}
protected String getDefaultTitle() {
return SSRBundle.message("structural.search.title");
}
protected JComponent createEditorContent() {
JPanel result = new JPanel(new BorderLayout());
result.add(BorderLayout.NORTH, new JLabel(SSRBundle.message("search.template")));
searchCriteriaEdit = createEditor(searchContext);
result.add(BorderLayout.CENTER, searchCriteriaEdit.getComponent());
result.setMinimumSize(new Dimension(150, 100));
return result;
}
private static boolean ourSupportDifferentFileTypes = true;
protected int getRowsCount() {
return ourSupportDifferentFileTypes ? 4 : 3;
}
protected JComponent createCenterPanel() {
JPanel editorPanel = new JPanel(new BorderLayout());
editorPanel.add(BorderLayout.CENTER, createEditorContent());
editorPanel.add(BorderLayout.SOUTH, Box.createVerticalStrut(8));
JComponent centerPanel = new JPanel(new BorderLayout());
{
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, editorPanel);
panel.add(BorderLayout.SOUTH, createTemplateManagementButtons());
centerPanel.add(BorderLayout.CENTER, panel);
}
JPanel optionsContent = new JPanel(new BorderLayout());
centerPanel.add(BorderLayout.SOUTH, optionsContent);
JPanel searchOptions = new JPanel();
searchOptions.setLayout(new GridLayout(getRowsCount(), 1, 0, 0));
searchOptions.setBorder(IdeBorderFactory.createTitledBorder(SSRBundle.message("ssdialog.options.group.border")));
myScopeChooserCombo = new ScopeChooserCombo(
searchContext.getProject(),
true,
false,
FindSettings.getInstance().getDefaultScopeName()
);
JPanel allOptions = new JPanel(new BorderLayout());
if (myShowScopePanel) {
JPanel scopePanel = new JPanel(new BorderLayout());
scopePanel.add(Box.createVerticalStrut(8), BorderLayout.NORTH);
JLabel label = new JLabel(SSRBundle.message("search.dialog.scope.label"));
scopePanel.add(label, BorderLayout.WEST);
scopePanel.add(myScopeChooserCombo, BorderLayout.CENTER);
label.setLabelFor(myScopeChooserCombo.getComboBox());
allOptions.add(
scopePanel,
BorderLayout.SOUTH
);
myScopeChooserCombo.getComboBox().addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
initiateValidation();
}
});
}
buildOptions(searchOptions);
allOptions.add(searchOptions, BorderLayout.CENTER);
optionsContent.add(allOptions, BorderLayout.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
openInNewTab = new JCheckBox(SSRBundle.message("open.in.new.tab.checkbox"));
openInNewTab.setSelected(ourOpenInNewTab);
ToolWindow findWindow = ToolWindowManager.getInstance(searchContext.getProject()).getToolWindow(ToolWindowId.FIND);
openInNewTab.setEnabled(findWindow != null && findWindow.isAvailable());
panel.add(openInNewTab, BorderLayout.EAST);
optionsContent.add(BorderLayout.SOUTH, panel);
return centerPanel;
}
protected JComponent createSouthPanel() {
final JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.add(super.createSouthPanel(), BorderLayout.NORTH);
statusPanel.add(statusText = new JLabel(SSRBundle.message("status.message")), BorderLayout.WEST);
final String s = SSRBundle.message("status.mnemonic");
if (s.length() > 0) statusText.setDisplayedMnemonic( s.charAt(0) );
statusPanel.add(status = new JLabel(),BorderLayout.CENTER);
return statusPanel;
}
private JPanel createTemplateManagementButtons() {
JPanel panel = new JPanel(null);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createHorizontalGlue());
panel.add(
createJButtonForAction(new AbstractAction() {
{
putValue(NAME, SSRBundle.message("save.template.text.button"));
}
public void actionPerformed(ActionEvent e) {
String name = showSaveTemplateAsDialog();
if (name != null) {
final Project project = searchContext.getProject();
final ConfigurationManager configurationManager = StructuralSearchPlugin.getInstance(project).getConfigurationManager();
final Collection<Configuration> configurations = configurationManager.getConfigurations();
if (configurations != null) {
name = ConfigurationManager.findAppropriateName(configurations, name, project);
if (name == null) return;
}
model.getConfig().setName(name);
setValuesToConfig(model.getConfig());
setDialogTitle(model.getConfig());
if (model.getShadowConfig() == null ||
model.getShadowConfig() instanceof PredefinedConfiguration) {
existingTemplatesComponent.addConfigurationToUserTemplates(model.getConfig());
}
else { // ???
setValuesToConfig(model.getShadowConfig());
model.getShadowConfig().setName(name);
}
}
}
})
);
panel.add(
Box.createHorizontalStrut(8)
);
panel.add(
createJButtonForAction(
new AbstractAction() {
{
putValue(NAME, SSRBundle.message("edit.variables.button"));
}
public void actionPerformed(ActionEvent e) {
SubstitutionShortInfoHandler handler = searchCriteriaEdit.getUserData(UIUtil.LISTENER_KEY);
ArrayList<Variable> variables = new ArrayList<Variable>(handler.getVariables());
CompletionTextField.setCurrentProject(searchContext.getProject());
new EditVarConstraintsDialog(
searchContext.getProject(),
model,
variables,
isReplaceDialog(),
getFileTypeByString((String)fileTypes.getSelectedItem())
).show();
initiateValidation();
CompletionTextField.setCurrentProject(null);
}
}
)
);
panel.add(
Box.createHorizontalStrut(8)
);
panel.add(
createJButtonForAction(
new AbstractAction() {
{
putValue(NAME, SSRBundle.message("history.button"));
}
public void actionPerformed(ActionEvent e) {
SelectTemplateDialog dialog = new SelectTemplateDialog(searchContext.getProject(), true, isReplaceDialog());
dialog.show();
if (!dialog.isOK()) {
return;
}
Configuration[] configurations = dialog.getSelectedConfigurations();
if (configurations.length == 1) {
setSearchPattern(configurations[0]);
}
}
}
)
);
panel.add(
Box.createHorizontalStrut(8)
);
panel.add(
createJButtonForAction(
new AbstractAction() {
{
putValue(NAME, SSRBundle.message("copy.existing.template.button"));
}
public void actionPerformed(ActionEvent e) {
SelectTemplateDialog dialog = new SelectTemplateDialog(searchContext.getProject(), false, isReplaceDialog());
dialog.show();
if (!dialog.isOK()) {
return;
}
Configuration[] configurations = dialog.getSelectedConfigurations();
if (configurations.length == 1) {
setSearchPattern(configurations[0]);
}
}
}
)
);
return panel;
}
public final Project getProject() {
return searchContext.getProject();
}
public String showSaveTemplateAsDialog() {
return ConfigurationManager.showSaveTemplateAsDialog(
model.getShadowConfig() != null ? model.getShadowConfig().getName() : "",
searchContext.getProject()
);
}
protected boolean isReplaceDialog() {
return false;
}
public void show() {
Configuration.setActiveCreator(this);
searchCriteriaEdit.putUserData(
SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY,
model.getConfig()
);
maxMatchesSwitch.setSelected(ourUseMaxCount);
if (!useLastConfiguration) {
final Editor editor = FileEditorManager.getInstance(searchContext.getProject()).getSelectedTextEditor();
boolean setSomeText = false;
if (editor != null) {
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
addOrReplaceSelection(selectionModel.getSelectedText());
existingTemplatesComponent.getPatternTree().setSelectionPath(null);
existingTemplatesComponent.getHistoryList().setSelectedIndex(-1);
setSomeText = true;
}
}
if (!setSomeText) {
int selection = existingTemplatesComponent.getHistoryList().getSelectedIndex();
if (selection != -1) {
setValuesFromConfig(
(Configuration)existingTemplatesComponent.getHistoryList().getSelectedValue()
);
}
}
}
initiateValidation();
super.show();
}
public JComponent getPreferredFocusedComponent() {
return searchCriteriaEdit.getContentComponent();
}
// Performs ok action
protected void doOKAction() {
SearchScope selectedScope = getSelectedScope();
if (selectedScope == null) return;
myDoingOkAction = true;
boolean result = doValidate();
myDoingOkAction = false;
if (!result) return;
myAlarm.cancelAllRequests();
super.doOKAction();
if (!myRunFindActionOnClose) return;
FindSettings.getInstance().setDefaultScopeName(selectedScope.getDisplayName());
ourOpenInNewTab = openInNewTab.isSelected();
try {
if (model.getShadowConfig() != null) {
if (model.getShadowConfig() instanceof PredefinedConfiguration) {
model.getConfig().setName(
model.getShadowConfig().getName()
);
} //else {
// // user template, save it
// setValuesToConfig(model.getShadowConfig());
//}
}
existingTemplatesComponent.addConfigurationToHistory(model.getConfig());
runAction(model.getConfig(), searchContext);
}
catch (MalformedPatternException ex) {
reportMessage("this.pattern.is.malformed.message", searchCriteriaEdit, ex.getMessage());
}
}
public Configuration getConfiguration() {
return model.getConfig();
}
private SearchScope getSelectedScope() {
SearchScope selectedScope = myScopeChooserCombo.getSelectedScope();
return selectedScope;
}
protected boolean doValidate() {
setValuesToConfig(model.getConfig());
boolean result = true;
try {
Matcher.validate(searchContext.getProject(), model.getConfig().getMatchOptions());
}
catch (MalformedPatternException ex) {
reportMessage(
"this.pattern.is.malformed.message",
searchCriteriaEdit,
ex.getMessage() != null ? ex.getMessage():""
);
result = false;
}
catch (UnsupportedPatternException ex) {
reportMessage("this.pattern.is.unsupported.message", searchCriteriaEdit, ex.getPattern());
result = false;
}
//getOKAction().setEnabled(result);
return result;
}
protected void reportMessage(@NonNls String messageId, Editor editor, Object... params) {
final String message = messageId != null ? SSRBundle.message(messageId, params) : "";
status.setText(message);
status.setToolTipText(message);
status.revalidate();
statusText.setLabelFor(editor != null ? editor.getContentComponent() : null);
}
protected void setValuesToConfig(Configuration config) {
MatchOptions options = config.getMatchOptions();
boolean searchWithinHierarchy = IdeBundle.message("scope.class.hierarchy").equals(myScopeChooserCombo.getSelectedScopeName());
// We need to reset search within hierarchy scope during online validation since the scope works with user participation
options.setScope(searchWithinHierarchy && !myDoingOkAction? GlobalSearchScope.projectScope(getProject()) :myScopeChooserCombo.getSelectedScope());
options.setLooseMatching(true);
options.setRecursiveSearch(isRecursiveSearchEnabled() && recursiveMatching.isSelected());
//options.setDistinct( distinctResults.isSelected() );
ourUseMaxCount = maxMatchesSwitch.isSelected();
if (maxMatchesSwitch.isSelected()) {
try {
options.setMaxMatchesCount(
Integer.parseInt(maxMatches.getText())
);
}
catch (NumberFormatException ex) {
options.setMaxMatchesCount(
MatchOptions.DEFAULT_MAX_MATCHES_COUNT
);
}
}
else {
options.setMaxMatchesCount(Integer.MAX_VALUE);
}
ourFileType = (String)fileTypes.getSelectedItem();
options.setFileType(getFileTypeByString(ourFileType));
options.setSearchPattern(searchCriteriaEdit.getDocument().getText());
options.setCaseSensitiveMatch(caseSensitiveMatch.isSelected());
config.setSearchOnDemand(isSearchOnDemandEnabled() && searchIncrementally.isSelected());
}
protected FileType getCurrentFileType() {
return getFileTypeByString((String)fileTypes.getSelectedItem());
}
private static FileType getFileTypeByString(String ourFileType) {
//noinspection HardCodedStringLiteral
if (ourFileType.equals("java")) {
return StdFileTypes.JAVA;
}
else //noinspection HardCodedStringLiteral
if (ourFileType.equals("html")) {
return StdFileTypes.HTML;
}
else {
return StdFileTypes.XML;
}
}
protected boolean isSearchOnDemandEnabled() {
return false;
}
protected Action[] createActions() {
return new Action[]{getOKAction(), getCancelAction(), getHelpAction()};
}
protected String getDimensionServiceKey() {
return "#com.intellij.structuralsearch.plugin.ui.SearchDialog";
}
public void dispose() {
Configuration.setActiveCreator(null);
// this will remove from myExcludedSet
DaemonCodeAnalyzer.getInstance(searchContext.getProject()).setHighlightingEnabled(
PsiDocumentManager.getInstance(searchContext.getProject()).getPsiFile(
searchCriteriaEdit.getDocument()
), true
);
EditorFactory.getInstance().releaseEditor(searchCriteriaEdit);
myAlarm.cancelAllRequests();
super.dispose();
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp("find.structuredSearch");
}
public SearchContext getSearchContext() {
return searchContext;
}
}
| plugins/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java | package com.intellij.structuralsearch.plugin.ui;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.template.impl.Variable;
import com.intellij.find.FindProgressIndicator;
import com.intellij.find.FindSettings;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.scopeChooser.ScopeChooserCombo;
import com.intellij.lang.Language;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.plugin.StructuralSearchPlugin;
import com.intellij.structuralsearch.plugin.replace.ui.NavigateSearchResultsDialog;
import com.intellij.structuralsearch.plugin.ui.actions.DoSearchAction;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.usages.*;
import com.intellij.util.Alarm;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NonNls;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
// Class to show the user the request for search
@SuppressWarnings({"RefusedBequest", "AssignmentToStaticFieldFromInstanceMethod"})
public class SearchDialog extends DialogWrapper implements ConfigurationCreator {
protected SearchContext searchContext;
// text for search
protected Editor searchCriteriaEdit;
// options of search scope
private ScopeChooserCombo myScopeChooserCombo;
private JCheckBox searchIncrementally;
private JCheckBox recursiveMatching;
//private JCheckBox distinctResults;
private JCheckBox caseSensitiveMatch;
private JCheckBox maxMatchesSwitch;
private JTextField maxMatches;
private JComboBox fileTypes;
private JLabel status;
private JLabel statusText;
protected SearchModel model;
private JCheckBox openInNewTab;
private Alarm myAlarm;
public static final String USER_DEFINED = SSRBundle.message("new.template.defaultname");
protected final ExistingTemplatesComponent existingTemplatesComponent;
private boolean useLastConfiguration;
private static boolean ourOpenInNewTab;
private static boolean ourUseMaxCount;
@NonNls private static String ourFileType = "java";
private final boolean myShowScopePanel;
private final boolean myRunFindActionOnClose;
private boolean myDoingOkAction;
public SearchDialog(SearchContext searchContext) {
this(searchContext, true, true);
}
public SearchDialog(SearchContext searchContext, boolean showScope, boolean runFindActionOnClose) {
super(searchContext.getProject(), true);
myShowScopePanel = showScope;
myRunFindActionOnClose = runFindActionOnClose;
this.searchContext = (SearchContext)searchContext.clone();
setTitle(getDefaultTitle());
if (runFindActionOnClose) {
setOKButtonText(SSRBundle.message("ssdialog.find.botton"));
setOKButtonIcon(IconLoader.getIcon("/actions/find.png"));
getOKAction().putValue(Action.MNEMONIC_KEY, new Integer('F'));
}
existingTemplatesComponent = ExistingTemplatesComponent.getInstance(this.searchContext.getProject());
model = new SearchModel(createConfiguration());
myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
init();
}
protected UsageViewContext createUsageViewContext(Configuration configuration) {
return new UsageViewContext(searchContext, configuration);
}
public void setUseLastConfiguration(boolean useLastConfiguration) {
this.useLastConfiguration = useLastConfiguration;
}
protected boolean isChanged(Configuration configuration) {
if (configuration.getMatchOptions().getSearchPattern() == null) return false;
return !searchCriteriaEdit.getDocument().getText().equals(configuration.getMatchOptions().getSearchPattern());
}
public void setSearchPattern(final Configuration config) {
model.setShadowConfig(config);
setValuesFromConfig(config);
initiateValidation();
}
protected Editor createEditor(final SearchContext searchContext) {
PsiElement element = searchContext.getFile();
if (element != null && !useLastConfiguration) {
final Editor selectedEditor = FileEditorManager.getInstance(searchContext.getProject()).getSelectedTextEditor();
if (selectedEditor != null) {
int caretPosition = selectedEditor.getCaretModel().getOffset();
PsiElement positionedElement = searchContext.getFile().findElementAt(caretPosition);
if (positionedElement == null) {
positionedElement = searchContext.getFile().findElementAt(caretPosition + 1);
}
if (positionedElement != null) {
element = PsiTreeUtil.getParentOfType(
positionedElement,
PsiClass.class, PsiCodeBlock.class
);
}
}
}
final PsiManager psimanager = PsiManager.getInstance(searchContext.getProject());
PsiCodeFragment file = psimanager.getElementFactory().createCodeBlockCodeFragment("", element, true);
Document doc = PsiDocumentManager.getInstance(searchContext.getProject()).getDocument(file);
DaemonCodeAnalyzer.getInstance(searchContext.getProject()).setHighlightingEnabled(file, false);
Editor editor = UIUtil.createEditor(doc, searchContext.getProject(), true, true);
editor.getDocument().addDocumentListener(new DocumentListener() {
public void beforeDocumentChange(final DocumentEvent event) {}
public void documentChanged(final DocumentEvent event) {
initiateValidation();
}
});
return editor;
}
private void initiateValidation() {
myAlarm.cancelAllRequests();
myAlarm.addRequest(new Runnable() {
public void run() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run() {
if (!doValidate()) {
getOKAction().setEnabled(false);
} else {
getOKAction().setEnabled(true);
reportMessage(null,null);
}
}
}
);
}
}
);
}
catch (Exception e) {
e.printStackTrace();
}
}
}, 500);
}
protected void buildOptions(JPanel searchOptions) {
searchIncrementally = new JCheckBox(SSRBundle.message("find.with.prompt.checkbox"), false);
if (isSearchOnDemandEnabled()) {
searchOptions.add(
UIUtil.createOptionLine(searchIncrementally)
);
}
recursiveMatching = new JCheckBox(SSRBundle.message("recursive.matching.checkbox"), true);
if (isRecursiveSearchEnabled()) {
searchOptions.add(
UIUtil.createOptionLine(recursiveMatching)
);
}
//searchOptions.add(
// UIUtil.createOptionLine(
// distinctResults = new JCheckBox("Distinct results",false)
// )
//);
//
//distinctResults.setMnemonic('D');
caseSensitiveMatch = new JCheckBox(SSRBundle.message("case.sensitive.checkbox"), true);
searchOptions.add(UIUtil.createOptionLine(caseSensitiveMatch));
searchOptions.add(
UIUtil.createOptionLine(
new JComponent[]{
maxMatchesSwitch = new JCheckBox(SSRBundle.message("maximum.matches.checkbox"), false),
maxMatches = new JTextField(
Integer.toString(
MatchOptions.DEFAULT_MAX_MATCHES_COUNT
),
3
),
(JComponent)Box.createHorizontalGlue()
}
)
);
maxMatches.setMaximumSize(new Dimension(50, 25));
//noinspection HardCodedStringLiteral
fileTypes = new JComboBox(new String[]{"java", "xml", "html"});
if (ourSupportDifferentFileTypes) {
final JLabel jLabel = new JLabel(SSRBundle.message("search.dialog.file.type.label"));
searchOptions.add(
UIUtil.createOptionLine(
new JComponent[]{
jLabel,
fileTypes,
(JComponent)Box.createHorizontalGlue()
}
)
);
jLabel.setLabelFor(fileTypes);
}
final PsiFile file = searchContext.getFile();
if (file != null) {
Language contextLanguage = null;
if (searchContext.getEditor() != null) {
final PsiElement psiElement = file.findElementAt(searchContext.getEditor().getCaretModel().getOffset());
contextLanguage = psiElement != null ? psiElement.getParent().getLanguage():null;
}
if (file.getFileType() == StdFileTypes.HTML ||
( file.getFileType() == StdFileTypes.JSP &&
contextLanguage == StdLanguages.HTML
)
) {
ourFileType = "html";
}
else if (file.getFileType() == StdFileTypes.XHTML ||
( file.getFileType() == StdFileTypes.JSPX &&
contextLanguage == StdLanguages.HTML
)) {
ourFileType = "xml";
}
else {
ourFileType = "java";
}
}
fileTypes.setSelectedItem(ourFileType);
fileTypes.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) initiateValidation();
}
});
}
protected boolean isRecursiveSearchEnabled() {
return true;
}
public void setValuesFromConfig(Configuration configuration) {
//searchCriteriaEdit.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, configuration);
setDialogTitle(configuration);
final MatchOptions matchOptions = configuration.getMatchOptions();
UIUtil.setContent(
searchCriteriaEdit,
matchOptions.getSearchPattern(),
0,
searchCriteriaEdit.getDocument().getTextLength(),
searchContext.getProject()
);
model.getConfig().getMatchOptions().setSearchPattern(
matchOptions.getSearchPattern()
);
recursiveMatching.setSelected(
isRecursiveSearchEnabled() && matchOptions.isRecursiveSearch()
);
caseSensitiveMatch.setSelected(
matchOptions.isCaseSensitiveMatch()
);
//distinctResults.setSelected(matchOptions.isDistinct());
if (matchOptions.getMaxMatchesCount() != Integer.MAX_VALUE) {
maxMatches.setText(String.valueOf(matchOptions.getMaxMatchesCount()));
}
model.getConfig().getMatchOptions().clearVariableConstraints();
if (matchOptions.hasVariableConstraints()) {
for (Iterator<String> i = matchOptions.getVariableConstraintNames(); i.hasNext();) {
final MatchVariableConstraint constraint = (MatchVariableConstraint)matchOptions.getVariableConstraint(i.next()).clone();
model.getConfig().getMatchOptions().addVariableConstraint(constraint);
if (isReplaceDialog()) constraint.setPartOfSearchResults(false);
}
}
searchIncrementally.setSelected(configuration.isSearchOnDemand());
fileTypes.setSelectedItem(configuration.getMatchOptions().getFileType().getName().toLowerCase());
}
private void setDialogTitle(final Configuration configuration) {
setTitle(getDefaultTitle() + " - " + configuration.getName());
}
public Configuration createConfiguration() {
SearchConfiguration configuration = new SearchConfiguration();
configuration.setName(USER_DEFINED);
return configuration;
}
protected void addOrReplaceSelection(final String selection) {
addOrReplaceSelectionForEditor(selection, searchCriteriaEdit);
}
protected final void addOrReplaceSelectionForEditor(final String selection, Editor editor) {
UIUtil.setContent(editor, selection, 0, -1, searchContext.getProject());
editor.getSelectionModel().setSelection(
0,
selection.length()
);
}
protected void runAction(final Configuration config, final SearchContext searchContext) {
if (searchIncrementally.isSelected()) {
NavigateSearchResultsDialog resultsDialog = createResultsNavigator(searchContext, config);
DoSearchAction.execute(searchContext.getProject(), resultsDialog, config);
}
else {
createUsageView(searchContext, config);
}
}
protected NavigateSearchResultsDialog createResultsNavigator(final SearchContext searchContext, Configuration config) {
return new NavigateSearchResultsDialog(searchContext.getProject(), false);
}
protected void createUsageView(final SearchContext searchContext, final Configuration config) {
UsageViewManager manager = UsageViewManager.getInstance(searchContext.getProject());
final UsageViewContext context = createUsageViewContext(config);
final UsageViewPresentation presentation = new UsageViewPresentation();
presentation.setOpenInNewTab(openInNewTab.isSelected());
presentation.setScopeText(config.getMatchOptions().getScope().getDisplayName());
context.configure(presentation);
final FindUsagesProcessPresentation processPresentation = new FindUsagesProcessPresentation();
processPresentation.setShowNotFoundMessage(true);
processPresentation.setShowPanelIfOnlyOneUsage(true);
processPresentation.setProgressIndicatorFactory(
new Factory<ProgressIndicator>() {
public ProgressIndicator create() {
return new FindProgressIndicator(searchContext.getProject(), presentation.getScopeText()) {
public void cancel() {
context.getCommand().stopAsyncSearch();
super.cancel();
}
};
}
}
);
processPresentation.addNotFoundAction(
new AbstractAction(SSRBundle.message("edit.query.button.description")) {
{
putValue(FindUsagesProcessPresentation.NAME_WITH_MNEMONIC_KEY, SSRBundle.message("edit.query.button"));
}
public void actionPerformed(ActionEvent e) {
UIUtil.invokeAction(config, searchContext);
}
}
);
manager.searchAndShowUsages(
new UsageTarget[]{
context.getTarget()
},
new Factory<UsageSearcher>() {
public UsageSearcher create() {
return new UsageSearcher() {
public void generate(final Processor<Usage> processor) {
context.getCommand().findUsages(processor);
}
};
}
},
processPresentation,
presentation,
new UsageViewManager.UsageViewStateListener() {
public void usageViewCreated(UsageView usageView) {
context.setUsageView(usageView);
configureActions(context);
}
public void findingUsagesFinished(final UsageView usageView) {
}
}
);
}
protected void configureActions(final UsageViewContext context) {
context.getUsageView().addButtonToLowerPane(
new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIUtil.invokeAction(context.getConfiguration(), searchContext);
}
});
}
},
SSRBundle.message("edit.query.button.description")
);
}
protected String getDefaultTitle() {
return SSRBundle.message("structural.search.title");
}
protected JComponent createEditorContent() {
JPanel result = new JPanel(new BorderLayout());
result.add(BorderLayout.NORTH, new JLabel(SSRBundle.message("search.template")));
searchCriteriaEdit = createEditor(searchContext);
result.add(BorderLayout.CENTER, searchCriteriaEdit.getComponent());
result.setMinimumSize(new Dimension(150, 100));
return result;
}
private static boolean ourSupportDifferentFileTypes = true;
protected int getRowsCount() {
return ourSupportDifferentFileTypes ? 4 : 3;
}
protected JComponent createCenterPanel() {
JPanel editorPanel = new JPanel(new BorderLayout());
editorPanel.add(BorderLayout.CENTER, createEditorContent());
editorPanel.add(BorderLayout.SOUTH, Box.createVerticalStrut(8));
JComponent centerPanel = new JPanel(new BorderLayout());
{
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, editorPanel);
panel.add(BorderLayout.SOUTH, createTemplateManagementButtons());
centerPanel.add(BorderLayout.CENTER, panel);
}
JPanel optionsContent = new JPanel(new BorderLayout());
centerPanel.add(BorderLayout.SOUTH, optionsContent);
JPanel searchOptions = new JPanel();
searchOptions.setLayout(new GridLayout(getRowsCount(), 1, 0, 0));
searchOptions.setBorder(IdeBorderFactory.createTitledBorder(SSRBundle.message("ssdialog.options.group.border")));
myScopeChooserCombo = new ScopeChooserCombo(
searchContext.getProject(),
true,
false,
FindSettings.getInstance().getDefaultScopeName()
);
JPanel allOptions = new JPanel(new BorderLayout());
if (myShowScopePanel) {
JPanel scopePanel = new JPanel(new BorderLayout());
scopePanel.add(Box.createVerticalStrut(8), BorderLayout.NORTH);
JLabel label = new JLabel(SSRBundle.message("search.dialog.scope.label"));
scopePanel.add(label, BorderLayout.WEST);
scopePanel.add(myScopeChooserCombo, BorderLayout.CENTER);
label.setLabelFor(myScopeChooserCombo.getComboBox());
allOptions.add(
scopePanel,
BorderLayout.SOUTH
);
myScopeChooserCombo.getComboBox().addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
initiateValidation();
}
});
}
buildOptions(searchOptions);
allOptions.add(searchOptions, BorderLayout.CENTER);
optionsContent.add(allOptions, BorderLayout.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
openInNewTab = new JCheckBox(SSRBundle.message("open.in.new.tab.checkbox"));
openInNewTab.setSelected(ourOpenInNewTab);
ToolWindow findWindow = ToolWindowManager.getInstance(searchContext.getProject()).getToolWindow(ToolWindowId.FIND);
openInNewTab.setEnabled(findWindow != null && findWindow.isAvailable());
panel.add(openInNewTab, BorderLayout.EAST);
optionsContent.add(BorderLayout.SOUTH, panel);
return centerPanel;
}
protected JComponent createSouthPanel() {
final JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.add(super.createSouthPanel(), BorderLayout.NORTH);
statusPanel.add(statusText = new JLabel(SSRBundle.message("status.message")), BorderLayout.WEST);
final String s = SSRBundle.message("status.mnemonic");
if (s.length() > 0) statusText.setDisplayedMnemonic( s.charAt(0) );
statusPanel.add(status = new JLabel(),BorderLayout.CENTER);
return statusPanel;
}
private JPanel createTemplateManagementButtons() {
JPanel panel = new JPanel(null);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createHorizontalGlue());
panel.add(
createJButtonForAction(new AbstractAction() {
{
putValue(NAME, SSRBundle.message("save.template.text.button"));
}
public void actionPerformed(ActionEvent e) {
String name = showSaveTemplateAsDialog();
if (name != null) {
final Project project = searchContext.getProject();
final ConfigurationManager configurationManager = StructuralSearchPlugin.getInstance(project).getConfigurationManager();
final Collection<Configuration> configurations = configurationManager.getConfigurations();
if (configurations != null) {
name = ConfigurationManager.findAppropriateName(configurations, name, project);
if (name == null) return;
}
model.getConfig().setName(name);
setValuesToConfig(model.getConfig());
setDialogTitle(model.getConfig());
if (model.getShadowConfig() == null ||
model.getShadowConfig() instanceof PredefinedConfiguration) {
existingTemplatesComponent.addConfigurationToUserTemplates(model.getConfig());
}
else { // ???
setValuesToConfig(model.getShadowConfig());
model.getShadowConfig().setName(name);
}
}
}
})
);
panel.add(
Box.createHorizontalStrut(8)
);
panel.add(
createJButtonForAction(
new AbstractAction() {
{
putValue(NAME, SSRBundle.message("edit.variables.button"));
}
public void actionPerformed(ActionEvent e) {
SubstitutionShortInfoHandler handler = searchCriteriaEdit.getUserData(UIUtil.LISTENER_KEY);
ArrayList<Variable> variables = new ArrayList<Variable>(handler.getVariables());
CompletionTextField.setCurrentProject(searchContext.getProject());
new EditVarConstraintsDialog(
searchContext.getProject(),
model,
variables,
isReplaceDialog(),
getFileTypeByString((String)fileTypes.getSelectedItem())
).show();
initiateValidation();
CompletionTextField.setCurrentProject(null);
}
}
)
);
panel.add(
Box.createHorizontalStrut(8)
);
panel.add(
createJButtonForAction(
new AbstractAction() {
{
putValue(NAME, SSRBundle.message("history.button"));
}
public void actionPerformed(ActionEvent e) {
SelectTemplateDialog dialog = new SelectTemplateDialog(searchContext.getProject(), true, isReplaceDialog());
dialog.show();
if (!dialog.isOK()) {
return;
}
Configuration[] configurations = dialog.getSelectedConfigurations();
if (configurations.length == 1) {
setSearchPattern(configurations[0]);
}
}
}
)
);
panel.add(
Box.createHorizontalStrut(8)
);
panel.add(
createJButtonForAction(
new AbstractAction() {
{
putValue(NAME, SSRBundle.message("copy.existing.template.button"));
}
public void actionPerformed(ActionEvent e) {
SelectTemplateDialog dialog = new SelectTemplateDialog(searchContext.getProject(), false, isReplaceDialog());
dialog.show();
if (!dialog.isOK()) {
return;
}
Configuration[] configurations = dialog.getSelectedConfigurations();
if (configurations.length == 1) {
setSearchPattern(configurations[0]);
}
}
}
)
);
return panel;
}
public final Project getProject() {
return searchContext.getProject();
}
public String showSaveTemplateAsDialog() {
return ConfigurationManager.showSaveTemplateAsDialog(
model.getShadowConfig() != null ? model.getShadowConfig().getName() : "",
searchContext.getProject()
);
}
protected boolean isReplaceDialog() {
return false;
}
public void show() {
Configuration.setActiveCreator(this);
searchCriteriaEdit.putUserData(
SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY,
model.getConfig()
);
maxMatchesSwitch.setSelected(ourUseMaxCount);
if (!useLastConfiguration) {
final Editor editor = FileEditorManager.getInstance(searchContext.getProject()).getSelectedTextEditor();
boolean setSomeText = false;
if (editor != null) {
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
addOrReplaceSelection(selectionModel.getSelectedText());
existingTemplatesComponent.getPatternTree().setSelectionPath(null);
existingTemplatesComponent.getHistoryList().setSelectedIndex(-1);
setSomeText = true;
}
}
if (!setSomeText) {
int selection = existingTemplatesComponent.getHistoryList().getSelectedIndex();
if (selection != -1) {
setValuesFromConfig(
(Configuration)existingTemplatesComponent.getHistoryList().getSelectedValue()
);
}
}
}
initiateValidation();
super.show();
}
public JComponent getPreferredFocusedComponent() {
return searchCriteriaEdit.getContentComponent();
}
// Performs ok action
protected void doOKAction() {
SearchScope selectedScope = getSelectedScope();
if (selectedScope == null) return;
myDoingOkAction = true;
boolean result = doValidate();
myDoingOkAction = false;
if (!result) return;
super.doOKAction();
if (!myRunFindActionOnClose) return;
FindSettings.getInstance().setDefaultScopeName(selectedScope.getDisplayName());
ourOpenInNewTab = openInNewTab.isSelected();
try {
if (model.getShadowConfig() != null) {
if (model.getShadowConfig() instanceof PredefinedConfiguration) {
model.getConfig().setName(
model.getShadowConfig().getName()
);
} //else {
// // user template, save it
// setValuesToConfig(model.getShadowConfig());
//}
}
existingTemplatesComponent.addConfigurationToHistory(model.getConfig());
runAction(model.getConfig(), searchContext);
}
catch (MalformedPatternException ex) {
reportMessage("this.pattern.is.malformed.message", searchCriteriaEdit, ex.getMessage());
}
}
public Configuration getConfiguration() {
return model.getConfig();
}
private SearchScope getSelectedScope() {
SearchScope selectedScope = myScopeChooserCombo.getSelectedScope();
return selectedScope;
}
protected boolean doValidate() {
setValuesToConfig(model.getConfig());
boolean result = true;
try {
Matcher.validate(searchContext.getProject(), model.getConfig().getMatchOptions());
}
catch (MalformedPatternException ex) {
reportMessage(
"this.pattern.is.malformed.message",
searchCriteriaEdit,
ex.getMessage() != null ? ex.getMessage():""
);
result = false;
}
catch (UnsupportedPatternException ex) {
reportMessage("this.pattern.is.unsupported.message", searchCriteriaEdit, ex.getPattern());
result = false;
}
//getOKAction().setEnabled(result);
return result;
}
protected void reportMessage(@NonNls String messageId, Editor editor, Object... params) {
final String message = messageId != null ? SSRBundle.message(messageId, params) : "";
status.setText(message);
status.setToolTipText(message);
status.revalidate();
statusText.setLabelFor(editor != null ? editor.getContentComponent() : null);
}
protected void setValuesToConfig(Configuration config) {
MatchOptions options = config.getMatchOptions();
boolean searchWithinHierarchy = IdeBundle.message("scope.class.hierarchy").equals(myScopeChooserCombo.getSelectedScopeName());
// We need to reset search within hierarchy scope during online validation since the scope works with user participation
options.setScope(searchWithinHierarchy && !myDoingOkAction? GlobalSearchScope.projectScope(getProject()) :myScopeChooserCombo.getSelectedScope());
options.setLooseMatching(true);
options.setRecursiveSearch(isRecursiveSearchEnabled() && recursiveMatching.isSelected());
//options.setDistinct( distinctResults.isSelected() );
ourUseMaxCount = maxMatchesSwitch.isSelected();
if (maxMatchesSwitch.isSelected()) {
try {
options.setMaxMatchesCount(
Integer.parseInt(maxMatches.getText())
);
}
catch (NumberFormatException ex) {
options.setMaxMatchesCount(
MatchOptions.DEFAULT_MAX_MATCHES_COUNT
);
}
}
else {
options.setMaxMatchesCount(Integer.MAX_VALUE);
}
ourFileType = (String)fileTypes.getSelectedItem();
options.setFileType(getFileTypeByString(ourFileType));
options.setSearchPattern(searchCriteriaEdit.getDocument().getText());
options.setCaseSensitiveMatch(caseSensitiveMatch.isSelected());
config.setSearchOnDemand(isSearchOnDemandEnabled() && searchIncrementally.isSelected());
}
protected FileType getCurrentFileType() {
return getFileTypeByString((String)fileTypes.getSelectedItem());
}
private static FileType getFileTypeByString(String ourFileType) {
//noinspection HardCodedStringLiteral
if (ourFileType.equals("java")) {
return StdFileTypes.JAVA;
}
else //noinspection HardCodedStringLiteral
if (ourFileType.equals("html")) {
return StdFileTypes.HTML;
}
else {
return StdFileTypes.XML;
}
}
protected boolean isSearchOnDemandEnabled() {
return false;
}
protected Action[] createActions() {
return new Action[]{getOKAction(), getCancelAction(), getHelpAction()};
}
protected String getDimensionServiceKey() {
return "#com.intellij.structuralsearch.plugin.ui.SearchDialog";
}
public void dispose() {
Configuration.setActiveCreator(null);
// this will remove from myExcludedSet
DaemonCodeAnalyzer.getInstance(searchContext.getProject()).setHighlightingEnabled(
PsiDocumentManager.getInstance(searchContext.getProject()).getPsiFile(
searchCriteriaEdit.getDocument()
), true
);
EditorFactory.getInstance().releaseEditor(searchCriteriaEdit);
myAlarm.cancelAllRequests();
super.dispose();
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp("find.structuredSearch");
}
public SearchContext getSearchContext() {
return searchContext;
}
}
| [#5579] MPE: PatternCompiler.compilePatternImpl (IDEADEV-17990)
| plugins/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java | [#5579] MPE: PatternCompiler.compilePatternImpl (IDEADEV-17990) | <ide><path>lugins/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java
<ide> myDoingOkAction = false;
<ide> if (!result) return;
<ide>
<add> myAlarm.cancelAllRequests();
<ide> super.doOKAction();
<ide> if (!myRunFindActionOnClose) return;
<ide> |
|
Java | apache-2.0 | 851da005623e26fcd6e3542fb916eabb27957194 | 0 | orekyuu/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,petteyg/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,signed/intellij-community,semonte/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,clumsy/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,kool79/intellij-community,retomerz/intellij-community,allotria/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,caot/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,vladmm/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,samthor/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,jagguli/intellij-community,supersven/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,samthor/intellij-community,amith01994/intellij-community,izonder/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,xfournet/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,clumsy/intellij-community,holmes/intellij-community,xfournet/intellij-community,semonte/intellij-community,hurricup/intellij-community,holmes/intellij-community,ahb0327/intellij-community,holmes/intellij-community,diorcety/intellij-community,caot/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,clumsy/intellij-community,izonder/intellij-community,dslomov/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,samthor/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,semonte/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,kool79/intellij-community,slisson/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,kool79/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,izonder/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,robovm/robovm-studio,slisson/intellij-community,asedunov/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,apixandru/intellij-community,supersven/intellij-community,apixandru/intellij-community,xfournet/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,adedayo/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kdwink/intellij-community,vladmm/intellij-community,semonte/intellij-community,fitermay/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,fnouama/intellij-community,caot/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,clumsy/intellij-community,diorcety/intellij-community,holmes/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,kool79/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,da1z/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,hurricup/intellij-community,amith01994/intellij-community,petteyg/intellij-community,supersven/intellij-community,dslomov/intellij-community,adedayo/intellij-community,samthor/intellij-community,samthor/intellij-community,dslomov/intellij-community,allotria/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,signed/intellij-community,signed/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,da1z/intellij-community,apixandru/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,da1z/intellij-community,ibinti/intellij-community,da1z/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,allotria/intellij-community,izonder/intellij-community,signed/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,amith01994/intellij-community,dslomov/intellij-community,allotria/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,semonte/intellij-community,ryano144/intellij-community,signed/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,izonder/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,amith01994/intellij-community,petteyg/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,izonder/intellij-community,slisson/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,signed/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,clumsy/intellij-community,FHannes/intellij-community,blademainer/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,dslomov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,xfournet/intellij-community,holmes/intellij-community,holmes/intellij-community,supersven/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,samthor/intellij-community,izonder/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,caot/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,supersven/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,apixandru/intellij-community,ryano144/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ryano144/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,allotria/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,blademainer/intellij-community,xfournet/intellij-community,supersven/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,semonte/intellij-community,izonder/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,da1z/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,supersven/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,jagguli/intellij-community,amith01994/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ryano144/intellij-community,ibinti/intellij-community,apixandru/intellij-community,blademainer/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,signed/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,slisson/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,semonte/intellij-community,ryano144/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,FHannes/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,holmes/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,akosyakov/intellij-community,kool79/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,kdwink/intellij-community,retomerz/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ryano144/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,gnuhub/intellij-community,holmes/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,kool79/intellij-community,semonte/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,hurricup/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,supersven/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,caot/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fnouama/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,da1z/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,allotria/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,robovm/robovm-studio,jagguli/intellij-community,samthor/intellij-community,kool79/intellij-community,xfournet/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community | /*
* Copyright 2000-2013 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.updateSettings.impl.pluginsAdvertisement;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.ide.plugins.*;
import com.intellij.notification.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.net.HttpConfigurable;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PluginsAdvertiser implements StartupActivity {
private static final Logger LOG = Logger.getInstance("#" + PluginsAdvertiser.class.getName());
public static List<PluginId> retrieve(UnknownFeature unknownFeature) {
final String featureType = unknownFeature.getFeatureType();
final String implementationName = unknownFeature.getImplementationName();
final String buildNumber = ApplicationInfo.getInstance().getBuild().asString();
final String pluginRepositoryUrl = "http://plugins.jetbrains.com/feature/getImplementations?" +
"featureType=" + featureType +
"&implementationName=" + implementationName +
"&build=" + buildNumber;
try {
HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(pluginRepositoryUrl);
connection.connect();
final InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
try {
final JsonElement jsonRootElement = new JsonParser().parse(streamReader);
final List<PluginId> result = new ArrayList<PluginId>();
for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
final JsonElement pluginId = jsonObject.get("pluginId");
result.add(PluginId.getId(StringUtil.unquoteString(pluginId.toString())));
}
return result;
}
finally {
streamReader.close();
}
}
catch (IOException e) {
LOG.error(e);
}
return null;
}
@Override
public void runActivity(@NotNull final Project project) {
final UnknownFeaturesCollector collectorSuggester = UnknownFeaturesCollector.getInstance(project);
final Set<UnknownFeature> unknownFeatures = collectorSuggester.getUnknownFeatures();
if (unknownFeatures.isEmpty()) return;
final Runnable runnable = new Runnable() {
public void run() {
final Application application = ApplicationManager.getApplication();
if (application.isUnitTestMode() || application.isHeadlessEnvironment()) return;
ProgressManager.getInstance().run(new Task.Backgroundable(project, "Search for non-bundled plugins in plugin repository...") {
private final Set<PluginDownloader> myPlugins = new HashSet<PluginDownloader>();
private List<IdeaPluginDescriptor> myAllPlugins;
@Override
public void run(@NotNull ProgressIndicator indicator) {
int idx = 0;
final Set<PluginId> ids = new HashSet<PluginId>();
for (UnknownFeature feature : unknownFeatures) {
indicator.setText("Searching for: " + feature.getFeatureType());
final List<PluginId> pluginId = retrieve(feature);
if (pluginId != null) {
//do not suggest to download disabled plugins
final List<String> disabledPlugins = PluginManagerCore.getDisabledPlugins();
for (PluginId id : pluginId) {
if (!disabledPlugins.contains(id.getIdString())) {
ids.add(id);
}
}
}
indicator.setFraction(idx++ / unknownFeatures.size());
}
try {
myAllPlugins = RepositoryHelper.loadPluginsFromRepository(indicator);
for (IdeaPluginDescriptor loadedPlugin : myAllPlugins) {
if (ids.contains(loadedPlugin.getPluginId())) {
myPlugins.add(PluginDownloader.createDownloader(loadedPlugin));
}
}
}
catch (Exception ignore) {
//no notification to show
}
}
@Override
public void onSuccess() {
if (!myPlugins.isEmpty()) {
final String displayId = "Plugins Suggestion";
new NotificationGroup(displayId, NotificationDisplayType.STICKY_BALLOON, true)
.createNotification(displayId, "Features covered by non-bundled plugins are detected.<br>" +
"<a href=\"configure\">Configure plugins...</a><br>" +
"<a href=\"ignore\">Ignore All</a>", NotificationType.INFORMATION, new NotificationListener() {
@Override
public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
final String description = event.getDescription();
if ("ignore".equals(description)) {
for (UnknownFeature feature : unknownFeatures) {
collectorSuggester.ignoreFeature(feature);
}
} else if ("configure".equals(description)) {
LOG.assertTrue(myAllPlugins != null);
new PluginsAdvertiserDialog(myProject, myPlugins.toArray(new PluginDownloader[myPlugins.size()]), myAllPlugins).show();
}
notification.expire();
}
}
}).notify(project);
}
}
});
}
};
SwingUtilities.invokeLater(runnable);
}
}
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java | /*
* Copyright 2000-2013 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.updateSettings.impl.pluginsAdvertisement;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.ide.plugins.*;
import com.intellij.notification.*;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.net.HttpConfigurable;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PluginsAdvertiser implements StartupActivity {
private static final Logger LOG = Logger.getInstance("#" + PluginsAdvertiser.class.getName());
public static List<PluginId> retrieve(UnknownFeature unknownFeature) {
final String featureType = unknownFeature.getFeatureType();
final String implementationName = unknownFeature.getImplementationName();
final String buildNumber = ApplicationInfo.getInstance().getBuild().asString();
final String pluginRepositoryUrl = "http://plugins.jetbrains.com/feature/getImplementations?" +
"featureType=" + featureType +
"&implementationName=" + implementationName +
"&build=" + buildNumber;
try {
HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(pluginRepositoryUrl);
connection.connect();
final InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
try {
final JsonElement jsonRootElement = new JsonParser().parse(streamReader);
final List<PluginId> result = new ArrayList<PluginId>();
for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
final JsonElement pluginId = jsonObject.get("pluginId");
result.add(PluginId.getId(StringUtil.unquoteString(pluginId.toString())));
}
return result;
}
finally {
streamReader.close();
}
}
catch (IOException e) {
LOG.error(e);
}
return null;
}
@Override
public void runActivity(@NotNull final Project project) {
final UnknownFeaturesCollector collectorSuggester = UnknownFeaturesCollector.getInstance(project);
final Set<UnknownFeature> unknownFeatures = collectorSuggester.getUnknownFeatures();
if (unknownFeatures.isEmpty()) return;
final Runnable runnable = new Runnable() {
public void run() {
ProgressManager.getInstance().run(new Task.Backgroundable(project, "Search for non-bundled plugins in plugin repository...") {
private final Set<PluginDownloader> myPlugins = new HashSet<PluginDownloader>();
private List<IdeaPluginDescriptor> myAllPlugins;
@Override
public void run(@NotNull ProgressIndicator indicator) {
int idx = 0;
final Set<PluginId> ids = new HashSet<PluginId>();
for (UnknownFeature feature : unknownFeatures) {
indicator.setText("Searching for: " + feature.getFeatureType());
final List<PluginId> pluginId = retrieve(feature);
if (pluginId != null) {
//do not suggest to download disabled plugins
final List<String> disabledPlugins = PluginManagerCore.getDisabledPlugins();
for (PluginId id : pluginId) {
if (!disabledPlugins.contains(id.getIdString())) {
ids.add(id);
}
}
}
indicator.setFraction(idx++ / unknownFeatures.size());
}
try {
myAllPlugins = RepositoryHelper.loadPluginsFromRepository(indicator);
for (IdeaPluginDescriptor loadedPlugin : myAllPlugins) {
if (ids.contains(loadedPlugin.getPluginId())) {
myPlugins.add(PluginDownloader.createDownloader(loadedPlugin));
}
}
}
catch (Exception ignore) {
//no notification to show
}
}
@Override
public void onSuccess() {
if (!myPlugins.isEmpty()) {
final String displayId = "Plugins Suggestion";
new NotificationGroup(displayId, NotificationDisplayType.STICKY_BALLOON, true)
.createNotification(displayId, "Features covered by non-bundled plugins are detected.<br>" +
"<a href=\"configure\">Configure plugins...</a><br>" +
"<a href=\"ignore\">Ignore All</a>", NotificationType.INFORMATION, new NotificationListener() {
@Override
public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
final String description = event.getDescription();
if ("ignore".equals(description)) {
for (UnknownFeature feature : unknownFeatures) {
collectorSuggester.ignoreFeature(feature);
}
} else if ("configure".equals(description)) {
LOG.assertTrue(myAllPlugins != null);
new PluginsAdvertiserDialog(myProject, myPlugins.toArray(new PluginDownloader[myPlugins.size()]), myAllPlugins).show();
}
notification.expire();
}
}
}).notify(project);
}
}
});
}
};
SwingUtilities.invokeLater(runnable);
}
}
| skip advs in tests and headless mode
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java | skip advs in tests and headless mode | <ide><path>latform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java
<ide> import com.google.gson.JsonParser;
<ide> import com.intellij.ide.plugins.*;
<ide> import com.intellij.notification.*;
<add>import com.intellij.openapi.application.Application;
<ide> import com.intellij.openapi.application.ApplicationInfo;
<add>import com.intellij.openapi.application.ApplicationManager;
<ide> import com.intellij.openapi.diagnostic.Logger;
<ide> import com.intellij.openapi.extensions.PluginId;
<ide> import com.intellij.openapi.progress.ProgressIndicator;
<ide> if (unknownFeatures.isEmpty()) return;
<ide> final Runnable runnable = new Runnable() {
<ide> public void run() {
<add> final Application application = ApplicationManager.getApplication();
<add> if (application.isUnitTestMode() || application.isHeadlessEnvironment()) return;
<ide> ProgressManager.getInstance().run(new Task.Backgroundable(project, "Search for non-bundled plugins in plugin repository...") {
<ide> private final Set<PluginDownloader> myPlugins = new HashSet<PluginDownloader>();
<ide> private List<IdeaPluginDescriptor> myAllPlugins; |
|
Java | apache-2.0 | 886200114548a311319d3fd7b59cc02a1fc48e22 | 0 | JetBrains/xodus,JetBrains/xodus,JetBrains/xodus | /**
* Copyright 2010 - 2017 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 jetbrains.exodus.entitystore;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.core.dataStructures.ConcurrentObjectCache;
import jetbrains.exodus.core.dataStructures.ObjectCacheBase;
import jetbrains.exodus.core.dataStructures.Priority;
import jetbrains.exodus.core.execution.Job;
import jetbrains.exodus.core.execution.SharedTimer;
import jetbrains.exodus.entitystore.iterate.EntityIterableBase;
import jetbrains.exodus.env.ReadonlyTransactionException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.WeakReference;
public final class EntityIterableCache {
private static final Logger logger = LoggerFactory.getLogger(EntityIterableCache.class);
@NotNull
private final PersistentEntityStoreImpl store;
@NotNull
private final PersistentEntityStoreConfig config;
@NotNull
private EntityIterableCacheAdapter cacheAdapter;
@NotNull
private ObjectCacheBase<Object, Long> deferredIterablesCache;
@NotNull
private ObjectCacheBase<Object, Long> iterableCountsCache;
@NotNull
final EntityStoreSharedAsyncProcessor processor;
public EntityIterableCache(@NotNull final PersistentEntityStoreImpl store) {
this.store = store;
config = store.getConfig();
cacheAdapter = new EntityIterableCacheAdapter(config);
clear();
processor = new EntityStoreSharedAsyncProcessor(config.getEntityIterableCacheThreadCount());
processor.start();
SharedTimer.registerPeriodicTask(new CacheHitRateAdjuster(this));
}
public float hitRate() {
return cacheAdapter.hitRate();
}
public int count() {
return cacheAdapter.count();
}
public void clear() {
cacheAdapter.clear();
final int cacheSize = config.getEntityIterableCacheSize();
deferredIterablesCache = new ConcurrentObjectCache<>(cacheSize);
iterableCountsCache = new ConcurrentObjectCache<>(cacheSize * 2);
}
/**
* @param it iterable.
* @return iterable which is cached or "it" itself if it's not cached.
*/
public EntityIterableBase putIfNotCached(@NotNull final EntityIterableBase it) {
if (config.isCachingDisabled() || !it.canBeCached()) {
return it;
}
final EntityIterableHandle handle = it.getHandle();
final PersistentStoreTransaction txn = it.getTransaction();
final EntityIterableCacheAdapter localCache = txn.getLocalCache();
txn.localCacheAttempt();
final EntityIterableBase cached = localCache.tryKey(handle);
if (cached != null) {
if (!cached.getHandle().isExpired()) {
txn.localCacheHit();
return cached;
}
localCache.remove(handle);
}
if (txn.isMutable() || !txn.isCurrent() || !txn.isCachingRelevant()) {
return it;
}
// if cache is enough full, then cache iterables after they live some time in deferred cache
if (!localCache.isSparse()) {
final long currentMillis = System.currentTimeMillis();
final Object handleIdentity = handle.getIdentity();
final Long whenCached = deferredIterablesCache.tryKey(handleIdentity);
if (whenCached == null) {
deferredIterablesCache.cacheObject(handleIdentity, currentMillis);
return it;
}
if (whenCached + config.getEntityIterableCacheDeferredDelay() > currentMillis) {
return it;
}
}
// if we are already within an EntityStoreSharedAsyncProcessor's dispatcher,
// then instantiate iterable without queueing a job.
if (isDispatcherThread()) {
return it.getOrCreateCachedInstance(txn);
}
if (!isCachingQueueFull()) {
new EntityIterableAsyncInstantiation(handle, it, true).queue(Priority.below_normal);
}
return it;
}
@Nullable
public Long getCachedCount(@NotNull final EntityIterableHandle handle) {
return iterableCountsCache.tryKey(handle.getIdentity());
}
public long getCachedCount(@NotNull final EntityIterableBase it) {
final EntityIterableHandle handle = it.getHandle();
@Nullable final Long result = getCachedCount(handle);
if (result == null && isDispatcherThread()) {
return it.getOrCreateCachedInstance(it.getTransaction()).size();
}
if (it.isThreadSafe() && !isCachingQueueFull()) {
new EntityIterableAsyncInstantiation(handle, it, false).queue(Priority.normal);
}
return result == null ? -1 : result;
}
public void setCachedCount(@NotNull final EntityIterableHandle handle, final long count) {
iterableCountsCache.cacheObject(handle.getIdentity(), count);
}
public boolean isDispatcherThread() {
return processor.isDispatcherThread();
}
boolean isCachingQueueFull() {
return processor.pendingJobs() > cacheAdapter.size();
}
@NotNull
EntityIterableCacheAdapter getCacheAdapter() {
return cacheAdapter;
}
boolean compareAndSetCacheAdapter(@NotNull final EntityIterableCacheAdapter oldValue,
@NotNull final EntityIterableCacheAdapter newValue) {
if (cacheAdapter == oldValue) {
cacheAdapter = newValue;
return true;
}
return false;
}
private String getStringPresentation(@NotNull final EntityIterableHandle handle) {
return config.getEntityIterableCacheUseHumanReadable() ?
EntityIterableBase.getHumanReadablePresentation(handle) : handle.toString();
}
@SuppressWarnings({"EqualsAndHashcode"})
private final class EntityIterableAsyncInstantiation extends Job {
@NotNull
private final EntityIterableBase it;
@NotNull
private final EntityIterableHandle handle;
@NotNull
private final CachingCancellingPolicy cancellingPolicy;
private EntityIterableAsyncInstantiation(@NotNull final EntityIterableHandle handle,
@NotNull final EntityIterableBase it,
final boolean isConsistent) {
this.it = it;
this.handle = handle;
cancellingPolicy = new CachingCancellingPolicy(isConsistent && handle.isConsistent());
setProcessor(processor);
}
@Override
public String getName() {
return "Caching job for handle " + it.getHandle();
}
@Override
public String getGroup() {
return store.getLocation();
}
@Override
public boolean isEqualTo(Job job) {
return handle.equals(((EntityIterableAsyncInstantiation) job).handle);
}
public int hashCode() {
return handle.hashCode();
}
@Override
protected void execute() throws Throwable {
final long started;
if (isCachingQueueFull() || cancellingPolicy.isOverdue(started = System.currentTimeMillis())) {
return;
}
Thread.yield();
store.executeInReadonlyTransaction(new StoreTransactionalExecutable() {
@Override
public void execute(@NotNull final StoreTransaction tx) {
if (!handle.isConsistent()) {
handle.resetBirthTime();
}
final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx;
cancellingPolicy.setLocalCache(txn.getLocalCache());
txn.setQueryCancellingPolicy(cancellingPolicy);
try {
if (!logger.isInfoEnabled()) {
it.getOrCreateCachedInstance(txn, !cancellingPolicy.isConsistent);
} else {
it.getOrCreateCachedInstance(txn, !cancellingPolicy.isConsistent);
final long cachedIn = System.currentTimeMillis() - started;
if (cachedIn > 1000) {
String action = cancellingPolicy.isConsistent ? "Cached" : "Cached (inconsistent)";
logger.info(action + " in " + cachedIn + " ms, handle=" + getStringPresentation(handle));
}
}
} catch (ReadonlyTransactionException rte) {
// work around XD-626
final String action = cancellingPolicy.isConsistent ? "Caching" : "Caching (inconsistent)";
logger.error(action + " failed with ReadonlyTransactionException. Re-queueing...");
queue(Priority.below_normal);
} catch (TooLongEntityIterableInstantiationException e) {
if (logger.isInfoEnabled()) {
final String action = cancellingPolicy.isConsistent ? "Caching" : "Caching (inconsistent)";
logger.info(action + " forcedly stopped, " + e.reason.message + ": " + getStringPresentation(handle));
}
}
}
});
}
}
private final class CachingCancellingPolicy implements QueryCancellingPolicy {
private final boolean isConsistent;
private final long startTime;
private final long cachingTimeout;
private EntityIterableCacheAdapter localCache;
private CachingCancellingPolicy(final boolean isConsistent) {
this.isConsistent = isConsistent;
startTime = System.currentTimeMillis();
cachingTimeout = config.getEntityIterableCacheCachingTimeout();
}
private boolean isOverdue(final long currentMillis) {
return currentMillis - startTime > cachingTimeout;
}
private void setLocalCache(@NotNull final EntityIterableCacheAdapter localCache) {
this.localCache = localCache;
}
@Override
public boolean needToCancel() {
return (isConsistent && cacheAdapter != localCache) || isOverdue(System.currentTimeMillis());
}
@Override
public void doCancel() {
final TooLongEntityIterableInstantiationReason reason;
if (isConsistent && cacheAdapter != localCache) {
reason = TooLongEntityIterableInstantiationReason.CACHE_ADAPTER_OBSOLETE;
} else {
reason = TooLongEntityIterableInstantiationReason.JOB_OVERDUE;
}
throw new TooLongEntityIterableInstantiationException(reason);
}
}
@SuppressWarnings({"serial", "SerializableClassInSecureContext", "EmptyClass", "SerializableHasSerializationMethods", "DeserializableClassInSecureContext"})
private static class TooLongEntityIterableInstantiationException extends ExodusException {
private final TooLongEntityIterableInstantiationReason reason;
TooLongEntityIterableInstantiationException(TooLongEntityIterableInstantiationReason reason) {
super(reason.message);
this.reason = reason;
}
}
private enum TooLongEntityIterableInstantiationReason {
CACHE_ADAPTER_OBSOLETE("cache adapter is obsolete"),
JOB_OVERDUE("caching job is overdue");
private final String message;
TooLongEntityIterableInstantiationReason(String message) {
this.message = message;
}
}
private static class CacheHitRateAdjuster implements SharedTimer.ExpirablePeriodicTask {
@NotNull
private final WeakReference<EntityIterableCache> cacheRef;
private CacheHitRateAdjuster(@NotNull final EntityIterableCache cache) {
cacheRef = new WeakReference<>(cache);
}
@Override
public boolean isExpired() {
return cacheRef.get() == null;
}
@Override
public void run() {
final EntityIterableCache cache = cacheRef.get();
if (cache != null) {
cache.cacheAdapter.adjustHitRate();
}
}
}
}
| entity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCache.java | /**
* Copyright 2010 - 2017 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 jetbrains.exodus.entitystore;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.core.dataStructures.ConcurrentObjectCache;
import jetbrains.exodus.core.dataStructures.ObjectCacheBase;
import jetbrains.exodus.core.dataStructures.Priority;
import jetbrains.exodus.core.execution.Job;
import jetbrains.exodus.core.execution.SharedTimer;
import jetbrains.exodus.entitystore.iterate.EntityIterableBase;
import jetbrains.exodus.env.ReadonlyTransactionException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.WeakReference;
public final class EntityIterableCache {
private static final Logger logger = LoggerFactory.getLogger(EntityIterableCache.class);
@NotNull
private final PersistentEntityStoreImpl store;
@NotNull
private final PersistentEntityStoreConfig config;
@NotNull
private EntityIterableCacheAdapter cacheAdapter;
@NotNull
private ObjectCacheBase<Object, Long> deferredIterablesCache;
@NotNull
private ObjectCacheBase<Object, Long> iterableCountsCache;
@NotNull
final EntityStoreSharedAsyncProcessor processor;
public EntityIterableCache(@NotNull final PersistentEntityStoreImpl store) {
this.store = store;
config = store.getConfig();
cacheAdapter = new EntityIterableCacheAdapter(config);
clear();
processor = new EntityStoreSharedAsyncProcessor(config.getEntityIterableCacheThreadCount());
processor.start();
SharedTimer.registerPeriodicTask(new CacheHitRateAdjuster(this));
}
public float hitRate() {
return cacheAdapter.hitRate();
}
public int count() {
return cacheAdapter.count();
}
public void clear() {
cacheAdapter.clear();
final int cacheSize = config.getEntityIterableCacheSize();
deferredIterablesCache = new ConcurrentObjectCache<>(cacheSize);
iterableCountsCache = new ConcurrentObjectCache<>(cacheSize * 2);
}
/**
* @param it iterable.
* @return iterable which is cached or "it" itself if it's not cached.
*/
public EntityIterableBase putIfNotCached(@NotNull final EntityIterableBase it) {
if (config.isCachingDisabled() || !it.canBeCached()) {
return it;
}
final EntityIterableHandle handle = it.getHandle();
final PersistentStoreTransaction txn = it.getTransaction();
final EntityIterableCacheAdapter localCache = txn.getLocalCache();
txn.localCacheAttempt();
final EntityIterableBase cached = localCache.tryKey(handle);
if (cached != null) {
if (!cached.getHandle().isExpired()) {
txn.localCacheHit();
return cached;
}
localCache.remove(handle);
}
if (txn.isMutable() || !txn.isCurrent() || !txn.isCachingRelevant()) {
return it;
}
// if cache is enough full, then cache iterables after they live some time in deferred cache
if (!localCache.isSparse()) {
final long currentMillis = System.currentTimeMillis();
final Object handleIdentity = handle.getIdentity();
final Long whenCached = deferredIterablesCache.tryKey(handleIdentity);
if (whenCached == null) {
deferredIterablesCache.cacheObject(handleIdentity, currentMillis);
return it;
}
if (whenCached + config.getEntityIterableCacheDeferredDelay() > currentMillis) {
return it;
}
}
// if we are already within an EntityStoreSharedAsyncProcessor's dispatcher,
// then instantiate iterable without queueing a job.
if (isDispatcherThread()) {
return it.getOrCreateCachedInstance(txn);
}
if (!isCachingQueueFull()) {
new EntityIterableAsyncInstantiation(handle, it, true).queue(Priority.below_normal);
}
return it;
}
@Nullable
public Long getCachedCount(@NotNull final EntityIterableHandle handle) {
return iterableCountsCache.tryKey(handle.getIdentity());
}
public long getCachedCount(@NotNull final EntityIterableBase it) {
final EntityIterableHandle handle = it.getHandle();
@Nullable final Long result = getCachedCount(handle);
if (result == null && isDispatcherThread()) {
return it.getOrCreateCachedInstance(it.getTransaction()).size();
}
if (it.isThreadSafe() && !isCachingQueueFull()) {
new EntityIterableAsyncInstantiation(handle, it, false).queue(Priority.normal);
}
return result == null ? -1 : result;
}
public void setCachedCount(@NotNull final EntityIterableHandle handle, final long count) {
iterableCountsCache.cacheObject(handle.getIdentity(), count);
}
public boolean isDispatcherThread() {
return processor.isDispatcherThread();
}
boolean isCachingQueueFull() {
return processor.pendingJobs() > cacheAdapter.size();
}
@NotNull
EntityIterableCacheAdapter getCacheAdapter() {
return cacheAdapter;
}
boolean compareAndSetCacheAdapter(@NotNull final EntityIterableCacheAdapter oldValue,
@NotNull final EntityIterableCacheAdapter newValue) {
if (cacheAdapter == oldValue) {
cacheAdapter = newValue;
return true;
}
return false;
}
private String getStringPresentation(@NotNull final EntityIterableHandle handle) {
return config.getEntityIterableCacheUseHumanReadable() ?
EntityIterableBase.getHumanReadablePresentation(handle) : handle.toString();
}
@SuppressWarnings({"EqualsAndHashcode"})
private final class EntityIterableAsyncInstantiation extends Job {
@NotNull
private final EntityIterableBase it;
@NotNull
private final EntityIterableHandle handle;
@NotNull
private final CachingCancellingPolicy cancellingPolicy;
private EntityIterableAsyncInstantiation(@NotNull final EntityIterableHandle handle,
@NotNull final EntityIterableBase it,
final boolean isConsistent) {
this.it = it;
this.handle = handle;
cancellingPolicy = new CachingCancellingPolicy(isConsistent && handle.isConsistent());
setProcessor(processor);
}
@Override
public String getName() {
return "Caching job for handle " + it.getHandle();
}
@Override
public String getGroup() {
return store.getLocation();
}
@Override
public boolean isEqualTo(Job job) {
return handle.equals(((EntityIterableAsyncInstantiation) job).handle);
}
public int hashCode() {
return handle.hashCode();
}
@Override
protected void execute() throws Throwable {
final long started;
if (isCachingQueueFull() || cancellingPolicy.isOverdue(started = System.currentTimeMillis())) {
return;
}
Thread.yield();
store.executeInReadonlyTransaction(new StoreTransactionalExecutable() {
@Override
public void execute(@NotNull final StoreTransaction tx) {
if (!handle.isConsistent()) {
handle.resetBirthTime();
}
final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx;
cancellingPolicy.setLocalCache(txn.getLocalCache());
txn.setQueryCancellingPolicy(cancellingPolicy);
try {
if (!logger.isInfoEnabled()) {
it.getOrCreateCachedInstance(txn, !cancellingPolicy.isConsistent);
} else {
it.getOrCreateCachedInstance(txn, !cancellingPolicy.isConsistent);
final long cachedIn = System.currentTimeMillis() - started;
if (cachedIn > 1000) {
String action = cancellingPolicy.isConsistent ? "Cached" : "Cached (inconsistent)";
logger.info(action + " in " + cachedIn + " ms, handle=" + getStringPresentation(handle));
}
}
} catch (ReadonlyTransactionException rte) {
// work around XD-626
final String action = cancellingPolicy.isConsistent ? "Caching" : "Caching (inconsistent)";
logger.error(action + " failed with ReadonlyTransactionException. Re-queueing...");
queue(Priority.below_normal);
} catch (TooLongEntityIterableInstantiationException e) {
if (logger.isInfoEnabled()) {
final String action = cancellingPolicy.isConsistent ? "Caching" : "Caching (inconsistent)";
logger.info(action + " forcedly stopped, " + e.reason.message + ": " + getStringPresentation(handle));
}
}
}
});
}
}
private final class CachingCancellingPolicy implements QueryCancellingPolicy {
private final boolean isConsistent;
private final long startTime;
private EntityIterableCacheAdapter localCache;
private CachingCancellingPolicy(final boolean isConsistent) {
this.isConsistent = isConsistent;
startTime = System.currentTimeMillis();
}
private boolean isOverdue(final long currentMillis) {
return currentMillis - startTime > config.getEntityIterableCacheCachingTimeout();
}
private void setLocalCache(@NotNull final EntityIterableCacheAdapter localCache) {
this.localCache = localCache;
}
@Override
public boolean needToCancel() {
return (isConsistent && cacheAdapter != localCache) || isOverdue(System.currentTimeMillis());
}
@Override
public void doCancel() {
final TooLongEntityIterableInstantiationReason reason;
if (isConsistent && cacheAdapter != localCache) {
reason = TooLongEntityIterableInstantiationReason.CACHE_ADAPTER_OBSOLETE;
} else {
reason = TooLongEntityIterableInstantiationReason.JOB_OVERDUE;
}
throw new TooLongEntityIterableInstantiationException(reason);
}
}
@SuppressWarnings({"serial", "SerializableClassInSecureContext", "EmptyClass", "SerializableHasSerializationMethods", "DeserializableClassInSecureContext"})
private static class TooLongEntityIterableInstantiationException extends ExodusException {
private final TooLongEntityIterableInstantiationReason reason;
TooLongEntityIterableInstantiationException(TooLongEntityIterableInstantiationReason reason) {
super(reason.message);
this.reason = reason;
}
}
private enum TooLongEntityIterableInstantiationReason {
CACHE_ADAPTER_OBSOLETE("cache adapter is obsolete"),
JOB_OVERDUE("caching job is overdue");
private final String message;
TooLongEntityIterableInstantiationReason(String message) {
this.message = message;
}
}
private static class CacheHitRateAdjuster implements SharedTimer.ExpirablePeriodicTask {
@NotNull
private final WeakReference<EntityIterableCache> cacheRef;
private CacheHitRateAdjuster(@NotNull final EntityIterableCache cache) {
cacheRef = new WeakReference<>(cache);
}
@Override
public boolean isExpired() {
return cacheRef.get() == null;
}
@Override
public void run() {
final EntityIterableCache cache = cacheRef.get();
if (cache != null) {
cache.cacheAdapter.adjustHitRate();
}
}
}
}
| reduce number of calls to PersistentEntityStoreConfig#getEntityIterableCacheCachingTimeout()
| entity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCache.java | reduce number of calls to PersistentEntityStoreConfig#getEntityIterableCacheCachingTimeout() | <ide><path>ntity-store/src/main/java/jetbrains/exodus/entitystore/EntityIterableCache.java
<ide>
<ide> private final boolean isConsistent;
<ide> private final long startTime;
<add> private final long cachingTimeout;
<ide> private EntityIterableCacheAdapter localCache;
<ide>
<ide> private CachingCancellingPolicy(final boolean isConsistent) {
<ide> this.isConsistent = isConsistent;
<ide> startTime = System.currentTimeMillis();
<add> cachingTimeout = config.getEntityIterableCacheCachingTimeout();
<ide> }
<ide>
<ide> private boolean isOverdue(final long currentMillis) {
<del> return currentMillis - startTime > config.getEntityIterableCacheCachingTimeout();
<add> return currentMillis - startTime > cachingTimeout;
<ide> }
<ide>
<ide> private void setLocalCache(@NotNull final EntityIterableCacheAdapter localCache) { |
|
Java | apache-2.0 | 5c9784e5b393fed1905c28bb48dfdcdf16357773 | 0 | chinmay-gupte/blueflood,btravers/blueflood,rackerlabs/blueflood,menchauser/blueflood,chinmay-gupte/blueflood,GeorgeJahad/blueflood,tilogaat/blueflood,chinmay-gupte/blueflood,chinmay-gupte/blueflood,VinnyQ/blueflood,izrik/blueflood,ChandraAddala/blueflood,shintasmith/blueflood,goru97/blueflood,goru97/blueflood,menchauser/blueflood,VinnyQ/blueflood,izrik/blueflood,VinnyQ/blueflood,tilogaat/blueflood,tilogaat/blueflood,chinmay-gupte/blueflood,btravers/blueflood,GeorgeJahad/blueflood,menchauser/blueflood,GeorgeJahad/blueflood,tilogaat/blueflood,btravers/blueflood,rackerlabs/blueflood,GeorgeJahad/blueflood,btravers/blueflood,VinnyQ/blueflood,VinnyQ/blueflood,tilogaat/blueflood,goru97/blueflood,GeorgeJahad/blueflood,rackerlabs/blueflood,shintasmith/blueflood,ChandraAddala/blueflood,ChandraAddala/blueflood,goru97/blueflood,goru97/blueflood,VinnyQ/blueflood,btravers/blueflood,menchauser/blueflood,shintasmith/blueflood,izrik/blueflood,menchauser/blueflood,izrik/blueflood,goru97/blueflood,ChandraAddala/blueflood,izrik/blueflood,shintasmith/blueflood,shintasmith/blueflood,ChandraAddala/blueflood,ChandraAddala/blueflood,rackerlabs/blueflood,izrik/blueflood,shintasmith/blueflood,rackerlabs/blueflood,rackerlabs/blueflood | /*
* Copyright 2013 Rackspace
*
* 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.rackspacecloud.blueflood.service;
import com.codahale.metrics.Timer;
import com.rackspacecloud.blueflood.io.AstyanaxReader;
import com.rackspacecloud.blueflood.rollup.Granularity;
import com.rackspacecloud.blueflood.types.Locator;
import com.rackspacecloud.blueflood.types.Range;
import com.rackspacecloud.blueflood.utils.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
/**
* fetches locators for a given slot and feeds a worker queue with rollup work. When those are all done notifies the
* RollupService that slot can be removed from running.
*/
class LocatorFetchRunnable implements Runnable {
private static final Logger log = LoggerFactory.getLogger(LocatorFetchRunnable.class);
private static final int LOCATOR_WAIT_FOR_ALL_SECS = 1000;
private final ThreadPoolExecutor rollupReadExecutor;
private final ThreadPoolExecutor rollupWriteExecutor;
private final String parentSlotKey;
private final ScheduleContext scheduleCtx;
private final long serverTime;
private static final Timer rollupLocatorExecuteTimer = Metrics.timer(RollupService.class, "Locate and Schedule Rollups for Slot");
private static final boolean enableHistograms = Configuration.getInstance().
getBooleanProperty(CoreConfig.ENABLE_HISTOGRAMS);
LocatorFetchRunnable(ScheduleContext scheduleCtx, String destSlotKey, ThreadPoolExecutor rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor) {
this.rollupReadExecutor = rollupReadExecutor;
this.rollupWriteExecutor = rollupWriteExecutor;
this.parentSlotKey = destSlotKey;
this.scheduleCtx = scheduleCtx;
this.serverTime = scheduleCtx.getCurrentTimeMillis();
}
public void run() {
final Timer.Context timerCtx = rollupLocatorExecuteTimer.time();
final Granularity gran = Granularity.granularityFromKey(parentSlotKey);
final int parentSlot = Granularity.slotFromKey(parentSlotKey);
final int shard = Granularity.shardFromKey(parentSlotKey);
final Range parentRange = gran.deriveRange(parentSlot, serverTime);
try {
gran.finer();
} catch (Exception ex) {
log.error("No finer granularity available than " + gran);
return;
}
if (log.isTraceEnabled())
log.trace("Getting locators for {} {} @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()});
// todo: I can see this set becoming a memory hog. There might be a better way of doing this.
long waitStart = System.currentTimeMillis();
int rollCount = 0;
final RollupExecutionContext executionContext = new RollupExecutionContext(Thread.currentThread());
final RollupBatchWriter rollupBatchWriter = new RollupBatchWriter(rollupWriteExecutor, executionContext);
Set<Locator> locators = new HashSet<Locator>();
try {
locators.addAll(AstyanaxReader.getInstance().getLocatorsToRollup(shard));
} catch (RuntimeException e) {
executionContext.markUnsuccessful(e);
log.error("Failed reading locators for slot: " + parentSlot, e);
}
for (Locator locator : locators) {
if (log.isTraceEnabled())
log.trace("Rolling up (check,metric,dimension) {} for (gran,slot,shard) {}", locator, parentSlotKey);
try {
executionContext.incrementReadCounter();
final SingleRollupReadContext singleRollupReadContext = new SingleRollupReadContext(locator, parentRange, gran);
rollupReadExecutor.execute(new RollupRunnable(executionContext, singleRollupReadContext, rollupBatchWriter));
rollCount += 1;
} catch (Throwable any) {
// continue on, but log the problem so that we can fix things later.
executionContext.markUnsuccessful(any);
executionContext.decrementReadCounter();
log.error(any.getMessage(), any);
log.error("BasicRollup failed for {} at {}", parentSlotKey, serverTime);
}
if (enableHistograms) {
// Also, compute histograms. Histograms for > 5 MIN granularity are always computed from 5 MIN histograms.
try {
executionContext.incrementReadCounter();
final SingleRollupReadContext singleRollupReadContext = new SingleRollupReadContext(locator,
parentRange, gran);
rollupReadExecutor.execute(new HistogramRollupRunnable(executionContext, singleRollupReadContext,
rollupBatchWriter));
rollCount += 1;
} catch (RejectedExecutionException ex) {
executionContext.markUnsuccessful(ex); // We should ideally only recompute the failed locators alone.
executionContext.decrementReadCounter();
log.error("Histogram rollup rejected for {} at {}", parentSlotKey, serverTime);
log.error("Exception: ", ex);
} catch (Exception ex) { // do not retrigger rollups when they fail. histograms are fine to be lost.
executionContext.decrementReadCounter();
log.error("Histogram rollup rejected for {} at {}", parentSlotKey, serverTime);
log.error("Exception: ", ex);
}
}
}
// now wait until ctx is drained. someone needs to be notified.
log.debug("Waiting for rollups to finish for " + parentSlotKey);
while (!executionContext.doneReading() || !executionContext.doneWriting()) {
if (executionContext.doneReading()) {
rollupBatchWriter.drainBatch(); // gets any remaining rollups enqueued for put. should be no-op after being called once
}
try {
Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS * 1000);
} catch (InterruptedException ex) {
if (log.isTraceEnabled())
log.trace("Woken wile waiting for rollups to coalesce for {} {}", parentSlotKey);
} finally {
String verb = executionContext.doneReading() ? "writing" : "reading";
log.debug("Still waiting for rollups to finish {} for {} {}", new Object[] {verb, parentSlotKey, System.currentTimeMillis() - waitStart });
}
}
if (log.isDebugEnabled())
log.debug("Finished {} rollups for (gran,slot,shard) {} in {}", new Object[] {rollCount, parentSlotKey, System.currentTimeMillis() - waitStart});
if (executionContext.wasSuccessful()) {
this.scheduleCtx.clearFromRunning(parentSlotKey);
} else {
log.error("Performing BasicRollups for {} failed", parentSlotKey);
this.scheduleCtx.pushBackToScheduled(parentSlotKey, false);
}
timerCtx.stop();
}
}
| blueflood-core/src/main/java/com/rackspacecloud/blueflood/service/LocatorFetchRunnable.java | /*
* Copyright 2013 Rackspace
*
* 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.rackspacecloud.blueflood.service;
import com.codahale.metrics.Timer;
import com.rackspacecloud.blueflood.io.AstyanaxReader;
import com.rackspacecloud.blueflood.rollup.Granularity;
import com.rackspacecloud.blueflood.types.Locator;
import com.rackspacecloud.blueflood.types.Range;
import com.rackspacecloud.blueflood.utils.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
/**
* fetches locators for a given slot and feeds a worker queue with rollup work. When those are all done notifies the
* RollupService that slot can be removed from running.
*/
class LocatorFetchRunnable implements Runnable {
private static final Logger log = LoggerFactory.getLogger(LocatorFetchRunnable.class);
private static final int LOCATOR_WAIT_FOR_ALL_SECS = 1000;
private final ThreadPoolExecutor rollupReadExecutor;
private final ThreadPoolExecutor rollupWriteExecutor;
private final String parentSlotKey;
private final ScheduleContext scheduleCtx;
private final long serverTime;
private static final Timer rollupLocatorExecuteTimer = Metrics.timer(RollupService.class, "Locate and Schedule Rollups for Slot");
private static final boolean enableHistograms = Configuration.getInstance().
getBooleanProperty(CoreConfig.ENABLE_HISTOGRAMS);
LocatorFetchRunnable(ScheduleContext scheduleCtx, String destSlotKey, ThreadPoolExecutor rollupReadExecutor, ThreadPoolExecutor rollupWriteExecutor) {
this.rollupReadExecutor = rollupReadExecutor;
this.rollupWriteExecutor = rollupWriteExecutor;
this.parentSlotKey = destSlotKey;
this.scheduleCtx = scheduleCtx;
this.serverTime = scheduleCtx.getCurrentTimeMillis();
}
public void run() {
final Timer.Context timerCtx = rollupLocatorExecuteTimer.time();
final Granularity gran = Granularity.granularityFromKey(parentSlotKey);
final int parentSlot = Granularity.slotFromKey(parentSlotKey);
final int shard = Granularity.shardFromKey(parentSlotKey);
final Range parentRange = gran.deriveRange(parentSlot, serverTime);
try {
gran.finer();
} catch (Exception ex) {
log.error("No finer granularity available than " + gran);
return;
}
if (log.isTraceEnabled())
log.trace("Getting locators for {} {} @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()});
// todo: I can see this set becoming a memory hog. There might be a better way of doing this.
long waitStart = System.currentTimeMillis();
int rollCount = 0;
final RollupExecutionContext executionContext = new RollupExecutionContext(Thread.currentThread());
final RollupBatchWriter rollupBatchWriter = new RollupBatchWriter(rollupWriteExecutor, executionContext);
Set<Locator> locators = new HashSet<Locator>();
try {
locators.addAll(AstyanaxReader.getInstance().getLocatorsToRollup(shard));
} catch (RuntimeException e) {
executionContext.markUnsuccessful(e);
log.error("Failed reading locators for slot: " + parentSlot, e);
}
for (Locator locator : locators) {
if (log.isTraceEnabled())
log.trace("Rolling up (check,metric,dimension) {} for (gran,slot,shard) {}", locator, parentSlotKey);
try {
executionContext.incrementReadCounter();
final SingleRollupReadContext singleRollupReadContext = new SingleRollupReadContext(locator, parentRange, gran);
rollupReadExecutor.execute(new RollupRunnable(executionContext, singleRollupReadContext, rollupBatchWriter));
rollCount += 1;
} catch (Throwable any) {
// continue on, but log the problem so that we can fix things later.
executionContext.markUnsuccessful(any);
executionContext.decrementReadCounter();
log.error(any.getMessage(), any);
log.error("BasicRollup failed for {} at {}", parentSlotKey, serverTime);
}
if (enableHistograms) {
// Also, compute histograms. Histograms for > 5 MIN granularity are always computed from 5 MIN histograms.
try {
executionContext.incrementReadCounter();
final SingleRollupReadContext singleRollupReadContext = new SingleRollupReadContext(locator,
parentRange, gran);
rollupReadExecutor.execute(new HistogramRollupRunnable(executionContext, singleRollupReadContext,
rollupBatchWriter));
rollCount += 1;
} catch (RejectedExecutionException ex) {
executionContext.markUnsuccessful(ex); // We should ideally only recompute the failed locators alone.
executionContext.decrementReadCounter();
log.error("Histogram rollup rejected for {} at {}", parentSlotKey, serverTime);
log.error("Exception: ", ex);
} catch (Exception ex) { // do not retrigger rollups when they fail. histograms are fine to be lost.
executionContext.decrementReadCounter();
log.error("Histogram rollup rejected for {} at {}", parentSlotKey, serverTime);
log.error("Exception: ", ex);
}
}
}
// now wait until ctx is drained. someone needs to be notified.
log.debug("Waiting for rollups to finish for " + parentSlotKey);
while (!executionContext.doneReading() || !executionContext.doneWriting()) {
if (executionContext.doneReading()) {
rollupBatchWriter.drainBatch(); // gets any remaining rollups enqueued for put. should be no-op after being called once
}
try {
Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS);
} catch (InterruptedException ex) {
if (log.isTraceEnabled())
log.trace("Woken wile waiting for rollups to coalesce for {} {}", parentSlotKey);
} finally {
String verb = executionContext.doneReading() ? "writing" : "reading";
log.debug("Still waiting for rollups to finish {} for {} {}", new Object[] {verb, parentSlotKey, System.currentTimeMillis() - waitStart });
}
}
if (log.isDebugEnabled())
log.debug("Finished {} rollups for (gran,slot,shard) {} in {}", new Object[] {rollCount, parentSlotKey, System.currentTimeMillis() - waitStart});
if (executionContext.wasSuccessful()) {
this.scheduleCtx.clearFromRunning(parentSlotKey);
} else {
log.error("Performing BasicRollups for {} failed", parentSlotKey);
this.scheduleCtx.pushBackToScheduled(parentSlotKey, false);
}
timerCtx.stop();
}
}
| variable name indicates 'seconds' but is treated as 'millis' when used. Fix by multiplying * 1000 during sleep.
| blueflood-core/src/main/java/com/rackspacecloud/blueflood/service/LocatorFetchRunnable.java | variable name indicates 'seconds' but is treated as 'millis' when used. Fix by multiplying * 1000 during sleep. | <ide><path>lueflood-core/src/main/java/com/rackspacecloud/blueflood/service/LocatorFetchRunnable.java
<ide> rollupBatchWriter.drainBatch(); // gets any remaining rollups enqueued for put. should be no-op after being called once
<ide> }
<ide> try {
<del> Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS);
<add> Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS * 1000);
<ide> } catch (InterruptedException ex) {
<ide> if (log.isTraceEnabled())
<ide> log.trace("Woken wile waiting for rollups to coalesce for {} {}", parentSlotKey); |
|
JavaScript | mit | f2baa85b454d304985ba6b32d3acec6e65a98051 | 0 | uplift/ExoSuit,uplift/ExoSuit | ( function( root, factory ) {
"use strict";
// Set up appropriately for the environment.
// Start with AMD.
if ( typeof define === 'function' && define.amd ) {
define(
[
'underscore',
'backbone'
],
function( _, Backbone ) {
root.ExoSuit = root.ExoSuit || {};
root.ExoSuit.Mixins = root.ExoSuit.Mixins || {};
return ( root.ExoSuit.Mixins.CappedSubsetMixin = factory( root, {}, _, Backbone ) );
}
);
// Next for Node.js or CommonJS.
} else if ( typeof exports !== 'undefined' ) {
var _ = require( 'underscore' );
var Backbone = require( 'backbone' );
module.exports = factory( root, exports, _, Backbone );
// Finally, as a browser global.
} else {
root.ExoSuit = root.ExoSuit || {};
root.ExoSuit.Mixins = root.ExoSuit.Mixins || {};
root.ExoSuit.Mixins.CappedSubsetMixin = factory( root, {}, root._, root.Backbone );
}
}( this, function( root, CappedSubsetMixin, _, Backbone ) {
"use strict";
CappedSubsetMixin = function() {
var orderMethods = [ 'first', 'last' ];
// Internal functions
function isInt( number ) {
if ( typeof number !== 'number' || parseInt( number, 10 ) !== number ) {
return false;
}
return true;
}
function contains( value, array ) {
var doesContain = false;
for ( var i = 0, len = array.length; i < len; i++ ) {
if ( !doesContain && value === array[ i ] ) {
doesContain = true;
}
}
return doesContain;
}
// Cache current mixin methods to use later
var oldInitialize = this.initialize;
// Set collection capped limit
this.limit = isInt( this.limit ) ? this.limit : 100;
this.order = contains( this.order, orderMethods ) ? this.order : 'last';
this.initialize = function( models, options ) {
options = options || {};
if ( options.parent ) {
this.parent = options.parent;
}
if ( !this.parent ) {
throw new Error( 'Parent collection is required to use subset collection' );
}
this.model = this.parent.model;
if ( options.limit && options.limit !== this.limit ) {
this.resize( options.limit, { silent: true } );
}
if ( options.order && options.order !== this.order ) {
this.reorder( options.order, { silent: true } );
}
this.listenTo( this.parent, {
add: this.__add,
remove: this.__remove,
reset: this.__reset,
sort: this.__reset
} );
this.__reset();
if ( oldInitialize ) {
oldInitialize.apply( this, arguments );
}
};
this._getParentModels = function() {
if ( !this.parent ) {
return;
}
var limit = this.parent.length < this.limit ? this.parent.length : this.limit;
return this.parent[ this.order ]( limit );
};
this.__add = function( model, collection, options ) {
options = options || {};
var index;
if ( !this.comparator && typeof options.at !== 'undefined' ) {
index = options.at;
}
if ( this.parent.length < this.limit ) {
this.add( model, options );
} else if ( this.order.toLowerCase() === 'last' && this.parent.indexOf( model ) >= ( this.parent.length - this.limit ) ) {
this.remove( this.parent.at( this.parent.length - this.limit - 1 ), options );
options.at = index ? index - this.limit : undefined;
this.add( model, options );
} else if ( this.order.toLowerCase() === 'first' && this.parent.indexOf( model ) < this.limit ) {
this.remove( this.parent.at( this.limit ), options );
this.add( model, options );
}
};
this.__remove = function( model, collection, options ) {
options = options || {};
var parentModels;
if ( this.contains( model ) ) {
this.remove( model, options );
if ( this.parent.length > this.length ) {
parentModels = this._getParentModels();
if ( this.order.toLowerCase() === 'last' ) {
if ( !this.comparator && typeof options.at === undefined ) {
options.at = 0 ;
}
this.add( parentModels[ 0 ], options );
} else {
this.add( parentModels[ this.limit - 1 ], options );
}
}
}
};
this.__reset = function( collection, options ) {
this.reset( this._getParentModels(), options );
};
this.resize = function( size, options ) {
// Make sure passed in size is a number
if ( !isInt( size ) ) {
throw new Error( 'Size must be a number' );
}
options = options || {};
var models,
modelsToProcess = [],
newCids,
oldLimit = this.limit;
this.limit = size;
models = this._getParentModels();
newCids = _.pluck( models, 'cid' );
if ( size > oldLimit ) {
if ( this.order === 'last' ) {
modelsToProcess = models.slice( 0, this.limit - this.length );
if ( !this.comparator && typeof options.at === "undefined" ) {
options.at = 0 ;
}
} else {
modelsToProcess = models.slice( this.length, this.limit );
}
this.add( modelsToProcess, options );
} else if ( size < oldLimit ) {
modelsToProcess = this.filter( function( model ) {
return !_.contains( newCids, model.cid );
}, this );
this.remove( modelsToProcess );
}
if ( !options.silent ) {
this.trigger( 'resize', size, this, options );
}
};
this.reorder = function( options ) {
options = options || {};
this.order = this.order === 'first' ? 'last' : 'first';
this.reset( this._getParentModels() );
if ( !options.silent ) {
this.trigger( 'reorder', this.order, this, options );
}
};
};
return CappedSubsetMixin;
} ));
| src/collections/subset/CappedSubset.js | ( function( root, factory ) {
"use strict";
// Set up appropriately for the environment.
// Start with AMD.
if ( typeof define === 'function' && define.amd ) {
define(
[
'underscore',
'backbone'
],
function( _, Backbone ) {
root.ExoSuit = root.ExoSuit || {};
root.ExoSuit.Mixins = root.ExoSuit.Mixins || {};
return ( root.ExoSuit.Mixins.CappedSubsetMixin = factory( root, {}, _, Backbone ) );
}
);
// Next for Node.js or CommonJS.
} else if ( typeof exports !== 'undefined' ) {
var _ = require( 'underscore' );
var Backbone = require( 'backbone' );
module.exports = factory( root, exports, _, Backbone );
// Finally, as a browser global.
} else {
root.ExoSuit = root.ExoSuit || {};
root.ExoSuit.Mixins = root.ExoSuit.Mixins || {};
root.ExoSuit.Mixins.CappedSubsetMixin = factory( root, {}, root._, root.Backbone );
}
}( this, function( root, CappedSubsetMixin, _, Backbone ) {
"use strict";
CappedSubsetMixin = function() {
var orderMethods = [ 'first', 'last' ];
// Internal functions
function isInt( number ) {
if ( typeof number !== 'number' || parseInt( number, 10 ) !== number ) {
return false;
}
return true;
}
function contains( value, array ) {
var doesContain = false;
for ( var i = 0, len = array.length; i < len; i++ ) {
if ( !doesContain && value === array[ i ] ) {
doesContain = true;
}
}
return doesContain;
}
// Cache current mixin methods to use later
var oldInitialize = this.initialize;
// Set collection capped limit
this.limit = isInt( this.limit ) ? this.limit : 100;
this.order = contains( this.order, orderMethods ) ? this.order : 'last';
this.initialize = function( models, options ) {
options = options || {};
if ( options.parent ) {
this.parent = options.parent;
}
if ( !this.parent ) {
throw new Error( 'Parent collection is required to use subset collection' );
}
this.model = this.parent.model;
if ( options.limit && options.limit !== this.limit ) {
this.resize( options.limit, { silent: true } );
}
if ( options.order && options.order !== this.order ) {
this.reorder( options.order, { silent: true } );
}
this.listenTo( this.parent, {
add: this.__add,
remove: this.__remove,
reset: this.__reset,
sort: this.__reset
} );
this.__reset();
if ( oldInitialize ) {
oldInitialize.apply( this, arguments );
}
};
this._getParentModels = function() {
if ( !this.parent ) {
return;
}
var limit = this.parent.length < this.limit ? this.parent.length : this.limit;
return this.parent[ this.order ]( limit );
};
this.__add = function( model, collection, options ) {
options = options || {};
var index;
if ( !this.comparator && typeof options.at !== 'undefined' ) {
index = options.at;
}
if ( this.parent.length < this.limit ) {
this.add( model );
} else if ( this.order.toLowerCase() === 'last' && this.parent.indexOf( model ) >= ( this.parent.length - this.limit ) ) {
this.remove( this.parent.at( this.parent.length - this.limit - 1 ) );
this.add( model, { at : index ? index - this.limit : undefined } );
} else if ( this.order.toLowerCase() === 'first' && this.parent.indexOf( model ) < this.limit ) {
this.remove( this.parent.at( this.limit ) );
this.add( model, { at : index } );
}
};
this.__remove = function( model, collection, options ) {
options = options || {};
var parentModels;
if ( this.contains( model ) ) {
this.remove( model );
if ( this.parent.length > this.length ) {
parentModels = this._getParentModels();
if ( this.order.toLowerCase() === 'last' ) {
if ( !this.comparator && typeof options.at === undefined ) {
options.at = 0 ;
}
this.add( parentModels[ 0 ], options );
} else {
this.add( parentModels[ this.limit - 1 ], options );
}
}
}
};
this.__reset = function() {
this.reset( this._getParentModels() );
};
this.resize = function( size, options ) {
// Make sure passed in size is a number
if ( !isInt( size ) ) {
throw new Error( 'Size must be a number' );
}
options = options || {};
var models,
modelsToProcess = [],
newCids,
oldLimit = this.limit;
this.limit = size;
models = this._getParentModels();
newCids = _.pluck( models, 'cid' );
if ( size > oldLimit ) {
if ( this.order === 'last' ) {
modelsToProcess = models.slice( 0, this.limit - this.length );
if ( !this.comparator && typeof options.at === "undefined" ) {
options.at = 0 ;
}
} else {
modelsToProcess = models.slice( this.length, this.limit );
}
this.add( modelsToProcess, options );
} else if ( size < oldLimit ) {
modelsToProcess = this.filter( function( model ) {
return !_.contains( newCids, model.cid );
}, this );
this.remove( modelsToProcess );
}
if ( !options.silent ) {
this.trigger( 'resize', size, this, options );
}
};
this.reorder = function( options ) {
options = options || {};
this.order = this.order === 'first' ? 'last' : 'first';
this.reset( this._getParentModels() );
if ( !options.silent ) {
this.trigger( 'reorder', this.order, this, options );
}
};
};
return CappedSubsetMixin;
} ));
| Pass options argument through
| src/collections/subset/CappedSubset.js | Pass options argument through | <ide><path>rc/collections/subset/CappedSubset.js
<ide> }
<ide>
<ide> if ( this.parent.length < this.limit ) {
<del> this.add( model );
<add> this.add( model, options );
<ide> } else if ( this.order.toLowerCase() === 'last' && this.parent.indexOf( model ) >= ( this.parent.length - this.limit ) ) {
<del> this.remove( this.parent.at( this.parent.length - this.limit - 1 ) );
<del> this.add( model, { at : index ? index - this.limit : undefined } );
<add> this.remove( this.parent.at( this.parent.length - this.limit - 1 ), options );
<add> options.at = index ? index - this.limit : undefined;
<add> this.add( model, options );
<ide> } else if ( this.order.toLowerCase() === 'first' && this.parent.indexOf( model ) < this.limit ) {
<del> this.remove( this.parent.at( this.limit ) );
<del> this.add( model, { at : index } );
<add> this.remove( this.parent.at( this.limit ), options );
<add> this.add( model, options );
<ide> }
<ide> };
<ide>
<ide> var parentModels;
<ide>
<ide> if ( this.contains( model ) ) {
<del> this.remove( model );
<add> this.remove( model, options );
<ide> if ( this.parent.length > this.length ) {
<ide> parentModels = this._getParentModels();
<ide> if ( this.order.toLowerCase() === 'last' ) {
<ide> }
<ide> };
<ide>
<del> this.__reset = function() {
<del> this.reset( this._getParentModels() );
<add> this.__reset = function( collection, options ) {
<add> this.reset( this._getParentModels(), options );
<ide> };
<ide>
<ide> this.resize = function( size, options ) { |
|
JavaScript | isc | 6d8053be2f99c7a0defba3c6f90df8c039d7ab67 | 0 | stefanwimmer128/jwin | /**
* Created by Stefan Wimmer <[email protected]> on 18.06.16.
*/
module.exports = ($) =>
{
$.Map = function ()
{
this.keys = [];
this.values = [];
this.put = (key, value) =>
{
if (this.exists(key))
{
for (const i in this.keys)
{
if (key === this.keys[i])
{
this.values[i] = value;
}
}
} else {
this.keys.push(key);
this.values.push(value);
}
};
this.get = (key) =>
{
let value = undefined;
for (const i in this.keys)
{
if (key === this.keys[i])
{
value = this.values[i];
}
}
return value;
};
this.exists = (key) =>
{
for (const i in this.keys)
{
if (key === this.keys[i]) return true;
}
return false;
};
this.size = () => this.keys.length;
};
return $;
};
| lib/map.js | /**
* Created by Stefan Wimmer <[email protected]> on 18.06.16.
*/
module.exports = ($) =>
{
$.Map = function ()
{
this.keys = [];
this.values = [];
this.put = (key, value) =>
{
this.keys.push(key);
this.values.push(value);
};
this.get = (key) =>
{
let value = undefined;
for (const i in this.keys)
{
if (key === this.keys[i])
{
value = this.values[i];
}
}
return value;
};
};
return $;
};
| Rewrite Map.prototype.put
| lib/map.js | Rewrite Map.prototype.put | <ide><path>ib/map.js
<ide>
<ide> this.put = (key, value) =>
<ide> {
<del> this.keys.push(key);
<del> this.values.push(value);
<add> if (this.exists(key))
<add> {
<add> for (const i in this.keys)
<add> {
<add> if (key === this.keys[i])
<add> {
<add> this.values[i] = value;
<add> }
<add> }
<add> } else {
<add> this.keys.push(key);
<add> this.values.push(value);
<add> }
<ide> };
<ide>
<ide> this.get = (key) =>
<ide> }
<ide> return value;
<ide> };
<add>
<add> this.exists = (key) =>
<add> {
<add> for (const i in this.keys)
<add> {
<add> if (key === this.keys[i]) return true;
<add> }
<add> return false;
<add> };
<add>
<add> this.size = () => this.keys.length;
<ide> };
<ide>
<ide> return $; |
|
Java | mit | bfdf14fe1cae5d3e72eae0547d3940c03aba62f0 | 0 | CSTIB-Hotel/OTCAnalyser | package uk.ac.cam.cstibhotel.otcanalyser.communicationlayer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import uk.ac.cam.cstibhotel.otcanalyser.dataanalysis.Analyser;
import uk.ac.cam.cstibhotel.otcanalyser.database.Database;
import uk.ac.cam.cstibhotel.otcanalyser.gui.SearchWindow;
import uk.ac.cam.cstibhotel.otcanalyser.gui.StatusBar;
import uk.ac.cam.cstibhotel.otcanalyser.trade.AssetClass;
import uk.ac.cam.cstibhotel.otcanalyser.trade.TradeType;
import uk.ac.cam.cstibhotel.otcanalyser.trade.UPIStrings;
public class CommunicationLayer {
// A list of all components expecting the results of a search query
private static ArrayList<SearchListener> searchListeners;
// Singleton instance of the communication layer
private static CommunicationLayer communicationLayer;
public static CommunicationLayer getInstance() {
if (communicationLayer == null) {
communicationLayer = new CommunicationLayer();
}
return communicationLayer;
}
private CommunicationLayer() {
searchListeners = new ArrayList<SearchListener>();
}
/*
* Builds a Search object from the currently-selected parameters in the SearchWindow and returns
* it.
*/
public static Search createSearch() throws ParseException {
Search s = new Search();
String tradeType = (String) SearchWindow.getInstance().TradeType.getSelectedItem();
if (tradeType.equals("Swap")) {
s.setTradeType(TradeType.SWAP);
} else if (tradeType.equals("Option")) {
s.setTradeType(TradeType.OPTION);
}
s.setAsset(SearchWindow.getInstance().UnderLyingAsset.getText());
try {
s.setMinPrice(Math.max(0L,
((Integer) SearchWindow.getInstance().minValue.getValue()).longValue()));
s.setMaxPrice(Math.max(0L,
((Integer) SearchWindow.getInstance().maxValue.getValue()).longValue()));
} catch (NumberFormatException e) {
StatusBar.setMessage("Error: Price fields must contain integers", 1);
}
s.setCurrency((String)SearchWindow.getInstance().currency.getSelectedItem());
int day = (int) SearchWindow.getInstance().StartDate.Day.getSelectedItem();
String monthString = (String) SearchWindow.getInstance().StartDate.Months.getSelectedItem();
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthString));
int month = cal.get(Calendar.MONTH);
int year = (int) SearchWindow.getInstance().StartDate.Year.getSelectedItem();
cal.set(year, month, day);
Date startTime = cal.getTime();
s.setStartTime(startTime);
day = (int) SearchWindow.getInstance().EndDate.Day.getSelectedItem();
monthString = (String) SearchWindow.getInstance().EndDate.Months.getSelectedItem();
cal.setTime(new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthString));
month = cal.get(Calendar.MONTH);
year = (int) SearchWindow.getInstance().EndDate.Year.getSelectedItem();
cal.set(year, month, day);
Date endTime = cal.getTime();
s.setEndTime(endTime);
String fullTaxonomy = "";
String selectedAsset = (String) SearchWindow.getInstance().tax.Asset.getSelectedItem();
int assetIndex = SearchWindow.getInstance().tax.Asset.getSelectedIndex();
int baseIndex = SearchWindow.getInstance().tax.BaseClass.getSelectedIndex();
int subIndex = SearchWindow.getInstance().tax.SubClass.getSelectedIndex();
// Add the Asset to the taxonomy string
fullTaxonomy += UPIStrings.Assets[assetIndex];
fullTaxonomy += ":";
/*
* Add the Base Product and Sub-product to the taxonomy string
* Also set the AssetClass while we're here to make code slightly neater
*/
switch (selectedAsset) {
case "Credit":
s.setAssetClass(AssetClass.CREDIT);
fullTaxonomy += UPIStrings.CreditBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.CreditSubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.CreditSubProducts[baseIndex][subIndex];
}
break;
case "Interest":
s.setAssetClass(AssetClass.RATES);
fullTaxonomy += UPIStrings.InterestBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.InterestSubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.InterestSubProducts[baseIndex][subIndex];
}
break;
case "Commodity":
s.setAssetClass(AssetClass.COMMODITY);
fullTaxonomy += UPIStrings.CommodityBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.CommoditySubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.CommoditySubProducts[baseIndex][subIndex];
}
break;
case "Foreign Exchange":
s.setAssetClass(AssetClass.FOREX);
fullTaxonomy += UPIStrings.ForexBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.ForexSubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.ForexSubProducts[baseIndex][subIndex];
}
break;
case "Equity":
s.setAssetClass(AssetClass.EQUITY);
fullTaxonomy += UPIStrings.EquityBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.EquitySubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.EquitySubProducts[baseIndex][subIndex];
}
break;
}
s.setUPI(fullTaxonomy);
return s;
}
/*
* Takes a Search and loads its values into the GUI for the user.
*/
public static void loadSearch(String name) {
Search s = Database.getSavedSearch(name);
if (s == null) {
// Search could not be loaded, so set an error message and return
StatusBar.setMessage("Failed to load search '" + name + "', search did not exist", 1);
}
System.out.println(s.getAsset());
// Set the trade type
if (s.getTradeType() == TradeType.SWAP) {
SearchWindow.getInstance().TradeType.setSelectedItem("Swap");
} else if (s.getTradeType() == TradeType.OPTION) {
SearchWindow.getInstance().TradeType.setSelectedItem("Option");
}
// Set the underlying asset
SearchWindow.getInstance().UnderLyingAsset.setText(s.getAsset());
// Set the minimum price
SearchWindow.getInstance().minValue.setValue(s.getMinPrice());
// Set the maximum price
SearchWindow.getInstance().maxValue.setValue(s.getMaxPrice());
// Set the currency
SearchWindow.getInstance().currency.setSelectedItem((s.getCurrency()));
// Set the start date and end date
Calendar cal = Calendar.getInstance();
cal.setTime(s.getStartTime());
SearchWindow.getInstance().StartDate.Day.setSelectedItem(cal.get(Calendar.DAY_OF_MONTH));
SearchWindow.getInstance().StartDate.Months.setSelectedIndex(cal.get(Calendar.MONTH));
SearchWindow.getInstance().StartDate.Year.setSelectedItem(cal.get(Calendar.YEAR));
cal.setTime(s.getEndTime());
SearchWindow.getInstance().EndDate.Day.setSelectedItem(cal.get(Calendar.DAY_OF_MONTH));
SearchWindow.getInstance().EndDate.Months.setSelectedIndex(cal.get(Calendar.MONTH));
SearchWindow.getInstance().EndDate.Year.setSelectedItem(cal.get(Calendar.YEAR));
// Set the asset class
switch (s.getAssetClass()) {
case COMMODITY:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Commodity");
break;
case RATES:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Interest");
break;
case CREDIT:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Credit");
break;
case EQUITY:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Equity");
break;
case FOREX:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Foreign Exchange");
break;
}
//TODO Set the base product
//TODO Set the sub-product
StatusBar.setMessage("Successfully loaded search '" + name + "'", 1);
}
/*
* Adds a listener to the list of searchListeners to allow them to
* receive results of a query
*/
public static void registerListener(SearchListener s) {
searchListeners.add(s);
}
/*
* Builds a Search and attempts to save it in the database. If this is unsuccessful, puts an
* error message in the StatusBar.
*/
public static void saveSearch(String name) throws ParseException {
// Build a search
Search s = createSearch();
boolean success = Database.getDB().saveSearch(s, name);
if (!success) {
StatusBar.setMessage("Error: could not save search", 1);
return;
}
StatusBar.setMessage("Successfully saved search '" + name + "'", 1);
}
/*
* Builds a Search, sends the query to the database and then passes the result to any of the
* SearchListeners registered to receive it.
*/
public static void search() throws ParseException {
// Build a search
Search s = createSearch();
// Get the result from the database
SearchResult result = Database.getDB().search(s);
// Send it to each member of searchListeners
for (SearchListener l : searchListeners) {
l.getSearchResult(result);
}
//Give search and number of results to analyser
Analyser.analyse(s, result.getNumResults());
}
}
| OTCAnalyser/src/uk/ac/cam/cstibhotel/otcanalyser/communicationlayer/CommunicationLayer.java | package uk.ac.cam.cstibhotel.otcanalyser.communicationlayer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import uk.ac.cam.cstibhotel.otcanalyser.dataanalysis.Analyser;
import uk.ac.cam.cstibhotel.otcanalyser.database.Database;
import uk.ac.cam.cstibhotel.otcanalyser.gui.SearchWindow;
import uk.ac.cam.cstibhotel.otcanalyser.gui.StatusBar;
import uk.ac.cam.cstibhotel.otcanalyser.trade.AssetClass;
import uk.ac.cam.cstibhotel.otcanalyser.trade.TradeType;
import uk.ac.cam.cstibhotel.otcanalyser.trade.UPIStrings;
public class CommunicationLayer {
// A list of all components expecting the results of a search query
private static ArrayList<SearchListener> searchListeners;
// Singleton instance of the communication layer
private static CommunicationLayer communicationLayer;
public static CommunicationLayer getInstance() {
if (communicationLayer == null) {
communicationLayer = new CommunicationLayer();
}
return communicationLayer;
}
private CommunicationLayer() {
searchListeners = new ArrayList<SearchListener>();
}
/*
* Builds a Search object from the currently-selected parameters in the SearchWindow and returns
* it.
*/
public static Search createSearch() throws ParseException {
Search s = new Search();
String tradeType = (String) SearchWindow.getInstance().TradeType.getSelectedItem();
if (tradeType.equals("Swap")) {
s.setTradeType(TradeType.SWAP);
} else if (tradeType.equals("Option")) {
s.setTradeType(TradeType.OPTION);
}
s.setAsset(SearchWindow.getInstance().UnderLyingAsset.getText());
try {
s.setMinPrice(Math.max(0L,
((Integer) SearchWindow.getInstance().minValue.getValue()).longValue()));
s.setMaxPrice(Math.max(0L,
((Integer) SearchWindow.getInstance().maxValue.getValue()).longValue()));
} catch (NumberFormatException e) {
StatusBar.setMessage("Error: Price fields must contain integers", 1);
}
s.setCurrency((String)SearchWindow.getInstance().currency.getSelectedItem());
int day = (int) SearchWindow.getInstance().StartDate.Day.getSelectedItem();
String monthString = (String) SearchWindow.getInstance().StartDate.Months.getSelectedItem();
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthString));
int month = cal.get(Calendar.MONTH);
int year = (int) SearchWindow.getInstance().StartDate.Year.getSelectedItem();
cal.set(year, month, day);
Date startTime = cal.getTime();
s.setStartTime(startTime);
day = (int) SearchWindow.getInstance().EndDate.Day.getSelectedItem();
monthString = (String) SearchWindow.getInstance().EndDate.Months.getSelectedItem();
cal.setTime(new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthString));
month = cal.get(Calendar.MONTH);
year = (int) SearchWindow.getInstance().EndDate.Year.getSelectedItem();
cal.set(year, month, day);
Date endTime = cal.getTime();
s.setEndTime(endTime);
String fullTaxonomy = "";
String selectedAsset = (String) SearchWindow.getInstance().tax.Asset.getSelectedItem();
int assetIndex = SearchWindow.getInstance().tax.Asset.getSelectedIndex();
int baseIndex = SearchWindow.getInstance().tax.BaseClass.getSelectedIndex();
int subIndex = SearchWindow.getInstance().tax.SubClass.getSelectedIndex();
// Add the Asset to the taxonomy string
fullTaxonomy += UPIStrings.Assets[assetIndex];
fullTaxonomy += ":";
/*
* Add the Base Product and Sub-product to the taxonomy string
* Also set the AssetClass while we're here to make code slightly neater
*/
switch (selectedAsset) {
case "Credit":
s.setAssetClass(AssetClass.CREDIT);
fullTaxonomy += UPIStrings.CreditBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.CreditSubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.CreditSubProducts[baseIndex][subIndex];
}
break;
case "Interest":
s.setAssetClass(AssetClass.RATES);
fullTaxonomy += UPIStrings.InterestBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.InterestSubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.InterestSubProducts[baseIndex][subIndex];
}
break;
case "Commodity":
s.setAssetClass(AssetClass.COMMODITY);
fullTaxonomy += UPIStrings.CommodityBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.CommoditySubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.CommoditySubProducts[baseIndex][subIndex];
}
break;
case "Foreign Exchange":
s.setAssetClass(AssetClass.FOREX);
fullTaxonomy += UPIStrings.ForexBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.ForexSubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.ForexSubProducts[baseIndex][subIndex];
}
break;
case "Equity":
s.setAssetClass(AssetClass.EQUITY);
fullTaxonomy += UPIStrings.EquityBaseProducts[baseIndex];
fullTaxonomy += ":";
if (UPIStrings.EquitySubProducts[baseIndex].length != 0) {
fullTaxonomy += UPIStrings.EquitySubProducts[baseIndex][subIndex];
}
break;
}
s.setUPI(fullTaxonomy);
return s;
}
/*
* Takes a Search and loads its values into the GUI for the user.
*/
public static void loadSearch(String name) {
Search s = Database.getSavedSearch(name);
System.out.println(s.getAsset());
// Set the trade type
if (s.getTradeType() == TradeType.SWAP) {
SearchWindow.getInstance().TradeType.setSelectedItem("Swap");
} else if (s.getTradeType() == TradeType.OPTION) {
SearchWindow.getInstance().TradeType.setSelectedItem("Option");
}
// Set the underlying asset
SearchWindow.getInstance().UnderLyingAsset.setText(s.getAsset());
// Set the minimum price
SearchWindow.getInstance().minValue.setValue(s.getMinPrice());
// Set the maximum price
SearchWindow.getInstance().maxValue.setValue(s.getMaxPrice());
// Set the currency
SearchWindow.getInstance().currency.setSelectedItem((s.getCurrency()));
// Set the start date and end date
Calendar cal = Calendar.getInstance();
cal.setTime(s.getStartTime());
SearchWindow.getInstance().StartDate.Day.setSelectedItem(cal.get(Calendar.DAY_OF_MONTH));
SearchWindow.getInstance().StartDate.Months.setSelectedIndex(cal.get(Calendar.MONTH));
SearchWindow.getInstance().StartDate.Year.setSelectedItem(cal.get(Calendar.YEAR));
cal.setTime(s.getEndTime());
SearchWindow.getInstance().EndDate.Day.setSelectedItem(cal.get(Calendar.DAY_OF_MONTH));
SearchWindow.getInstance().EndDate.Months.setSelectedIndex(cal.get(Calendar.MONTH));
SearchWindow.getInstance().EndDate.Year.setSelectedItem(cal.get(Calendar.YEAR));
// Set the asset class
switch (s.getAssetClass()) {
case COMMODITY:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Commodity");
break;
case RATES:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Interest");
break;
case CREDIT:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Credit");
break;
case EQUITY:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Equity");
break;
case FOREX:
SearchWindow.getInstance().tax.Asset.setSelectedItem("Foreign Exchange");
break;
}
//TODO Set the base product
//TODO Set the sub-product
StatusBar.setMessage("Successfully loaded search '" + name + "'", 1);
}
/*
* Adds a listener to the list of searchListeners to allow them to
* receive results of a query
*/
public static void registerListener(SearchListener s) {
searchListeners.add(s);
}
/*
* Builds a Search and attempts to save it in the database. If this is unsuccessful, puts an
* error message in the StatusBar.
*/
public static void saveSearch(String name) throws ParseException {
// Build a search
Search s = createSearch();
boolean success = Database.getDB().saveSearch(s, name);
if (!success) {
StatusBar.setMessage("Error: could not save search", 1);
return;
}
StatusBar.setMessage("Successfully saved search '" + name + "'", 1);
}
/*
* Builds a Search, sends the query to the database and then passes the result to any of the
* SearchListeners registered to receive it.
*/
public static void search() throws ParseException {
// Build a search
Search s = createSearch();
// Get the result from the database
SearchResult result = Database.getDB().search(s);
// Send it to each member of searchListeners
for (SearchListener l : searchListeners) {
l.getSearchResult(result);
}
//Give search and number of results to analyser
Analyser.analyse(s, result.getNumResults());
}
}
| Fixes #45 by checking for a null when trying to get a saved search | OTCAnalyser/src/uk/ac/cam/cstibhotel/otcanalyser/communicationlayer/CommunicationLayer.java | Fixes #45 by checking for a null when trying to get a saved search | <ide><path>TCAnalyser/src/uk/ac/cam/cstibhotel/otcanalyser/communicationlayer/CommunicationLayer.java
<ide> public static void loadSearch(String name) {
<ide> Search s = Database.getSavedSearch(name);
<ide>
<add> if (s == null) {
<add> // Search could not be loaded, so set an error message and return
<add> StatusBar.setMessage("Failed to load search '" + name + "', search did not exist", 1);
<add> }
<add>
<ide> System.out.println(s.getAsset());
<ide>
<ide> // Set the trade type |
|
Java | apache-2.0 | 12f4a3ceb095aa10c2039d9c8cf18c64fdae438e | 0 | jtarrio/debloat | package org.tarrio.dilate;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class AlgorithmRegistry {
private static final String XML_CONFIG_FILE = "dilate-algorithms.xml";
private static final AlgorithmRegistry instance = new AlgorithmRegistry()
.readConfiguration();
private Map<String, CompressorProvider> algorithms;
AlgorithmRegistry() {
this.algorithms = new HashMap<String, CompressorProvider>();
}
AlgorithmRegistry readConfiguration() {
try {
registerFromXml(getClass().getResourceAsStream(XML_CONFIG_FILE));
return this;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void registerFromProperties(InputStream stream)
throws ClassNotFoundException, IOException {
Properties properties = new Properties();
properties.load(stream);
for (Object key : properties.keySet()) {
register((String) key, (String) properties.get(key));
}
}
public void registerFromXml(InputStream stream)
throws ClassNotFoundException, IOException {
Properties properties = new Properties();
properties.loadFromXML(stream);
for (Object key : properties.keySet()) {
register((String) key, (String) properties.get(key));
}
}
public static AlgorithmRegistry getInstance() {
return instance;
}
public Compressor get(String algorithm) {
CompressorProvider provider = algorithms.get(algorithm);
return provider == null ? null : provider.get();
}
public Compressor get(Codec.Decoder decoder) throws IOException {
return get(decoder.getAlgoritm());
}
public Set<String> getAlgorithms() {
return algorithms.keySet();
}
public void register(String algorithm, CompressorProvider compressorProvider) {
algorithms.put(algorithm, compressorProvider);
}
public void register(String algorithm,
final Class<? extends Compressor> compressorClass) {
algorithms.put(algorithm, new CompressorProvider() {
@Override
public Compressor get() {
try {
return compressorClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
});
}
public void register(String algorithm, final Compressor compressor) {
algorithms.put(algorithm, new CompressorProvider() {
@Override
public Compressor get() {
return compressor;
}
});
}
@SuppressWarnings("unchecked")
public void register(String algorithm, String className)
throws ClassNotFoundException {
register(algorithm, (Class<Compressor>) Class.forName(className));
}
public interface CompressorProvider {
public Compressor get();
}
}
| src/main/java/org/tarrio/dilate/AlgorithmRegistry.java | package org.tarrio.dilate;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class AlgorithmRegistry {
private static final String XML_CONFIG_FILE = "dilate-algorithms.xml";
private static final AlgorithmRegistry instance = new AlgorithmRegistry()
.readConfiguration();
private Map<String, CompressorProvider> algorithms;
AlgorithmRegistry() {
this.algorithms = new HashMap<String, CompressorProvider>();
}
AlgorithmRegistry readConfiguration() {
try {
registerFromXml(AlgorithmRegistryTest.class
.getResourceAsStream(XML_CONFIG_FILE));
return this;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void registerFromProperties(InputStream stream)
throws ClassNotFoundException, IOException {
Properties properties = new Properties();
properties.load(stream);
for (Object key : properties.keySet()) {
register((String) key, (String) properties.get(key));
}
}
public void registerFromXml(InputStream stream)
throws ClassNotFoundException, IOException {
Properties properties = new Properties();
properties.loadFromXML(stream);
for (Object key : properties.keySet()) {
register((String) key, (String) properties.get(key));
}
}
public static AlgorithmRegistry getInstance() {
return instance;
}
public Compressor get(String algorithm) {
CompressorProvider provider = algorithms.get(algorithm);
return provider == null ? null : provider.get();
}
public Compressor get(Codec.Decoder decoder) throws IOException {
return get(decoder.getAlgoritm());
}
public Set<String> getAlgorithms() {
return algorithms.keySet();
}
public void register(String algorithm, CompressorProvider compressorProvider) {
algorithms.put(algorithm, compressorProvider);
}
public void register(String algorithm,
final Class<? extends Compressor> compressorClass) {
algorithms.put(algorithm, new CompressorProvider() {
@Override
public Compressor get() {
try {
return compressorClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
});
}
public void register(String algorithm, final Compressor compressor) {
algorithms.put(algorithm, new CompressorProvider() {
@Override
public Compressor get() {
return compressor;
}
});
}
@SuppressWarnings("unchecked")
public void register(String algorithm, String className)
throws ClassNotFoundException {
register(algorithm, (Class<Compressor>) Class.forName(className));
}
public interface CompressorProvider {
public Compressor get();
}
}
| Fix AlgorithmRegistry
| src/main/java/org/tarrio/dilate/AlgorithmRegistry.java | Fix AlgorithmRegistry | <ide><path>rc/main/java/org/tarrio/dilate/AlgorithmRegistry.java
<ide>
<ide> AlgorithmRegistry readConfiguration() {
<ide> try {
<del> registerFromXml(AlgorithmRegistryTest.class
<del> .getResourceAsStream(XML_CONFIG_FILE));
<add> registerFromXml(getClass().getResourceAsStream(XML_CONFIG_FILE));
<ide> return this;
<ide> } catch (ClassNotFoundException e) {
<ide> throw new RuntimeException(e); |
|
Java | epl-1.0 | 30b461f5dfdbd0df87cca6a727df08a35ca8dbbc | 0 | fabioz/Pydev,akurtakov/Pydev,fabioz/Pydev,fabioz/Pydev,akurtakov/Pydev,akurtakov/Pydev,akurtakov/Pydev,fabioz/Pydev,akurtakov/Pydev,akurtakov/Pydev,fabioz/Pydev,fabioz/Pydev | /**
* Copyright (c) 2013-2015 by Brainwy Software Ltda, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.overview_ruler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Composite;
import org.python.pydev.shared_core.log.Log;
public final class StyledTextWithoutVerticalBar extends StyledText {
public StyledTextWithoutVerticalBar(Composite parent, int style) {
super(parent, style);
}
/**
* Optimization:
* The method:
* org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(int[], StyleRange[])
*
* is *extremely* inefficient on huge documents with lots of styles when
* ranges are not passed and have to be computed in the block:
*
* if (newRanges == null && COMPACT_STYLES) {
*
* So, we just pre-create the ranges here (Same thing on org.brainwy.liclipsetext.editor.common.LiClipseSourceViewer.StyledTextImproved)
* A patch should later be given to SWT itself.
*/
@Override
public void setStyleRanges(StyleRange[] styles) {
if (styles != null) {
int[] newRanges = createRanges(styles);
super.setStyleRanges(newRanges, styles);
return;
}
super.setStyleRanges(styles);
}
@Override
public void replaceStyleRanges(int start, int length, StyleRange[] styles) {
checkWidget();
if (isListening(ST.LineGetStyle)) {
return;
}
if (styles == null) {
SWT.error(SWT.ERROR_NULL_ARGUMENT);
}
int[] newRanges = createRanges(styles);
setStyleRanges(start, length, newRanges, styles);
}
private int[] createRanges(StyleRange[] styles) throws AssertionError {
int charCount = this.getCharCount();
int[] newRanges = new int[styles.length << 1];
int endOffset = -1;
for (int i = 0, j = 0; i < styles.length; i++) {
StyleRange newStyle = styles[i];
if (endOffset > newStyle.start) {
String msg = "Error endOffset (" + endOffset + ") > next style start (" + newStyle.start + ")";
Log.log(msg);
int diff = endOffset - newStyle.start;
newStyle.start = endOffset;
newStyle.length -= diff;
if (newStyle.length < 0) {
// Unable to fix it
throw new AssertionError(msg);
}
}
endOffset = newStyle.start + newStyle.length;
if (endOffset > charCount) {
String msg = "Error endOffset (" + endOffset + ") > charCount (" + charCount + ")";
Log.log(msg);
newStyle.length -= endOffset - charCount;
if (newStyle.length < 0) {
// Unable to fix it
throw new AssertionError(msg);
}
}
newRanges[j++] = newStyle.start;
newRanges[j++] = newStyle.length;
}
return newRanges;
}
} | plugins/org.python.pydev.shared_ui/src_overview_ruler/org/python/pydev/overview_ruler/StyledTextWithoutVerticalBar.java | /**
* Copyright (c) 2013-2015 by Brainwy Software Ltda, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.overview_ruler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Composite;
import org.python.pydev.shared_core.log.Log;
public final class StyledTextWithoutVerticalBar extends StyledText {
public StyledTextWithoutVerticalBar(Composite parent, int style) {
super(parent, style);
}
/**
* Optimization:
* The method:
* org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(int[], StyleRange[])
*
* is *extremely* inefficient on huge documents with lots of styles when
* ranges are not passed and have to be computed in the block:
*
* if (newRanges == null && COMPACT_STYLES) {
*
* So, we just pre-create the ranges here (Same thing on org.brainwy.liclipsetext.editor.common.LiClipseSourceViewer.StyledTextImproved)
* A patch should later be given to SWT itself.
*/
@Override
public void setStyleRanges(StyleRange[] styles) {
if (styles != null) {
int[] newRanges = createRanges(styles);
super.setStyleRanges(newRanges, styles);
return;
}
super.setStyleRanges(styles);
}
@Override
public void replaceStyleRanges(int start, int length, StyleRange[] styles) {
checkWidget();
if (isListening(ST.LineGetStyle)) {
return;
}
if (styles == null) {
SWT.error(SWT.ERROR_NULL_ARGUMENT);
}
int[] newRanges = createRanges(styles);
setStyleRanges(start, length, newRanges, styles);
}
private int[] createRanges(StyleRange[] styles) throws AssertionError {
int charCount = this.getCharCount();
int[] newRanges = new int[styles.length << 1];
for (int i = 0, j = 0; i < styles.length; i++) {
StyleRange newStyle = styles[i];
int endOffset = newStyle.start + newStyle.length;
if (endOffset > charCount) {
String msg = "Error endOffset (" + endOffset + ") > charCount (" + charCount + ")";
Log.log(msg);
newStyle.length -= endOffset - charCount;
if (newStyle.length < 0) {
// Unable to fix it
throw new AssertionError(msg);
}
}
newRanges[j++] = newStyle.start;
newRanges[j++] = newStyle.length;
}
return newRanges;
}
} | One more check when setting style ranges.
| plugins/org.python.pydev.shared_ui/src_overview_ruler/org/python/pydev/overview_ruler/StyledTextWithoutVerticalBar.java | One more check when setting style ranges. | <ide><path>lugins/org.python.pydev.shared_ui/src_overview_ruler/org/python/pydev/overview_ruler/StyledTextWithoutVerticalBar.java
<ide> int charCount = this.getCharCount();
<ide>
<ide> int[] newRanges = new int[styles.length << 1];
<add> int endOffset = -1;
<ide> for (int i = 0, j = 0; i < styles.length; i++) {
<ide> StyleRange newStyle = styles[i];
<del> int endOffset = newStyle.start + newStyle.length;
<add> if (endOffset > newStyle.start) {
<add> String msg = "Error endOffset (" + endOffset + ") > next style start (" + newStyle.start + ")";
<add> Log.log(msg);
<add> int diff = endOffset - newStyle.start;
<add> newStyle.start = endOffset;
<add> newStyle.length -= diff;
<add> if (newStyle.length < 0) {
<add> // Unable to fix it
<add> throw new AssertionError(msg);
<add> }
<add> }
<add>
<add> endOffset = newStyle.start + newStyle.length;
<ide> if (endOffset > charCount) {
<ide> String msg = "Error endOffset (" + endOffset + ") > charCount (" + charCount + ")";
<ide> Log.log(msg); |
|
Java | agpl-3.0 | b4708cde3bdf1d8d1e9bd0452774d41bdc2ceb93 | 0 | hbz/etikett,hbz/etikett,hbz/etikett,hbz/etikett | /*Copyright (c) 2015 "hbz"
This file is part of etikett.
etikett is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package helper;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Normalizer;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.rio.RDFFormat;
/**
* @author Jan Schnasse
*
*/
@SuppressWarnings("javadoc")
public class GndLabelResolver implements LabelResolver {
public final static String DOMAIN = "d-nb.info";
final public static String protocol = "https://";
final public static String alternateProtocol = "http://";
final public static String namespace = "d-nb.info/standards/elementset/gnd#";
final public static String id = alternateProtocol + "d-nb.info/gnd/";
final public static String id2 = protocol + "d-nb.info/gnd/";
public static Properties turtleObjectProp = new Properties();
private Connector conn = null;
private static void setProperties() {
turtleObjectProp.setProperty("namespace", "d-nb.info/standards/elementset/gnd#");
turtleObjectProp.setProperty("preferredName", "preferredName");
turtleObjectProp.setProperty("preferredNameForTheConferenceOrEvent", "preferredNameForTheConferenceOrEvent");
turtleObjectProp.setProperty("preferredNameForTheCorporateBody", "preferredNameForTheCorporateBody");
turtleObjectProp.setProperty("preferredNameForThePerson", "preferredNameForThePerson");
turtleObjectProp.setProperty("preferredNameForThePlaceOrGeographicName",
"preferredNameForThePlaceOrGeographicName");
turtleObjectProp.setProperty("preferredNameForTheSubjectHeading", "preferredNameForTheSubjectHeading");
turtleObjectProp.setProperty("preferredNameForTheWork", "preferredNameForTheWork");
}
/**
* @param uri
* analyes data from the url to find a proper label
* @return a label
*/
public String lookup(String uri, String language) {
try {
play.Logger.info("Lookup Label from GND. Language selection is not supported yet! " + uri);
// Workaround for d-nb: change protocol to https
// String sslUrl = uri.replace("http://", "https://");
// URL dnbUrl = new URL(sslUrl + "/about/lds");
Collection<Statement> statement = RdfUtils.readRdfToGraph(new URL(uri + "/about/lds"), RDFFormat.RDFXML,
"application/rdf+xml");
Iterator<Statement> sit = statement.iterator();
while (sit.hasNext()) {
Statement s = sit.next();
boolean isLiteral = s.getObject() instanceof Literal;
if (!(s.getSubject() instanceof BNode)) {
if (isLiteral) {
ValueFactory v = SimpleValueFactory.getInstance();
Statement newS = v.createStatement(s.getSubject(), s.getPredicate(), v.createLiteral(
Normalizer.normalize(s.getObject().stringValue(), Normalizer.Form.NFKC)));
String label = findLabel(newS, uri);
if (label != null) {
play.Logger.info("Found Label: " + label);
return label;
} else {
String finalUrl = Connector.Factory.getInstance(new URL(uri)).getFinalUrl().toString()
.replace("/about/lds/", "");
label = findLabel(newS, finalUrl);
if (label != null) {
play.Logger.info("Found Label with last redirected Url: " + label);
return label;
}
}
play.Logger.debug("Statement not feasable:" + s.getSubject() + " " + s.getPredicate() + " "
+ s.getObject());
}
}
}
play.Logger.info("GndLabelResolver.findLabel failed to find Label within Statement");
} catch (Exception e) {
play.Logger.error("Failed to find label for " + uri);
}
return null;
}
private static String findLabel(Statement s, String uri) {
if (!uri.equals(s.getSubject().stringValue())) {
return null;
}
GndLabelResolver.setProperties();
Enumeration<Object> keys = turtleObjectProp.keys();
while (keys.hasMoreElements()) {
String predicate = protocol + namespace + turtleObjectProp.getProperty((String) keys.nextElement());
if (predicate.equals(s.getPredicate().stringValue())) {
return s.getObject().stringValue();
}
}
keys = turtleObjectProp.keys();
while (keys.hasMoreElements()) {
String predicate = alternateProtocol + namespace
+ turtleObjectProp.getProperty((String) keys.nextElement());
if (predicate.equals(s.getPredicate().stringValue())) {
return s.getObject().stringValue();
}
}
return null;
}
public Connector getConnector(String urlString, String accept) {
conn = null;
URL url;
try {
url = URLUtil.createUrl(urlString);
Connector conn = Connector.Factory.getInstance(url);
conn.setConnectorProperty("Accept", accept);
} catch (MalformedURLException e) {
play.Logger.warn("Can't create Connector from " + urlString);
}
return conn;
}
}
| app/helper/GndLabelResolver.java | /*Copyright (c) 2015 "hbz"
This file is part of etikett.
etikett is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package helper;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Normalizer;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.rio.RDFFormat;
/**
* @author Jan Schnasse
*
*/
@SuppressWarnings("javadoc")
public class GndLabelResolver implements LabelResolver {
public final static String DOMAIN = "d-nb.info";
final public static String protocol = "https://";
final public static String alternateProtocol = "http://";
final public static String namespace = "d-nb.info/standards/elementset/gnd#";
final public static String id = alternateProtocol + "d-nb.info/gnd/";
final public static String id2 = protocol + "d-nb.info/gnd/";
public static Properties turtleObjectProp = new Properties();
private Connector conn = null;
private static void setProperties() {
turtleObjectProp.setProperty("namespace", "d-nb.info/standards/elementset/gnd#");
turtleObjectProp.setProperty("preferredName", "preferredName");
turtleObjectProp.setProperty("preferredNameForTheConferenceOrEvent", "preferredNameForTheConferenceOrEvent");
turtleObjectProp.setProperty("preferredNameForTheCorporateBody", "preferredNameForTheCorporateBody");
turtleObjectProp.setProperty("preferredNameForThePerson", "preferredNameForThePerson");
turtleObjectProp.setProperty("preferredNameForThePlaceOrGeographicName",
"preferredNameForThePlaceOrGeographicName");
turtleObjectProp.setProperty("preferredNameForTheSubjectHeading", "preferredNameForTheSubjectHeading");
turtleObjectProp.setProperty("preferredNameForTheWork", "preferredNameForTheWork");
}
/**
* @param uri
* analyes data from the url to find a proper label
* @return a label
*/
public String lookup(String uri, String language) {
try {
play.Logger.info("Lookup Label from GND. Language selection is not supported yet! " + uri);
// Workaround for d-nb: change protocol to https
// String sslUrl = uri.replace("http://", "https://");
// URL dnbUrl = new URL(sslUrl + "/about/lds");
Collection<Statement> statement = RdfUtils.readRdfToGraph(new URL(uri), RDFFormat.RDFXML,
"application/rdf+xml");
play.Logger.debug("created Satement ? " + statement.toString());
Iterator<Statement> sit = statement.iterator();
while (sit.hasNext()) {
Statement s = sit.next();
boolean isLiteral = s.getObject() instanceof Literal;
if (!(s.getSubject() instanceof BNode)) {
if (isLiteral) {
ValueFactory v = SimpleValueFactory.getInstance();
Statement newS = v.createStatement(s.getSubject(), s.getPredicate(), v.createLiteral(
Normalizer.normalize(s.getObject().stringValue(), Normalizer.Form.NFKC)));
String label = findLabel(newS, uri);
if (label != null) {
play.Logger.info("Found Label: " + label);
return label;
} else {
label = findLabel(newS,
Connector.Factory.getInstance(new URL(uri)).getFinalUrl().toString());
if (label != null) {
play.Logger.info("Found Label with last redirected Url: " + label);
return label;
}
}
play.Logger.debug("Statement not feasable:" + s.getSubject() + " " + s.getPredicate() + " "
+ s.getObject());
}
}
}
play.Logger.info("GndLabelResolver.findLabel failed to find Label within Statement");
} catch (Exception e) {
play.Logger.error("Failed to find label for " + uri);
}
return null;
}
private static String findLabel(Statement s, String uri) {
if (!uri.equals(s.getSubject().stringValue())) {
return null;
}
GndLabelResolver.setProperties();
Enumeration<Object> keys = turtleObjectProp.keys();
while (keys.hasMoreElements()) {
String predicate = protocol + namespace + turtleObjectProp.getProperty((String) keys.nextElement());
if (predicate.equals(s.getPredicate().stringValue())) {
return s.getObject().stringValue();
}
}
keys = turtleObjectProp.keys();
while (keys.hasMoreElements()) {
String predicate = alternateProtocol + namespace
+ turtleObjectProp.getProperty((String) keys.nextElement());
if (predicate.equals(s.getPredicate().stringValue())) {
return s.getObject().stringValue();
}
}
return null;
}
public Connector getConnector(String urlString, String accept) {
conn = null;
URL url;
try {
url = URLUtil.createUrl(urlString);
Connector conn = Connector.Factory.getInstance(url);
conn.setConnectorProperty("Accept", accept);
} catch (MalformedURLException e) {
play.Logger.warn("Can't create Connector from " + urlString);
}
return conn;
}
}
| going back to the last working version
| app/helper/GndLabelResolver.java | going back to the last working version | <ide><path>pp/helper/GndLabelResolver.java
<ide> // Workaround for d-nb: change protocol to https
<ide> // String sslUrl = uri.replace("http://", "https://");
<ide> // URL dnbUrl = new URL(sslUrl + "/about/lds");
<del> Collection<Statement> statement = RdfUtils.readRdfToGraph(new URL(uri), RDFFormat.RDFXML,
<add> Collection<Statement> statement = RdfUtils.readRdfToGraph(new URL(uri + "/about/lds"), RDFFormat.RDFXML,
<ide> "application/rdf+xml");
<ide>
<del> play.Logger.debug("created Satement ? " + statement.toString());
<ide> Iterator<Statement> sit = statement.iterator();
<ide>
<ide> while (sit.hasNext()) {
<ide> play.Logger.info("Found Label: " + label);
<ide> return label;
<ide> } else {
<del> label = findLabel(newS,
<del> Connector.Factory.getInstance(new URL(uri)).getFinalUrl().toString());
<add> String finalUrl = Connector.Factory.getInstance(new URL(uri)).getFinalUrl().toString()
<add> .replace("/about/lds/", "");
<add> label = findLabel(newS, finalUrl);
<ide> if (label != null) {
<ide> play.Logger.info("Found Label with last redirected Url: " + label);
<ide> return label;
<ide> }
<ide> play.Logger.debug("Statement not feasable:" + s.getSubject() + " " + s.getPredicate() + " "
<ide> + s.getObject());
<del>
<ide> }
<ide> }
<ide> } |
|
Java | mit | ca2f2db17eba70e32e37f0bd579091c1db9ab37b | 0 | mizukyf/cmdexec | package org.doogwood.cmdexec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 入力ストリームを生成する出力ストリーム.
* 出力ストリームとして何かしらの処理の結果を受け取り内部的に貯めこんで、
* その結果をもとにして入力ストリームを生成する。
*/
public final class PipeOutputStream extends OutputStream {
/**
* 一時ファイル作成を判断する閾値.
*/
private final int threshold;
/**
* これまでに書き込んだバイト数.
*/
private int byteCount = 0;
/**
* データを貯めこむバイト配列ストリーム.
*/
private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
/**
* データを貯めこむ一時ファイル.
*/
private File tempFile = null;
/**
* 一時ファイルのための出力ストリーム.
*/
private FileOutputStream tempFileOutputStream = null;
/**
* ストリームへの書き込みが終わっているかどうかを示す.
*/
private boolean closed = false;
/**
* コンストラクタ.
* @param threshold 一時ファイル作成を判断する閾値(単位はバイト)
*/
public PipeOutputStream(final int threshold) {
if (threshold < 0) {
throw new IllegalArgumentException();
}
this.threshold = threshold;
}
/**
* コンストラクタ.
* 一時ファイル作成を判断する閾値には1MB({@code 1028 * 1028}バイト)が設定される。
*/
public PipeOutputStream() {
this(1028 * 1028);
}
@Override
public void write(final int b) throws IOException {
if (byteCount < threshold) {
byteCount ++;
writeIntoByteArray(b);
} else {
if (tempFile == null) {
makeTempFile();
}
writeIntoTempFile(b);
}
}
private void makeTempFile() throws IOException {
tempFile = File.createTempFile("pipeOutputStream", ".tmp");
tempFile.deleteOnExit();
tempFileOutputStream = new FileOutputStream(tempFile);
tempFileOutputStream.write(byteArrayOutputStream.toByteArray());
byteArrayOutputStream = null;
}
private void writeIntoTempFile(final int b) throws IOException {
tempFileOutputStream.write(b);
}
private void writeIntoByteArray(final int b) {
byteArrayOutputStream.write(b);
}
/**
* 一時ファイルを使用している場合{@code true}を返す.
* @return 判定結果
*/
public boolean isUsingTempFile() {
return tempFile != null;
}
/**
* データを読み込む準備ができている場合{@code true}を返す.
* このメソッドが{@code true}を返した場合、
* この{@code OutputStream}へのデータの書き出しが完了しており、
* {@link #getInputStream()}を呼び出す準備ができていることを示す。
* @return 判定結果
*/
public boolean isReadyForReading() {
return closed;
}
@Override
public final void close() throws IOException {
if (tempFileOutputStream != null) {
tempFileOutputStream.close();
tempFileOutputStream = null;
}
closed = true;
}
/**
* 入力ストリームを生成して返す.
* @return 入力ストリーム
* @throws IOException
*/
public InputStream getInputStream() throws IOException {
if (!isReadyForReading()) {
throw new IllegalStateException();
}
if (tempFile == null) {
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} else {
return new FileInputStream(tempFile);
}
}
}
| src/main/java/org/doogwood/cmdexec/PipeOutputStream.java | package org.doogwood.cmdexec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 入力ストリームを生成する出力ストリーム.
* 出力ストリームとして何かしらの処理の結果を受け取り内部的に貯めこんで、
* その結果をもとにして入力ストリームを生成する。
*/
public final class PipeOutputStream extends OutputStream {
/**
* 一時ファイル作成を判断する閾値.
*/
private final int threshold;
/**
* これまでに書き込んだバイト数.
*/
private int byteCount = 0;
/**
* データを貯めこむバイト配列ストリーム.
*/
private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
/**
* データを貯めこむ一時ファイル.
*/
private File tempFile = null;
/**
* 一時ファイルのための出力ストリーム.
*/
private FileOutputStream tempFileOutputStream = null;
/**
* ストリームへの書き込みが終わっているかどうかを示す.
*/
private boolean closed = false;
/**
* コンストラクタ.
* @param threshold 一時ファイル作成を判断する閾値(単位はバイト)
*/
public PipeOutputStream(final int threshold) {
if (threshold < 0) {
throw new IllegalArgumentException();
}
this.threshold = threshold;
}
/**
* コンストラクタ.
* 一時ファイル作成を判断する閾値には1MB({@code 1028 * 1028}バイト)が設定される。
*/
public PipeOutputStream() {
this(1028 * 1028);
}
@Override
public void write(final int b) throws IOException {
byteCount ++;
if (byteCount <= threshold) {
writeIntoByteArray(b);
} else {
if (tempFile == null) {
makeTempFile();
}
writeIntoTempFile(b);
}
}
private void makeTempFile() throws IOException {
tempFile = File.createTempFile("pipeOutputStream", ".tmp");
tempFile.deleteOnExit();
tempFileOutputStream = new FileOutputStream(tempFile);
tempFileOutputStream.write(byteArrayOutputStream.toByteArray());
byteArrayOutputStream = null;
}
private void writeIntoTempFile(final int b) throws IOException {
tempFileOutputStream.write(b);
}
private void writeIntoByteArray(final int b) {
byteArrayOutputStream.write(b);
}
/**
* 一時ファイルを使用している場合{@code true}を返す.
* @return 判定結果
*/
public boolean isUsingTempFile() {
return tempFile != null;
}
/**
* データを読み込む準備ができている場合{@code true}を返す.
* このメソッドが{@code true}を返した場合、
* この{@code OutputStream}へのデータの書き出しが完了しており、
* {@link #getInputStream()}を呼び出す準備ができていることを示す。
* @return 判定結果
*/
public boolean isReadyForReading() {
return closed;
}
@Override
public final void close() throws IOException {
if (tempFileOutputStream != null) {
tempFileOutputStream.close();
tempFileOutputStream = null;
}
closed = true;
}
/**
* 入力ストリームを生成して返す.
* @return 入力ストリーム
* @throws IOException
*/
public InputStream getInputStream() throws IOException {
if (!isReadyForReading()) {
throw new IllegalStateException();
}
if (tempFile == null) {
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} else {
return new FileInputStream(tempFile);
}
}
}
| 数十億バイト書き込んだあと発生しうる問題への対処
| src/main/java/org/doogwood/cmdexec/PipeOutputStream.java | 数十億バイト書き込んだあと発生しうる問題への対処 | <ide><path>rc/main/java/org/doogwood/cmdexec/PipeOutputStream.java
<ide>
<ide> @Override
<ide> public void write(final int b) throws IOException {
<del> byteCount ++;
<del> if (byteCount <= threshold) {
<add> if (byteCount < threshold) {
<add> byteCount ++;
<ide> writeIntoByteArray(b);
<ide> } else {
<ide> if (tempFile == null) { |
|
Java | apache-2.0 | 791dd0d062b9f764949666f4d56d9ef215ab36dc | 0 | seanox/devwex,seanox/devwex,seanox/devwex,seanox/devwex | /**
* LIZENZBEDINGUNGEN - Seanox Software Solutions ist ein Open-Source-Projekt, im
* Folgenden Seanox Software Solutions oder kurz Seanox genannt.
* Diese Software unterliegt der Version 2 der Apache License.
*
* Devwex, Advanced Server Development
* Copyright (C) 2022 Seanox Software Solutions
*
* 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.seanox.devwex;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.net.ssl.SSLSocket;
/**
* Worker, wartet auf eingehende HTTP-Anfrage, wertet diese aus, beantwortet
* diese entsprechend der HTTP-Methode und protokolliert den Zugriff.<br>
* <br>
* Hinweis zum Thema Fehlerbehandlung - Die Verarbeitung der Requests soll so
* tolerant wie möglich erfolgen. Somit werden interne Fehler, wenn
* möglich, geschluckt und es erfolgt eine alternative aber sichere
* Beantwortung. Kann der Request nicht mehr kontrolliert werden, erfolgt ein
* kompletter Abbruch.
*
* @author Seanox Software Solutions
* @version 5.5.0 20220912
*/
class Worker implements Runnable {
/** Server Context */
private volatile String context;
/** Socket vom Worker */
private volatile Socket accept;
/** Socket des Servers */
private volatile ServerSocket socket;
/** Server Konfiguration */
private volatile Initialize initialize;
/** Dateneingangsstrom */
private volatile InputStream input;
/** Datenausgangsstrom */
private volatile OutputStream output;
/** Zugriffsrechte des Servers */
private volatile Section access;
/** Umgebungsvariablen des Servers */
private volatile Section environment;
/** Felder des Request-Headers */
private volatile Section fields;
/** Filter des Servers */
private volatile Section filters;
/** Common Gateway Interfaces des Servers */
private volatile Section interfaces;
/** Konfiguration des Servers */
private volatile Section options;
/** virtuelle Verzeichnisse des Servers */
private volatile Section references;
/** Mediatypes des Servers */
private volatile Section mediatypes;
/** Statuscodes des Servers */
private volatile Section statuscodes;
/** Dokumentenverzeichnis des Servers */
private volatile String docroot;
/** Header des Requests */
private volatile String header;
/** Mediatype des Requests */
private volatile String mediatype;
/** Resource des Requests */
private volatile String resource;
/** Gateway Interface */
private volatile String gateway;
/** Systemverzeichnis des Servers */
private volatile String sysroot;
/** Datenflusskontrolle */
private volatile boolean control;
/** Blockgrösse für Datenzugriffe */
private volatile int blocksize;
/** Statuscode des Response */
private volatile int status;
/** Interrupt für Systemprozesse im Millisekunden */
private volatile long interrupt;
/** Timeout beim ausgehenden Datentransfer in Millisekunden */
private volatile long isolation;
/** Timeout bei Datenleerlauf in Millisekunden */
private volatile long timeout;
/** Menge der übertragenen Daten */
private volatile long volume;
/**
* Konstruktor, richtet den Worker mit Socket ein.
* @param context Server Context
* @param socket Socket mit dem eingegangen Request
* @param initialize Server Konfiguraiton
*/
Worker(String context, ServerSocket socket, Initialize initialize) {
context = context.replaceAll("(?i):[a-z]+$", "");
this.context = context;
this.socket = socket;
this.initialize = initialize;
}
/**
* Entfernt aus dem String Parameter und Optionen im Format {@code [...]}.
* Bereinigt werden alle Angaben, ob voll- oder unvollständig, ab dem
* ersten Vorkommen.
* @param string zu bereinigender String
* @return der String ohne Parameter und Optionen
*/
private static String cleanOptions(String string) {
int cursor = string.indexOf('[');
if (cursor >= 0)
string = string.substring(0, cursor).trim();
return string;
}
/**
* Creates a hexadecimal MD5 hash for the string.
* @param string for which the hash is to be created
* @return the created hexadecimal MD5 hash
* @throws Exception
* In case of unexpected errors
*/
private static String textHash(String string)
throws Exception {
if (string == null)
string = "";
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] bytes = digest.digest(string.getBytes());
string = new BigInteger(1, bytes).toString(16);
while (string.length() < 32)
string = ("0").concat(string);
return string;
}
/**
* Escapes the control characters in the string: BS, HT, LF, FF, CR, ', ", \
* and characters outside the ASCII range 0x20-0x7F with a slash sequence:
* <ul>
* <li>Slash + ISO</li>
* <li>Slash + three bytes octal (0x80-0xFF)</li>
* <li>Slash + four bytes hexadecimal (0x100-0xFFFF)</li>
* </ul>
* @param string string to be escaped
* @return the string with escaped characters
*/
private static String textEscape(String string) {
if (string == null)
return null;
int length = string.length();
byte[] codex = ("\b\t\n\f\r\"'\\btnfr\"'\\").getBytes();
byte[] codec = ("0123456789ABCDEF").getBytes();
byte[] cache = new byte[length *6];
int count = 0;
for (int loop = 0; loop < length; loop++) {
int code = string.charAt(loop);
int cursor = Arrays.binarySearch(codex, (byte)code);
if (cursor >= 0 && cursor < 8) {
cache[count++] = '\\';
cache[count++] = codex[cursor +8];
} else if (code > 0xFF) {
cache[count++] = '\\';
cache[count++] = 'u';
cache[count++] = codec[(code >> 12) & 0xF];
cache[count++] = codec[(code >> 8) & 0xF];
cache[count++] = codec[(code >> 4) & 0xF];
cache[count++] = codec[(code & 0xF)];
} else if (code < 0x20 || code > 0x7F) {
cache[count++] = '\\';
cache[count++] = 'x';
cache[count++] = codec[(code >> 4) & 0xF];
cache[count++] = codec[(code & 0xF)];
} else cache[count++] = (byte)code;
}
return new String(cache, 0, count);
}
/**
* Decodes URL and UTF-8 optionally encoded parts in a string. Non-compliant
* sequences do cause an error, instead they remain as unknown encoding.
* @param string String to be decoded
* @return the decoded string
*/
private static String textDecode(String string) {
if (string == null)
string = "";
// Part 1: URL decoding
// Non-compliant sequences do cause an error, instead they remain as
// unknown encoding
int length = string.length();
byte[] bytes = new byte[length *2];
int count = 0;
for (int loop = 0; loop < length; loop++) {
// ASCII code is determined
int code = string.charAt(loop);
// Plus sign is converted to space.
if (code == 43)
code = 32;
// Hexadecimal sequences are converted to ASCII character
if (code == 37) {
loop += 2;
try {code = Integer.parseInt(string.substring(loop -1, loop +1), 16);
} catch (Throwable throwable) {
loop -= 2;
}
}
bytes[count++] = (byte)code;
}
// Part 2: UTF-8 decoding
// Non-compliant sequences do cause an error, instead they remain as
// unknown encoding
bytes = Arrays.copyOfRange(bytes, 0, count);
length = bytes.length;
int cursor = 0;
int digit = 0;
boolean control = false;
for (int loop = count = 0; loop < length; loop++) {
// ASCII code is determined
int code = bytes[loop] & 0xFF;
if (code >= 0xC0 && code <= 0xC3)
control = true;
// Decoding of the bytes as UTF-8.
// The pattern 10xxxxxx is extended by the 6Bits
if ((code & 0xC0) == 0x80) {
digit = (digit << 0x06) | (code & 0x3F);
if (--cursor == 0) {
bytes[count++] = (byte)digit;
control = false;
}
} else {
digit = 0;
cursor = 0;
// 0xxxxxxx (7Bit/0Byte) are used directly
if (((code & 0x80) == 0x00) || !control) {
bytes[count++] = (byte)code;
control = false;
}
// 110xxxxx (5Bit/1Byte), 1110xxxx (4Bit/2Byte),
// 11110xxx (3Bit/3Byte), 111110xx (2Bit/4Byte),
// 1111110x (1Bit/5Byte)
if ((code & 0xE0) == 0xC0) {
cursor = 1;
digit = code & 0x1F;
} else if ((code & 0xF0) == 0xE0) {
cursor = 2;
digit = code & 0x0F;
} else if ((code & 0xF8) == 0xF0) {
cursor = 3;
digit = code & 0x07;
} else if ((code & 0xFC) == 0xF8) {
cursor = 4;
digit = code & 0x03;
} else if ((code & 0xFE) == 0xFC) {
cursor = 5;
digit = code & 0x01;
}
}
}
return new String(bytes, 0, count);
}
/**
* Formatiert das Datum im angebenden Format und in der angegebenen Zone.
* Rückgabe das formatierte Datum, im Fehlerfall ein leerer String.
* @param format Formatbeschreibung
* @param date zu formatierendes Datum
* @param zone Zeitzone, {@code null} Standardzone
* @return das formatierte Datum als String, im Fehlerfall leerer String
*/
private static String dateFormat(String format, Date date, String zone) {
SimpleDateFormat pattern;
// die Formatierung wird eingerichtet
pattern = new SimpleDateFormat(format, Locale.US);
// die Zeitzone wird gegebenenfalls fuer die Formatierung gesetzt
if (zone != null) pattern.setTimeZone(TimeZone.getTimeZone(zone));
// die Zeitangabe wird formatiert
return pattern.format(date);
}
/**
* Reads the data of a file as a byte array.
* In case of error null is returned.
* @param file file to be read
* @return the read data, in case of error {@code null}
*/
private static byte[] fileRead(File file) {
try {return Files.readAllBytes(file.toPath());
} catch (Throwable throwable) {
return null;
}
}
/**
* Normalizes the string of a path and resolves existing path directives if
* necessary and changes the backslash to slash.
* @param path Path to be normalized
* @return the normalized path
*/
private static String fileNormalize(String path) {
// path is changed to slash
String string = path.replace('\\', '/').trim();
// multiple slashes are combined
for (int cursor; (cursor = string.indexOf("//")) >= 0;)
string = string.substring(0, cursor).concat(string.substring(cursor +1));
// the path is compensated if necessary /abc/./def/../ghi -> /abc/ghi
// in the path /. is compensated
if (string.endsWith("/."))
string = string.concat("/");
for (int cursor; (cursor = string.indexOf("/./")) >= 0;)
string = string.substring(0, cursor).concat(string.substring(cursor +2));
// in the path /.. is compensated
if (string.endsWith("/.."))
string = string.concat("/");
for (int cursor; (cursor = string.indexOf("/../")) >= 0;) {
String stream;
stream = string.substring(cursor +3);
string = string.substring(0, cursor);
cursor = string.lastIndexOf("/");
cursor = Math.max(0, cursor);
string = string.substring(0, cursor).concat(stream);
}
// multiple consecutive slashes are combined
for (int cursor; (cursor = string.indexOf("//")) >= 0;)
string = string.substring(0, cursor).concat(string.substring(cursor +1));
return string;
}
/**
* Löscht die Ressource, handelt es sich um ein Verzeichnis, werden
* alle Unterdateien und Unterverzeichnisse rekursive gelöscht.
* Rückgabe {@code true} im Fehlerfall {@code false}.
* @param resource zu löschende Ressource
* @return {@code true}, im Fehlerfall {@code false}
*/
private static boolean fileDelete(File resource) {
File[] files;
int loop;
// bei Verzeichnissen wird die Dateiliste ermittelt rekursive geloescht
if (resource.isDirectory()) {
files = resource.listFiles();
if (files == null)
return true;
for (loop = 0; loop < files.length; loop++)
if (!Worker.fileDelete(files[loop]))
return false;
}
// der File oder das leere Verzeichnis wird geloescht, ist dies nicht
// moeglich wird false zurueckgegeben
return resource.delete();
}
/**
* Prüft ob die Ressource dem {@code IF-(UN)MODIFIED-SINCE} entspricht.
* Rückgabe {@code false} wenn die Ressource in Datum und
* Dateigrösse entspricht, sonst {@code true}.
* @param file Dateiobjekt
* @param string Information der Modifikation
* @return {@code true} wenn Unterschiede in Datum oder Dateigrösse
* ermittelt wurden
*/
private static boolean fileIsModified(File file, String string) {
SimpleDateFormat pattern;
StringTokenizer tokenizer;
int cursor;
long timing;
if (string.length() <= 0)
return true;
// If-(Un)Modified-Since wird geprueft
tokenizer = new StringTokenizer(string, ";");
try {
// die Formatierung wird eingerichtet
pattern = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.US);
// die Zeitzone wird gegebenenfalls fuer die Formatierung gesetzt
pattern.setTimeZone(TimeZone.getTimeZone("GMT"));
timing = pattern.parse(tokenizer.nextToken()).getTime() /1000L;
// IF-(UN)MODIFIED-SINCE:TIMEDATE wird ueberprueft
if (timing != file.lastModified() /1000L)
return true;
while (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken().trim();
if (!string.toLowerCase().startsWith("length"))
continue;
cursor = string.indexOf("=");
if (cursor < 0)
continue;
// IF-(UN)MODIFIED-SINCE:LENGTH wird ueberprueft
return file.length() != Long.parseLong(string.substring(cursor +1).trim());
}
} catch (Throwable throwable) {
return true;
}
return false;
}
/**
* Erstellt zu einem abstrakter File das physische File-Objekt.
* @param file abstrakter File
* @return das physische File-Objekt, sonst {@code null}
*/
private static File fileCanonical(File file) {
try {return file.getCanonicalFile();
} catch (Throwable throwable) {
return null;
}
}
/**
* Ruft eine Modul-Methode auf.
* Wenn erforderlich wird das Modul zuvor geladen und initialisiert.
* Module werden global geladen und initialisiert. Ist ein Modul beim Aufruf
* der Methode noch nicht geladen, erfolgt dieses ohne Angabe von Parametern
* mit der ersten Anforderung.<br>
* Soll ein Modul mit Parametern initalisiert werden, muss das Modul in der
* Sektion {@code INITIALIZE} deklariert oder über den
* Context-ClassLoader vom Devwex-Module-SDK geladen werden.
* Rückgabe {@code true} wenn die Ressource geladen und die Methode
* erfolgreich aufgerufen wurde.
* @param resource Resource
* @param invoke Methode
* @return {@code true}, im Fehlerfall {@code false}
*/
private boolean invoke(String resource, String invoke)
throws Exception {
Object object;
Method method;
String string;
if (invoke == null
|| invoke.trim().length() <= 0)
return false;
object = Service.load(Service.load(resource), null);
if (object == null)
return false;
string = this.environment.get("module_opts");
if (string.length() <= 0)
string = null;
// die Methode fuer den Modul-Einsprung wird ermittelt
method = object.getClass().getMethod(invoke, Object.class, String.class);
// die Methode fuer den Modul-Einsprung wird aufgerufen
method.invoke(object, this, string);
return true;
}
/**
* Ermittelt für das angegebene virtuelle Verzeichnis den realen Pfad.
* Wurde der Pfad nicht als virtuelles Verzeichnis eingerichtet, wird ein
* leerer String zurückgegeben.
* @param path Pfad des virtuellen Verzeichnis
* @return der reale Pfad oder ein leerer String
*/
private String locate(String path) {
Enumeration enumeration;
File source;
String access;
String alias;
String locale;
String location;
String options;
String reference;
String result;
String rules;
String shadow;
String buffer;
String string;
String target;
boolean absolute;
boolean connect;
boolean forbidden;
boolean module;
boolean redirect;
boolean virtual;
int cursor;
// der Pfad wird getrimmt, in Kleinbuchstaben umformatiert, die
// Backslashs gegen Slashs getauscht
path = path.replace('\\', '/').trim();
// fuer die Ermittlung wird der Pfad mit / abgeschlossen um auch
// Referenzen wie z.B. /a mit /a/ ermitteln zu koennen
locale = path.toLowerCase();
if (!locale.endsWith("/"))
locale = locale.concat("/");
// initiale Einrichtung der Variablen
access = "";
location = "";
options = "";
reference = "";
result = "";
shadow = "";
absolute = false;
forbidden = false;
module = false;
redirect = false;
source = null;
// die Liste der Referenzen wird ermittelt
enumeration = this.references.elements();
// die virtuellen Verzeichnisse werden ermittelt
while (enumeration.hasMoreElements()) {
// die Regel wird ermittelt
rules = ((String)enumeration.nextElement()).toLowerCase();
rules = this.references.get(rules);
// Alias, Ziel und Optionen werden ermittelt
cursor = rules.indexOf('>');
if (cursor < 0) {
cursor = rules.replace(']', '[').indexOf('[');
if (cursor < 0)
continue;
alias = rules.substring(0, cursor).trim();
rules = rules.substring(cursor).trim();
} else {
alias = rules.substring(0, cursor).trim();
rules = rules.substring(cursor +2).trim();
}
target = Worker.cleanOptions(rules);
alias = Worker.fileNormalize(alias);
// die Optionen werden ermittelt
string = rules.toUpperCase();
virtual = string.contains("[A]") || string.contains("[M]");
connect = string.contains("[M]") || string.contains("[R]");
// ungueltige bzw. unvollstaendige Regeln werden ignoriert
// - ohne Alias
// - Redirect / Modul ohne Ziel
// - Alias ohne Ziel und Optionen
if (alias.length() <= 0
|| (connect && target.length() <= 0)
|| (rules.length() <= 0 && target.length() <= 0))
continue;
// ggf. wird der Alias um Slash erweitert, damit spaeter DOCROOT
// und Alias einen plausiblen Pfad ergeben
if (!alias.startsWith("/"))
alias = ("/").concat(alias);
// ggf. wird der Alias als Target uebernommen, wenn kein Target
// angegeben wurde, z.B. wenn fuer einen realen Pfad nur Optionen
// festgelegt werden
if (target.length() <= 0)
target = this.docroot.concat(alias);
// das Ziel wird mit / abgeschlossen um auch Referenzen zwischen /a
// und /a/ ermitteln zu koennen
buffer = alias;
if (!virtual && !buffer.endsWith("/") && buffer.length() > 0)
buffer = buffer.concat("/");
// die qualifizierteste laengste Refrerenz wird ermittelt
if (locale.startsWith(buffer.toLowerCase())
&& buffer.length() > 0 && reference.length() <= buffer.length()) {
// optional wird die Sperrung des Verzeichnis ermittelt
forbidden = string.contains("[C]");
if (!connect) {
// die Zieldatei wird eingerichtet
// der absolute Pfad wird ermittelt
// Verzeichnisse werden ggf. mit Slash beendet
source = Worker.fileCanonical(new File(target));
if (source != null) {
target = source.getPath().replace('\\', '/');
if (source.isDirectory() && !target.endsWith("/"))
target = target.concat("/");
}
}
if (source != null || virtual || connect) {
location = target;
options = rules;
reference = alias;
module = string.contains("[M]");
absolute = string.contains("[A]") && !module;
redirect = string.contains("[R]") && !module;
}
}
// der Zielpfad wird mit / abgeschlossen um auch Referenzen
// zwischen /a und /a/ ermitteln zu koennen
buffer = alias;
if (!absolute
&& !module
&& !buffer.endsWith("/")
&& buffer.length() > 0)
buffer = buffer.concat("/");
// die ACC-Eintraege zur Authentifizierung werden zusammengesammelt
if (string.contains("[ACC:")
&& locale.startsWith(buffer.toLowerCase())
&& buffer.length() > 0
&& shadow.length() <= buffer.length()) {
shadow = buffer;
access = rules.replaceAll("(?i)(\\[(((acc|realm):[^\\[\\]]*?)|d)\\])", "\00$1\01");
access = access.replaceAll("[^\01]+(\00|$)", "");
access = access.replaceAll("[\00\01]+", " ");
}
}
// die Referenz wird alternativ ermittelt
if (reference.length() <= 0) reference = path;
// konnte eine Referenz ermittelt werden wird diese geparst
if (reference.length() > 0) {
// die Location wird ermittelt und gesetzt
result = absolute || module ? location : location.concat(path.substring(Math.min(path.length(), reference.length())));
// die Option [A] und [M] wird fuer absolute Referenzen geprueft
if (absolute || module) {
string = path.substring(0, Math.min(path.length(), reference.length()));
this.environment.set("script_name", string);
this.environment.set("path_context", string);
this.environment.set("path_info", path.substring(string.length()));
}
// die Moduldefinition wird als Umgebungsvariablen gesetzt
if (module) result = options;
}
if (result.length() <= 0)
result = this.docroot.concat(this.environment.get("path_url"));
if (!module && absolute)
result = result.concat("[A]");
if (!module && forbidden)
result = result.concat("[C]");
if (!module && redirect)
result = result.concat("[R]");
result = result.concat(access);
return result;
}
/**
* Überprüft die Zugriffbrechtigungen für eine Referenz und
* setzt ggf. den entsprechenden Status.
* @param reference Referenz
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private void authorize(String reference)
throws Exception {
Section section;
String access;
String realm;
String shadow;
String buffer;
String string;
String target;
StringTokenizer tokenizer;
boolean control;
boolean digest;
string = reference.toLowerCase();
if (!string.contains("[acc:") || this.status >= 500)
return;
// optional wird die Bereichskennung ermittelt
realm = reference.replaceAll("^(.*(\\[\\s*(?i)realm:([^\\[\\]]*?)\\s*\\]).*)|.*$", "$3");
realm = realm.replace("\"", "\\\"");
this.fields.set("auth_realm", realm);
digest = string.contains("[d]");
// der Authentication-Type wird gesetzt
this.fields.set("auth_type", digest ? "Digest" : "Basic");
// die Werte der ACC-Optionen werden ermittelt
string = string.replaceAll("\\[acc:([^\\[\\]]*?)\\]", "\00$1\01");
string = string.replaceAll("((((^|\01).*?)\00)|(\01.*$))|(^.*$)", " ").trim();
control = false;
tokenizer = new StringTokenizer(string);
access = "";
// die ACC-Eintraege (Gruppen) werden aufgeloest
// mit der Option [ACC:NONE] wird die Authorisation aufgehoben
while (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken();
if (string.equals("none"))
return;
control = true;
access = access.concat(" ").concat(this.access.get(string));
}
access = access.trim();
if (access.length() <= 0) {
if (control)
this.status = 401;
return;
}
// die Autorisierung wird ermittelt
string = this.fields.get("http_authorization");
if (string.toLowerCase().startsWith("digest ")
&& digest) {
string = string.replaceAll("(\\w+)\\s*=\\s*(?:(?:\"(.*?)\")|([^,]*))", "\00$1=$2$3\n");
string = string.replaceAll("[^\n]+\00", "");
section = Section.parse(string, true);
target = section.get("response");
shadow = section.get("username");
buffer = shadow.concat(":").concat(realm).concat(":");
string = Worker.textHash(this.environment.get("request_method").concat(":").concat(section.get("uri")));
string = (":").concat(section.get("nonce")).concat(":").concat(section.get("nc")).concat(":").concat(section.get("cnonce")).concat(":").concat(section.get("qop")).concat(":").concat(string);
tokenizer = new StringTokenizer(access);
while (tokenizer.hasMoreTokens()) {
access = tokenizer.nextToken();
if (shadow.equals(access))
access = access.substring(shadow.length());
else if (access.startsWith(shadow.concat(":")))
access = access.substring(shadow.length() +1);
else continue;
access = Worker.textHash(buffer.concat(access));
access = Worker.textHash(access.concat(string));
if (target.equals(access)) {
this.fields.set("auth_user", shadow);
return;
}
}
} else if (string.toLowerCase().startsWith("basic ")
&& !digest) {
try {string = new String(Base64.getDecoder().decode(string.substring(6).getBytes())).trim();
} catch (Throwable throwable) {
string = "";
}
access = (" ").concat(access).concat(" ");
if (string.length() > 0
&& access.contains((" ").concat(string).concat(" "))) {
string = string.substring(0, Math.max(0, string.indexOf(':'))).trim();
this.fields.set("auth_user", string);
return;
}
}
this.status = 401;
}
/**
* Überprüft die Filter und wendet diese bei Bedarf an.
* Filter haben keinen direkten Rückgabewert, sie beieinflussen u.a.
* Server-Status und Datenflusskontrolle.
*/
private String filter()
throws Exception {
Enumeration enumeration;
File file;
String valueA;
String valueB;
String method;
String buffer;
String string;
String location;
StringTokenizer rules;
StringTokenizer words;
boolean control;
int cursor;
int status;
location = this.resource;
if (this.status == 400 || this.status >= 500)
return location;
// FILTER die Filter werden in den Vektor geladen
// die Steuerung erfolgt ueber REFERENCE, SCRIPT_URI und CODE
enumeration = this.filters.elements();
while (enumeration.hasMoreElements()) {
string = this.filters.get((String)enumeration.nextElement());
cursor = string.indexOf('>');
buffer = cursor >= 0 ? string.substring(cursor +1).trim() : "";
if (cursor >= 0)
string = string.substring(0, cursor);
// Die Auswertung der Filter erfolgt nach dem Auschlussprinzip.
// Dazu werden alle Regeln einer Zeile in einer Schleife einzeln
// geprueft und die Schleife mit der ersten nicht zutreffenden Regel
// verlassen. Somit wird das Ende der Schleife nur erreicht, wenn
// keine der Bedingungen versagt hat und damit alle zutreffen.
rules = new StringTokenizer(string, "[+]");
while (rules.hasMoreTokens()) {
// die Filterbeschreibung wird ermittelt
string = rules.nextToken().toLowerCase().trim();
words = new StringTokenizer(string);
// Methode und Bedingung muessen gesetzt sein
// mit Toleranz fuer [+] beim Konkatenieren leerer Bedingungen
if (words.countTokens() < 2)
continue;
// die Methode wird ermittelt
string = words.nextToken();
// die Methode wird auf Erfuellung geprueft
if (string.length() > 0 && !string.equals("all")
&& !string.equals(this.environment.get("request_method").toLowerCase()))
break;
// die Bedingung wird ermittelt
string = words.nextToken();
// die Pseudobedingung ALWAYS spricht immer an
if (!string.equals("always")) {
// die Filterkontrolle wird gesetzt, hierbei sind nur IS und
// NOT zulaessig, andere Werte sind nicht zulaessig
if (!string.equals("is") && !string.equals("not"))
break;
control = string.equals("is");
// Methode und Bedingung muessen gesetzt sein
if (words.countTokens() < 2)
break;
// Funktion und Parameter werden ermittelt
method = words.nextToken();
string = words.nextToken();
// der zu pruefende Wert wird ermittelt
string = this.environment.get(string);
valueA = string.toLowerCase();
valueB = Worker.textDecode(valueA);
// der zu pruefende Wert/Ausdruck wird ermittelt
string = words.hasMoreTokens() ? words.nextToken() : "";
if ((method.equals("starts")
&& control != (valueA.startsWith(string)
|| valueB.startsWith(string)))
|| (method.equals("contains")
&& control != (valueA.contains(string)
|| valueB.contains(string)))
|| (method.equals("equals")
&& control != (valueA.equals(string)
|| valueB.equals(string)))
|| (method.equals("ends")
&& control != (valueA.endsWith(string)
|| valueB.endsWith(string)))
|| (method.equals("match")
&& control != (valueA.matches(string)
|| valueB.matches(string)))
|| (method.equals("empty")
&& control != (valueA.length() <= 0)))
break;
if (rules.hasMoreTokens())
continue;
}
// die Anweisung wird ermittelt
string = Worker.cleanOptions(buffer);
// wurde ein Modul definiert, wird es optional im Hintergrund
// als Filter- oder Process-Modul ausgefuehrt, die Verarbeitung
// endet erst, wenn das Modul die Datenflusskontrolle veraendert
if (buffer.toUpperCase().contains("[M]") && string.length() > 0) {
control = this.control;
status = this.status;
this.environment.set("module_opts", buffer);
this.invoke(string, "filter");
if (this.control != control
|| this.status != status)
return this.resource;
continue;
}
// bei einer Weiterleitung (Redirect) wird STATUS 302 gesetzt
if (buffer.toUpperCase().contains("[R]") && string.length() > 0) {
this.environment.set("script_uri", string);
this.status = 302;
return location;
}
// Verweise auf Dateien oder Verzeichnisse werden diese als
// Location zurueckgegeben
if (string.length() > 0) {
file = Worker.fileCanonical(new File(buffer));
if (file != null && file.exists())
return file.getPath();
}
// sprechen alle Bedingungen an und es gibt keine spezielle
// Anweisung, wird der STATUS 403 gesetzt
this.status = 403;
return location;
}
}
return location;
}
/**
* Initialisiert die Connection, liest den Request, analysiert diesen und
* richtet die Connection in der Laufzeitumgebung entsprechen ein.
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private void initiate()
throws Exception {
ByteArrayOutputStream buffer;
Enumeration enumeration;
File file;
String entry;
String method;
String shadow;
String string;
StringTokenizer tokenizer;
Section section;
boolean connect;
boolean secure;
boolean virtual;
int count;
int cursor;
int digit;
int offset;
// der Datenpuffer wird zum Auslesen vom Header eingerichtet
buffer = new ByteArrayOutputStream(65535);
if ((this.accept instanceof SSLSocket))
try {this.fields.set("auth_cert", ((SSLSocket)this.accept).getSession().getPeerPrincipal().getName());
} catch (Throwable throwable) {
}
try {
// das SO-Timeout wird fuer den ServerSocket gesetzt
this.accept.setSoTimeout((int)this.timeout);
// die Datenstroeme werden eingerichtet
this.output = this.accept.getOutputStream();
this.input = this.accept.getInputStream();
// der Inputstream wird gepuffert
this.input = new BufferedInputStream(this.input, this.blocksize);
count = cursor = offset = 0;
// der Header vom Requests wird gelesen, tritt beim Zugriff auf die
// Datenstroeme ein Fehler auf, wird STATUS 400 gesetzt
while (true) {
if ((digit = this.input.read()) >= 0) {
// der Request wird auf kompletten Header geprueft
cursor = (digit == ((cursor % 2) == 0 ? 13 : 10)) ? cursor +1 : 0;
if (cursor > 0 && count > 0 && offset > 0 && buffer.size() > 0) {
string = new String(buffer.toByteArray(), offset, buffer.size() -offset);
offset = string.indexOf(':');
shadow = string.substring(offset < 0 ? string.length() : offset +1).trim();
string = string.substring(0, offset < 0 ? string.length() : offset).trim();
// entsprechend RFC 3875 (CGI/1.1-Spezifikation) werden
// alle Felder vom HTTP-Header als HTTP-Parameter zur
// Verfuegung gestellt, dazu wird das Zeichen - durch _
// ersetzt und allen Parametern das Praefix "http_"
// vorangestellt
string = ("http_").concat(string.replace('-', '_'));
if (!this.fields.contains(string)
&& string.length() > 0
&& shadow.length() > 0)
this.fields.set(string, shadow);
offset = buffer.size();
}
// die Feldlaenge wird berechnet
count = cursor > 0 ? 0 : count +1;
if (count == 1) offset = buffer.size();
// die Zeile eines Felds vom Header muss sich mit 8-Bit
// addressieren lassen (fehlende Regelung im RFC 1945/2616)
if (count > 32768) this.status = 413;
// die Daten werden gespeichert
buffer.write(digit);
// der Header des Request wird auf 65535 Bytes begrenzt
if (buffer.size() >= 65535
&& cursor < 4) {
this.status = 413;
break;
}
// der Request wird auf kompletter Header geprueft
if (cursor == 4)
break;
} else {
// der Datenstrom wird auf Ende geprueft
if (digit >= 0)
Thread.sleep(this.interrupt);
else break;
}
}
} catch (Throwable throwable) {
this.status = 400;
if (throwable instanceof SocketTimeoutException)
this.status = 408;
}
// der Header wird vorrangig fuer die Schnittstellen gesetzt
this.header = buffer.toString().trim();
// die zusaetzlichen Header-Felder werden vorrangig fuer Filter
// ermittelt und sind nicht Bestandteil vom (X)CGI, dafuer werden nur
// die relevanten Parameter wie Methode, Pfade und Query uebernommen
// die erste Zeile wird ermittelt
tokenizer = new StringTokenizer(this.header, "\r\n");
string = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : "";
this.fields.set("req_line", string);
// die Methode vom Request wird ermittelt
offset = string.indexOf(' ');
shadow = string.substring(0, offset < 0 ? string.length() : offset);
string = string.substring(offset < 0 ? string.length() : offset +1);
this.fields.set("req_method", shadow);
// ohne HTTP-Methode ist die Anfrage ungueltig, somit STATUS 400
if (this.status == 0
&& shadow.length() <= 0)
this.status = 400;
// Protokoll und Version vom Request werden ermittelt aber ignoriert
offset = string.lastIndexOf(' ');
string = string.substring(0, offset < 0 ? string.length() : offset);
// Pfad und Query vom Request werden ermittelt
offset = string.indexOf(' ');
string = string.substring(0, offset < 0 ? string.length() : offset);
this.fields.set("req_path", string);
// Pfad und Query vom Request werden ermittelt
offset = string.indexOf('?');
shadow = string.substring(offset < 0 ? string.length() : offset +1);
string = string.substring(0, offset < 0 ? string.length() : offset);
this.fields.set("req_query", shadow);
this.fields.set("req_uri", string);
// der Pfad wird dekodiert
shadow = Worker.textDecode(string);
// der Pfad wird ausgeglichen /abc/./def/../ghi/ -> /abc/ghi
string = Worker.fileNormalize(shadow);
if (shadow.endsWith("/") && !string.endsWith("/"))
string = string.concat("/");
this.fields.set("req_path", string);
// ist der Request nicht korrekt wird STATUS 400 gesetzt
// enthaelt der Request keinen Header wird STATUS 400 gesetzt
// enthaelt der Request kein gueltige Pfadangabe wird STATUS 400 gesetzt
if (this.status == 0
&& (!string.startsWith("/")
|| this.header.length() <= 0))
this.status = 400;
// der Host wird ohne Port ermittelt und verwendet
string = this.fields.get("http_host");
offset = string.indexOf(':');
string = string.substring(0, offset < 0 ? string.length() : offset);
while (string.endsWith("."))
string = string.substring(0, string.length() -1);
// ist kein Host im Request, wird die aktuelle Adresse verwendet
if (string.length() <= 0)
string = this.accept.getLocalAddress().getHostAddress();
this.fields.set("http_host", string);
// der Host wird zur Virtualisierung ermittelt
if (string.length() > 0) {
string = ("virtual:").concat(string);
section = this.initialize.get(string.concat(":ini"));
shadow = section.get("server").toLowerCase();
// die Optionen werden mit allen Vererbungen ermittelt bzw.
// erweitert wenn ein virtueller Host fuer den Server existiert
if ((" ").concat(shadow).concat(" ").contains((" ").concat(this.context.toLowerCase()).concat(" "))
|| shadow.length() <= 0) {
this.options.merge(section);
this.references.merge(this.initialize.get(string.concat(":ref")));
this.access.merge(this.initialize.get(string.concat(":acc")));
this.filters.merge(this.initialize.get(string.concat(":flt")));
this.environment.merge(this.initialize.get(string.concat(":env")));
this.interfaces.merge(this.initialize.get(string.concat(":cgi")));
}
// die zu verwendende Blockgroesse wird ermittelt
try {this.blocksize = Integer.parseInt(this.options.get("blocksize"));
} catch (Throwable throwable) {
this.blocksize = 65535;
}
if (this.blocksize <= 0)
this.blocksize = 65535;
string = this.options.get("timeout");
this.isolation = string.toUpperCase().contains("[S]") ? -1 : 0;
// das Timeout der Connection wird ermittelt
try {this.timeout = Long.parseLong(Worker.cleanOptions(string));
} catch (Throwable throwable) {
this.timeout = 0;
}
}
// das aktuelle Arbeitsverzeichnis wird ermittelt
file = Worker.fileCanonical(new File("."));
string = file != null ? file.getPath().replace('\\', '/') : ".";
if (string.endsWith("/"))
string = string.substring(0, string.length() -1);
// das Systemverzeichnis wird ermittelt
file = Worker.fileCanonical(new File(this.options.get("sysroot")));
this.sysroot = file != null ? file.getPath().replace('\\', '/') : string;
if (this.sysroot.endsWith("/"))
this.sysroot = this.sysroot.substring(0, this.sysroot.length() -1);
if (this.options.get("sysroot").length() <= 0)
this.sysroot = string;
// das Dokumentenverzeichnis wird ermittelt
file = Worker.fileCanonical(new File(this.options.get("docroot")));
this.docroot = file != null ? file.getPath().replace('\\', '/') : string;
if (this.docroot.endsWith("/"))
this.docroot = this.docroot.substring(0, this.docroot.length() -1);
if (this.options.get("docroot").length() <= 0)
this.docroot = string;
// die serverseitig festen Umgebungsvariablen werden gesetzt
this.environment.set("server_port", String.valueOf(this.accept.getLocalPort()));
this.environment.set("server_protocol", "HTTP/1.0");
this.environment.set("server_software", "Seanox-Devwex/#[ant:release-version] #[ant:release-date]");
this.environment.set("document_root", this.docroot);
// die Requestspezifischen Umgebungsvariablen werden gesetzt
this.environment.set("content_length", this.fields.get("http_content_length"));
this.environment.set("content_type", this.fields.get("http_content_type"));
this.environment.set("query_string", this.fields.get("req_query"));
this.environment.set("request", this.fields.get("req_line"));
this.environment.set("request_method", this.fields.get("req_method"));
this.environment.set("remote_addr", this.accept.getInetAddress().getHostAddress());
this.environment.set("remote_port", String.valueOf(this.accept.getPort()));
// die Unique-Id wird aus dem HashCode des Sockets, den Millisekunden
// sowie der verwendeten Portnummer ermittelt, die Laenge ist variabel
string = Long.toString(Math.abs(this.accept.hashCode()), 36);
string = string.concat(Long.toString(((Math.abs(System.currentTimeMillis()) *100000) +this.accept.getPort()), 36));
// die eindeutige Request-Id wird gesetzt
this.environment.set("unique_id", string.toUpperCase());
// der Path wird ermittelt
shadow = this.fields.get("req_path");
// die Umgebungsvariabeln werden entsprechend der Ressource gesetzt
this.environment.set("path_url", shadow);
this.environment.set("script_name", shadow);
this.environment.set("script_url", this.fields.get("req_uri"));
this.environment.set("path_context", "");
this.environment.set("path_info", "");
// REFERRENCE - Zur Ressource werden ggf. der virtuellen Pfad im Unix
// Fileformat (Slash) bzw. der reale Pfad, sowie optionale Parameter,
// Optionen und Verweise auf eine Authentication ermittelt.
this.resource = this.locate(shadow);
// Option [A] fuer eine absolute Referenz wird ermittelt
string = this.resource.toUpperCase();
digit = string.contains("[A]") ? 1 : 0;
digit |= string.contains("[M]") ? 2 : 0;
digit |= string.contains("[R]") ? 4 : 0;
digit |= string.contains("[C]") ? 8 : 0;
digit |= string.contains("[X]") ? 16 : 0;
virtual = (digit & 1) != 0;
connect = (digit & (2|4)) != 0;
// HINWEIS - Auch Module koennen die Option [R] besitzen, diese wird
// dann aber ignoriert, da die Weiterleitung zu Modulen nur ueber deren
// virtuellen Pfad erfolgt
if ((this.status == 0 || this.status == 404) && (digit & 8) != 0) this.status = 403;
if ((this.status == 0 || this.status == 404) && (digit & 2) != 0) this.status = 0;
if ((this.status == 0 || this.status == 404) && (digit & (2|4)) == 4) {
this.environment.set("script_uri", Worker.cleanOptions(this.resource));
this.status = 302;
}
// ggf. wird die Zugriffsbrechtigung geprueft
// unterstuetzt werden Basic- und Digest-Authentication
this.authorize(this.resource);
// die Request-Parameter (nur mit dem Praefix http_ und auth_) werden in
// die Umgebungsvariablen uebernommen
enumeration = this.fields.elements();
while (enumeration.hasMoreElements()) {
string = (String)enumeration.nextElement();
if (!string.startsWith("HTTP_")
&& !string.startsWith("AUTH_") )
continue;
this.environment.set(string, this.fields.get(string));
}
this.environment.set("remote_user", this.fields.get("auth_user"));
if (!connect)
this.resource = Worker.cleanOptions(this.resource);
if (this.resource.length() <= 0)
this.resource = this.docroot.concat(this.environment.get("path_url"));
// die Ressource wird als File eingerichtet
file = new File(this.resource);
// die Ressource wird syntaktisch geprueft, nicht real existierende
// Ressourcen sowie Abweichungen im kanonisch Pfad werden mit Status
// 404 quitiert (das schliesst die Bugs im Windows-Dateisystem / / und
// Punkt vorm Slash ein), die Gross- und Kleinschreibung wird in Windows
// ignoriert
if (!connect
&& this.status == 0) {
File canonical = Worker.fileCanonical(file);
if (!file.equals(canonical))
this.status = 404;
if (canonical != null)
file = canonical;
if (file.isDirectory()
&& file.list() == null)
this.status = 404;
this.resource = file.getPath();
}
if (file.isFile() && shadow.endsWith("/"))
shadow = shadow.substring(0, shadow.length() -1);
if (file.isDirectory() && !shadow.endsWith("/"))
shadow = shadow.concat("/");
// der HOST oder VIRTUAL HOST wird ermittelt
entry = this.fields.get("http_host");
if (entry.length() <= 0)
entry = this.accept.getLocalAddress().getHostAddress();
// die OPTION IDENTITY wird geprueft
if (this.options.get("identity").toLowerCase().equals("on"))
this.environment.set("server_name", entry);
// aus dem Schema wird die Verwendung vom Secure-Layer ermittelt
secure = this.socket instanceof javax.net.ssl.SSLServerSocket;
// die Location wird zusammengestellt
string = this.environment.get("server_port");
string = (!string.equals("80") && !secure || !string.equals("443") && secure) && string.length() > 0 ? (":").concat(string) : "";
string = (secure ? "https" : "http").concat("://").concat(entry).concat(string);
// die URI vom Skript wird komplementiert
if (this.status != 302)
this.environment.set("script_uri", string.concat(this.fields.get("req_path")));
// bei abweichendem Path wird die Location als Redirect eingerichtet
if (this.status == 0 && !this.environment.get("path_url").equals(shadow) && !virtual && !connect) {
this.environment.set("script_uri", string.concat(shadow));
this.status = 302;
}
// die aktuelle Referenz wird ermittelt
string = this.environment.get("script_uri");
string = Worker.fileNormalize(string);
// bezieht sich die Referenz auf ein Verzeichnis und der URI endet
// aber nicht auf "/" wird STATUS 302 gesetzt
if (file.isDirectory() && !string.endsWith("/")) {
this.environment.set("script_uri", string.concat("/"));
if (this.status == 0)
this.status = 302;
}
// DEFAULT, beim Aufruf von Verzeichnissen wird nach einer alternativ
// anzuzeigenden Datei gesucht, was intern wie ein Verweis funktioniert
if (file.isDirectory() && this.status == 0) {
// das Verzeichnis wird mit Slash abgeschlossen
if (!this.resource.endsWith("/"))
this.resource = this.resource.concat("/");
// die Defaultdateien werden ermittelt
tokenizer = new StringTokenizer(this.options.get("default").replace('\\', '/'));
while (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken();
if (string.length() <= 0
|| string.indexOf('/') >= 0
|| !new File(this.resource.concat(string)).isFile())
continue;
this.resource = this.resource.concat(string);
shadow = this.environment.get("path_context");
if (shadow.length() <= 0)
shadow = this.environment.get("path_url");
if (!shadow.endsWith("/"))
shadow = shadow.concat("/");
this.environment.set("script_name", shadow.concat(string));
break;
}
}
string = Worker.cleanOptions(this.resource);
this.environment.set("script_filename", string);
this.environment.set("path_translated", string);
// der Query String wird ermittelt
string = this.environment.get("query_string");
// der Query String wird die Request URI aufbereite
if (string.length() > 0) string = ("?").concat(string);
// die Request URI wird gesetzt
this.environment.set("request_uri", this.fields.get("req_uri").concat(string));
// die aktuelle HTTP-Methode wird ermittelt
string = this.environment.get("request_method").toLowerCase();
// METHODS, die zulaessigen Methoden werden ermittelt
shadow = (" ").concat(this.options.get("methods").toLowerCase()).concat(" ");
// die aktuelle Methode wird in der Liste der zulaessigen gesucht, ist
// nicht enthalten, wird STATUS 405 gesetzt, ausgenommen sind Module
// mit der Option [X], da an diese alle Methoden weitergereicht werden
if (((digit & (2 | 16)) != (2 | 16))
&& !shadow.contains((" ").concat(string).concat(" "))
&& this.status <= 0)
this.status = 405;
this.resource = this.filter();
string = Worker.cleanOptions(this.resource);
this.environment.set("script_filename", string);
this.environment.set("path_translated", string);
// handelt es sich bei der Ressource um ein Modul wird keine Zuweisung
// fuer das (X)CGI und den Mediatype vorgenommen
if (connect || this.resource.toUpperCase().contains("[M]")) {
this.mediatype = this.options.get("mediatype");
this.gateway = this.resource;
return;
}
if (this.status == 302)
return;
// die Dateierweiterung wird ermittelt
cursor = this.resource.lastIndexOf(".");
entry = cursor >= 0 ? this.resource.substring(cursor +1) : this.resource;
// CGI - zur Dateierweiterung wird ggf. eine Anwendung ermittelt
this.gateway = this.interfaces.get(entry);
if (this.gateway.length() > 0) {
cursor = this.gateway.indexOf('>');
// die zulaessigen Methoden werden ermittelt
method = this.gateway.substring(0, Math.max(0, cursor)).toLowerCase().trim();
// die eigentliche Anwendung ermittelt
if (cursor >= 0) this.gateway = this.gateway.substring(cursor +2).trim();
// die Variable GATEWAY-INTERFACE wird fuer das (X)CGI gesetzt
if (this.gateway.length() > 0) {
this.environment.set("gateway_interface", "CGI/1.1");
// die Methode wird geprueft, ob diese fuer das CGI zugelassen
// ist, wenn nicht zulaessig, wird STATUS 405 gesetzt
string = (" ").concat(this.environment.get("request_method")).concat(" ").toLowerCase();
shadow = (" ").concat(method).concat(" ");
if (method.length() > 0
&& !shadow.contains(string)
&& !shadow.contains(" all ")
&& this.status < 500
&& this.status != 302)
this.status = 405;
}
}
// der Mediatype wird ermittelt
this.mediatype = this.mediatypes.get(entry);
// kann dieser nicht festgelegt werden wird der Standardeintrag aus den
// Server Basisoptionen eingetragen
if (this.mediatype.length() <= 0) this.mediatype = this.options.get("mediatype");
// die vom Client unterstuetzten Mediatypes werden ermittelt
shadow = this.fields.get("http_accept");
if (shadow.length() > 0) {
// es wird geprueft ob der Client den Mediatype unterstuetzt,
// ist dies nicht der Fall, wird STATUS 406 gesetzt
tokenizer = new StringTokenizer(shadow.toLowerCase().replace(';', ','), ",");
while (this.status == 0) {
if (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken().trim();
if (string.equals(this.mediatype) || string.equals("*/*") || string.equals("*"))
break;
cursor = this.mediatype.indexOf("/");
if (cursor >= 0 && (string.equals(this.mediatype.substring(0, cursor +1).concat("*"))
|| string.equals(("*").concat(this.mediatype.substring(cursor)))))
break;
} else this.status = 406;
}
}
}
/**
* Erstellt den Basis-Header für einen Response und erweitert diesen um
* die optional übergebenen Parameter.
* @param status HTTP-Status
* @param header optionale Liste mit Parameter
* @return der erstellte Response-Header
*/
private String header(int status, String[] header) {
String string;
string = String.valueOf(status);
string = ("HTTP/1.0 ").concat(string).concat(" ").concat(Worker.cleanOptions(this.statuscodes.get(string))).trim();
if (this.options.get("identity").toLowerCase().equals("on"))
string = string.concat("\r\nServer: Seanox-Devwex/#[ant:release-version] #[ant:release-date]");
string = string.concat("\r\n").concat(Worker.dateFormat("'Date: 'E, dd MMM yyyy HH:mm:ss z", new Date(), "GMT"));
string = string.concat("\r\n").concat(String.join("\r\n", header));
return string.trim();
}
/**
* Erstellt ein Array mit den Umgebungsvariablen.
* Umgebungsvariablen ohne Wert werden nicht übernommen.
* @return die Umgebungsvariablen als Array
*/
private String[] getEnvironment() {
Enumeration enumeration;
List list;
StringTokenizer tokenizer;
String label;
String value;
int index;
list = new ArrayList();
// die Umgebungsvariablen werden ermittelt und uebernommen
enumeration = this.environment.elements();
while (enumeration.hasMoreElements()) {
label = (String)enumeration.nextElement();
value = this.environment.get(label);
if (value.length() <= 0)
continue;
value = label.concat("=").concat(value);
if (list.contains(value))
continue;
list.add(value);
}
// die Zeilen vom Header werden ermittelt
tokenizer = new StringTokenizer(this.header, "\r\n");
// die erste Zeile mit dem Request wird verworfen
if (tokenizer.hasMoreTokens())
tokenizer.nextToken();
while (tokenizer.hasMoreTokens()) {
value = tokenizer.nextToken();
index = value.indexOf(':');
if (index <= 0)
continue;
label = value.substring(0, index).trim();
value = value.substring(index +1).trim();
if (label.length() <= 0
|| value.length() <= 0)
continue;
label = ("http_").concat(label.replace('-', '_'));
value = label.toUpperCase().concat("=").concat(value);
if (list.contains(value))
continue;
list.add(value);
}
return (String[])list.toArray(new String[0]);
}
private void doGateway()
throws Exception {
InputStream error;
InputStream input;
OutputStream output;
Process process;
String shadow;
String header;
String string;
String[] environment;
byte[] bytes;
int cursor;
int length;
int offset;
long duration;
long size;
if (this.gateway.toUpperCase().contains("[M]")) {
// die Moduldefinition wird als Umgebungsvariablen gesetzt
this.environment.set("module_opts", this.gateway);
this.invoke(Worker.cleanOptions(this.gateway), "service");
return;
}
string = this.gateway;
shadow = this.environment.get("script_filename");
cursor = shadow.replace('\\', '/').lastIndexOf("/") +1;
string = string.replace("[d]", "[D]");
string = string.replace("[D]", shadow.substring(0, cursor));
string = string.replace("[c]", "[C]");
string = string.replace("[C]", shadow.replace((File.separator.equals("/")) ? '\\' : '/', File.separatorChar));
shadow = shadow.substring(cursor);
cursor = shadow.lastIndexOf(".");
string = string.replace("[n]", "[N]");
string = string.replace("[N]", shadow.substring(0, cursor < 0 ? shadow.length() : cursor));
string = Worker.cleanOptions(string);
// die maximale Prozesslaufzeit wird ermittelt
try {duration = Long.parseLong(this.options.get("duration"));
} catch (Throwable throwable) {
duration = 0;
}
// der zeitliche Verfall des Prozess wird ermittelt
if (duration > 0)
duration += System.currentTimeMillis();
// der Datenpuffer wird entsprechen der BLOCKSIZE eingerichtet
bytes = new byte[this.blocksize];
// initiale Einrichtung der Variablen
environment = this.getEnvironment();
// der Prozess wird gestartet, Daten werden soweit ausgelesen
// bis der Prozess beendet wird oder ein Fehler auftritt
process = Runtime.getRuntime().exec(string.trim(), environment);
try {
input = process.getInputStream();
output = process.getOutputStream();
// der XCGI-Header wird aus den CGI-Umgebungsvariablen
// erstellt und vergleichbar dem Header ins StdIO geschrieben
if (this.gateway.toUpperCase().contains("[X]"))
output.write(String.join("\r\n", environment).trim().concat("\r\n\r\n").getBytes());
// die Laenge des Contents wird ermittelt
try {length = Integer.parseInt(this.fields.get("http_content_length"));
} catch (Throwable throwable) {
length = 0;
}
while (length > 0) {
// die Daten werden aus dem Datenstrom gelesen
size = this.input.read(bytes);
if (size < 0)
break;
// die an das CGI zu uebermittelnde Datenmenge wird auf die
// Menge von CONTENT-LENGHT begrenzt
if (size > length)
size = length;
// die Daten werden an das CGI uebergeben
output.write(bytes, 0, (int)size);
// das verbleibende Datenvolumen wird berechnet
length -= size;
// die maximale Prozesslaufzeit wird geprueft
if (duration > 0
&& duration < System.currentTimeMillis()) {
this.status = 504;
break;
}
Thread.sleep(this.interrupt);
}
// der Datenstrom wird geschlossen
if (process.isAlive())
output.close();
// der Prozess wird zwangsweise beendet um auch die Prozesse
// abzubrechen deren Verarbeitung fehlerhaft verlief
if (this.status != 200)
return;
// der Datenpuffer fuer den wird eingerichtet
header = new String();
// Responsedaten werden bis zum Ende der Anwendung gelesen
// dazu wird initial die Datenflusskontrolle gesetzt
while (true) {
// das Beenden der Connection wird geprueft
try {this.accept.getSoTimeout();
} catch (Throwable throwable) {
this.status = 503;
break;
}
if (input.available() > 0) {
// die Daten werden aus dem StdIO gelesen
length = input.read(bytes);
offset = 0;
// fuer die Analyse vom Header wird nur die erste Zeile
// vom CGI-Output ausgewertet, der Header selbst wird
// vom Server nicht geprueft oder manipuliert, lediglich
// die erste Zeile wird HTTP-konform aufbereitet
if (this.control && header != null) {
header = header.concat(new String(bytes, 0, length));
cursor = header.indexOf("\r\n\r\n");
if (cursor >= 0) {
offset = length -(header.length() -cursor -4);
header = header.substring(0, cursor);
} else offset = header.length();
// der Buffer zur Header-Analyse ist auf 65535 Bytes
// begrenzt, Ueberschreiten fuehrt zum STATUS 502
if (header.length() > 65535) {
this.status = 502;
break;
} else if (cursor >= 0) {
header = header.trim();
cursor = header.indexOf("\r\n");
string = cursor >= 0 ? header.substring(0, cursor).trim() : header;
shadow = string.toUpperCase();
if (shadow.startsWith("HTTP/")) {
if (shadow.matches("^HTTP/STATUS(\\s.*)*$"))
header = null;
try {this.status = Math.abs(Integer.parseInt(string.replaceAll("^(\\S+)\\s*(\\S+)*\\s*(.*?)\\s*$", "$2")));
} catch (Throwable throwable) {
}
// ggf. werden die Statuscodes mit eigenen bzw.
// unbekannten Codes und Text temporaer
// angereichert, mit dem Ende der Connection wird
// die Liste verworfen
string = string.replaceAll("^(\\S+)\\s*(\\S+)*\\s*(.*?)\\s*$", "$3");
if (string.length() > 0
&& !this.statuscodes.contains(String.valueOf(this.status)))
this.statuscodes.set(String.valueOf(this.status), string);
}
// beginnt der Response mit HTTP/STATUS, wird der
// Datenstrom ausgelesen, nicht aber an den Client
// weitergeleitet, die Beantwortung vom Request
// uebernimmt in diesem Fall der Server
if (header != null) {
header = header.replaceAll("(?si)^ *HTTP */ *[^\r\n]*([\r\n]+|$)", "");
header = this.header(this.status, header.split("[\r\n]+"));
this.control = false;
}
}
}
// die Daten werden nur in den Output geschrieben, wenn die
// Ausgabekontrolle gesetzt wurde und der Response nicht mit
// HTTP/STATUS beginnt
if (!this.control) {
// der Zeitpunkt wird registriert, um auf blockierte
// Datenstroeme reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
if (header != null)
this.output.write(header.concat("\r\n\r\n").getBytes());
header = null;
this.output.write(bytes, offset, length -offset);
if (this.isolation != 0)
this.isolation = -1;
this.volume += length -offset;
}
}
// die maximale Prozesslaufzeit wird geprueft
if (duration > 0
&& duration < System.currentTimeMillis()) {
this.status = 504;
break;
}
// der Datenstrom wird auf vorliegende Daten
// und der Prozess wird auf sein Ende geprueft
if (input.available() <= 0
&& !process.isAlive())
break;
Thread.sleep(this.interrupt);
}
} finally {
try {
string = new String();
error = process.getErrorStream();
while (error.available() > 0) {
length = error.read(bytes);
string = string.concat(new String(bytes, 0, length));
}
string = string.trim();
if (string.length() > 0)
Service.print(("GATEWAY ").concat(string));
} finally {
// der Prozess wird zwangsweise beendet um auch die Prozesse
// abzubrechen deren Verarbeitung fehlerhaft verlief
try {process.destroy();
} catch (Throwable throwable) {
}
}
}
}
/**
* Erstellt vom angeforderten Verzeichnisse auf Basis vom Template
* {@code index.html} eine navigierbare HTML-Seite.
* @param directory Verzeichnis des Dateisystems
* @param query Option der Sortierung
* @return das Verzeichnisse als navigierbares HTML
*/
private byte[] createDirectoryIndex(File directory, String query) {
Enumeration enumeration;
File file;
Generator generator;
Hashtable data;
Hashtable values;
List list;
List storage;
StringTokenizer tokenizer;
String entry;
String path;
String string;
File[] files;
String[] entries;
int[] assign;
boolean control;
boolean reverse;
int cursor;
int digit;
int loop;
values = new Hashtable();
// der Header wird mit den Umgebungsvariablen zusammengefasst,
// die serverseitig gesetzten haben dabei die hoehere Prioritaet
enumeration = this.environment.elements();
while (enumeration.hasMoreElements()) {
entry = (String)enumeration.nextElement();
if (entry.toLowerCase().equals("path")
|| entry.toLowerCase().equals("file"))
continue;
values.put(entry, this.environment.get(entry));
}
// die Zuordung der Felder fuer die Sortierung wird definiert
if (query.length() <= 0)
query = "n";
query = query.substring(0, 1);
digit = query.charAt(0);
reverse = digit >= 'A' && digit <= 'Z';
query = query.toLowerCase();
digit = query.charAt(0);
// case, name, date, size, type
assign = new int[] {0, 1, 2, 3, 4};
// die Sortierung wird durch die Query festgelegt und erfolgt nach
// Case, Query und Name, die Eintraege sind als Array abgelegt um eine
// einfache und flexible Zuordnung der Sortierreihenfolge zu erreichen
// 0 - case, 1 - name, 3 - date, 4 - size, 5 - type
if (digit == 'd') {
// case, date, name, size, type
assign = new int[] {0, 2, 1, 3, 4};
} else if (digit == 's') {
// case, size, name, date, type
assign = new int[] {0, 3, 1, 2, 4};
} else if (digit == 't') {
// case, type, name, date, size
assign = new int[] {0, 4, 1, 2, 3};
} else query = "n";
// das Standard-Template fuer den INDEX wird ermittelt und geladen
file = new File(this.sysroot.concat("/index.html"));
generator = Generator.parse(Worker.fileRead(file));
string = this.environment.get("path_url");
if (!string.endsWith("/"))
string = string.concat("/");
values.put("path_url", string);
// der Pfad wird fragmentiert, Verzeichnissstruktur koennen so als
// einzelne Links abgebildet werden
tokenizer = new StringTokenizer(string, "/");
for (path = ""; tokenizer.hasMoreTokens();) {
entry = tokenizer.nextToken();
path = path.concat("/").concat(entry);
values.put("path", path);
values.put("name", entry);
generator.set("location", values);
}
// die Dateiliste wird ermittelt
files = directory.listFiles();
if (files == null)
files = new File[0];
storage = new ArrayList(Arrays.asList(files));
// mit der Option [S] werden versteckte Dateien nicht angezeigt
control = this.options.get("index").toUpperCase().contains("[S]");
entries = new String[5];
// die Dateiinformationen werden zusammengestellt
for (loop = 0; loop < storage.size(); loop++) {
// die physiche Datei wird ermittlet
file = (File)storage.get(loop);
// die Eintraege werden als Array abgelegt um eine einfache und
// flexible Zuordnung der Sortierreihenfolge zu erreichen
// 0 - base, 1 - name, 2 - date, 3 - size, 4 - type
// der Basistyp wird ermittelt
entries[0] = file.isDirectory() ? "directory" : "file";
// der Name wird ermittelt
entries[1] = file.getName();
// der Zeitpunkt der letzten Aenderung wird ermittelt
entries[2] = String.format("%tF %<tT", new Date(file.lastModified()));
// die Groesse wird ermittelt, nicht aber bei Verzeichnissen
string = file.isDirectory() ? "-" : String.valueOf(file.length());
// die Groesse wird an der ersten Stelle mit dem Character erweitert
// welches sich aus der Laenge der Groesse ergibt um diese nach
// numerischer Groesse zu sortieren
entries[3] = String.valueOf((char)string.length()).concat(string);
// der Dateityp wird ermittlet, nicht aber bei Verzeichnissen
string = entries[1];
cursor = string.lastIndexOf(".");
string = cursor >= 0 ? string.substring(cursor +1) : "";
entries[4] = file.isDirectory() ? "-" : string.toLowerCase().trim();
// Dateien und Verzeichnisse der Option "versteckt" werden markiert
string = String.join("\00 ", new String[] {entries[assign[0]], entries[assign[1]],
entries[assign[2]], entries[assign[3]], entries[assign[4]]});
if (control && file.isHidden())
string = "";
storage.set(loop, string);
}
// die Dateiliste wird sortiert
Collections.sort(storage, String.CASE_INSENSITIVE_ORDER);
if (reverse)
Collections.reverse(storage);
list = new ArrayList();
// die Dateiinformationen werden zusammengestellt
for (loop = 0; loop < storage.size(); loop++) {
// nicht anerkannte Dateien werden unterdrueckt
tokenizer = new StringTokenizer((String)storage.get(loop), "\00");
if (tokenizer.countTokens() <= 0)
continue;
data = new Hashtable(values);
list.add(data);
// die Eintraege werden als Array abgelegt um eine einfache und
// flexible Zuordnung der Sortierreihenfolge zu erreichen
// 0 - base, 1 - name, 2 - date, 3 - size, 4 - type
entries[assign[0]] = tokenizer.nextToken();
entries[assign[1]] = tokenizer.nextToken().substring(1);
entries[assign[2]] = tokenizer.nextToken().substring(1);
entries[assign[3]] = tokenizer.nextToken().substring(1);
entries[assign[4]] = tokenizer.nextToken().substring(1);
data.put("case", entries[0]);
data.put("name", entries[1]);
data.put("date", entries[2]);
data.put("size", entries[3].substring(1));
data.put("type", entries[4]);
string = entries[4];
if (!string.equals("-")) {
string = this.mediatypes.get(string);
if (string.length() <= 0)
string = this.options.get("mediatype");
} else string = "";
data.put("mime", string);
}
query = query.concat(reverse ? "d" : "a");
if (list.size() <= 0)
query = query.concat(" x");
values.put("sort", query);
values.put("file", list);
generator.set(values);
return generator.extract();
}
private void doGet()
throws Exception {
File file;
InputStream input;
List header;
StringTokenizer tokenizer;
String method;
String string;
byte[] bytes;
long size;
long offset;
long limit;
header = new ArrayList();
// die Methode wird ermittelt
method = this.fields.get("req_method").toLowerCase();
// die Ressource wird eingerichtet
file = new File(this.resource);
if (file.isDirectory()) {
// die Option INDEX ON wird ueberprueft
// bei Verzeichnissen und der INDEX OFF wird STATUS 403 gesetzt
if (Worker.cleanOptions(this.options.get("index")).toLowerCase().equals("on")) {
header.add(("Content-Type: ").concat(this.mediatypes.get("html")));
bytes = new byte[0];
// die Verzeichnisstruktur wird bei METHOD:GET generiert
if (method.equals("get")) {
bytes = this.createDirectoryIndex(file, this.environment.get("query_string"));
header.add(("Content-Length: ").concat(String.valueOf(bytes.length)));
}
// der Header wird fuer die Ausgabe zusammengestellt
string = this.header(this.status, (String[])header.toArray(new String[0])).concat("\r\n\r\n");
// die Connection wird als verwendet gekennzeichnet
this.control = false;
// der Zeitpunkt wird registriert, um auf blockierte
// Datenstroeme reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
this.output.write(string.getBytes());
this.output.write(bytes);
if (this.isolation != 0)
this.isolation = -1;
this.volume += bytes.length;
return;
}
this.status = 403;
return;
}
// wenn vom Client uebermittelt, wird IF-(UN)MODIFIED-SINCE geprueft
// und bei (un)gueltiger Angabe STATUS 304/412 gesetzt
if (!Worker.fileIsModified(file, this.fields.get("http_if_modified_since"))) {
this.status = 304;
return;
}
if (this.fields.contains("http_if_unmodified_since")
&& Worker.fileIsModified(file, this.fields.get("http_if_unmodified_since"))) {
this.status = 412;
return;
}
offset = 0;
size = file.length();
limit = size;
// ggf. werden der partielle Datenbereich RANGE ermittelt
if (this.fields.contains("http_range")
&& size > 0) {
// mogeliche Header fuer den Range:
// Range: ...; bytes=500-999 ...
// ...; bytes=-999 ...
// ...; bytes=500- ...
string = this.fields.get("http_range").replace(';', '\n');
string = Section.parse(string).get("bytes");
if (string.matches("^(\\d+)*\\s*-\\s*(\\d+)*$")) {
tokenizer = new StringTokenizer(string, "-");
try {
offset = Long.parseLong(tokenizer.nextToken().trim());
if (tokenizer.hasMoreTokens()) {
limit = Long.parseLong(tokenizer.nextToken().trim());
} else if (string.startsWith("-")) {
if (offset > 0) {
limit = size -1;
offset = Math.max(0, size -offset);
} else limit = -1;
}
limit = Math.min(limit, size -1);
if (offset >= size) {
this.status = 416;
return;
}
if (offset <= limit) {
this.status = 206;
limit++;
} else {
offset = 0;
limit = size;
}
} catch (Throwable throwable) {
offset = 0;
size = file.length();
limit = size;
}
}
}
// der Header wird zusammengestellt
header.add(("Last-Modified: ").concat(Worker.dateFormat("E, dd MMM yyyy HH:mm:ss z", new Date(file.lastModified()), "GMT")));
header.add(("Content-Length: ").concat(String.valueOf(limit -offset)));
header.add(("Accept-Ranges: bytes"));
// wenn verfuegbar wird der Content-Type gesetzt
if (this.mediatype.length() > 0)
header.add(("Content-Type: ").concat(this.mediatype));
// ggf. wird der partielle Datenbereich gesetzt
if (this.status == 206)
header.add(("Content-Range: bytes ").concat(String.valueOf(offset)).concat("-").concat(String.valueOf(limit -1)).concat("/").concat(String.valueOf(size)));
// der Header wird fuer die Ausgabe zusammengestellt
string = this.header(this.status, (String[])header.toArray(new String[0])).concat("\r\n\r\n");
// die Connection wird als verwendet gekennzeichnet
this.control = false;
// der Zeitpunkt wird registriert, um auf blockierte Datenstroeme
// reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
this.output.write(string.getBytes());
if (this.isolation != 0)
this.isolation = -1;
if (method.equals("get")) {
// das ByteArray wird mit dem BLOCKSIZE eingerichtet
bytes = new byte[this.blocksize];
input = null;
try {
// der Datenstrom wird eingerichtet
input = new FileInputStream(this.resource);
// ggf. wird der partielle Datenbereich beruecksichtigt
input.skip(offset);
// der Datenstrom wird ausgelesen
while ((offset +this.volume < limit)
&& ((size = input.read(bytes)) >= 0)) {
if (this.status == 206 && (offset +this.volume +size > limit))
size = limit -(offset +this.volume);
// der Zeitpunkt wird registriert, um auf blockierte
// Datenstroeme reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
this.output.write(bytes, 0, Math.max(0, (int)size));
if (this.isolation != 0)
this.isolation = -1;
this.volume += size;
}
} finally {
// der Datenstrom wird geschlossen
try {input.close();
} catch (Throwable throwable) {
}
}
}
}
private void doPut()
throws Exception {
File file;
OutputStream output;
byte[] bytes;
long length;
long size;
// die Ressource wird eingerichtet
file = new File(this.resource);
// ohne CONTENT-LENGTH werden Verzeichnisse, sonst Dateien angelegt
if (!this.fields.contains("http_content_length")) {
// die Verzeichnisstruktur wird angelegt
// bei Fehlern wird STATUS 424 gesetzt
if (!(file.isDirectory() || file.mkdirs()))
this.status = 424;
// bei erfolgreicher Methode wird STATUS 201 gesetzt
if (this.status == 200
|| this.status == 404) {
this.fields.set("req_location", this.environment.get("script_uri"));
this.status = 201;
}
return;
}
// die Laenge des Contents wird ermittelt
try {length = Long.parseLong(this.fields.get("http_content_length"));
} catch (Throwable throwable) {
length = -1;
}
// die Methode setzt eine gueltige Dateilaenge voraus, ohne gueltige
// Dateilaenge wird STATUS 411 gesetzt
if (length < 0) {
this.status = 411;
return;
}
// ggf. bestehende Dateien werden entfernt
file.delete();
// das Datenpuffer wird eingerichtet
bytes = new byte[this.blocksize];
output = null;
try {
// der Datenstrom wird eingerichtet
output = new FileOutputStream(this.resource);
while (length > 0) {
// die Daten werden aus dem Datenstrom gelesen
if ((size = this.input.read(bytes)) < 0)
break;
// die zu schreibende Datenmenge wird ermittelt
// CONTENT-LENGHT wird dabei nicht ueberschritten
size = Math.min(size, length);
// die Daten werden geschrieben
output.write(bytes, 0, (int)size);
// das verbleibende Datenvolumen wird berechnet
length -= size;
Thread.sleep(this.interrupt);
}
// kann die Datei nicht oder durch Timeout nur unvollstaendig
// angelegt werden wird STATUS 424 gesetzt
if (length > 0)
this.status = 424;
} finally {
// der Datenstrom wird geschlossen
try {output.close();
} catch (Throwable throwable) {
}
}
// bei erfolgreicher Methode wird STATUS 201 gesetzt
if (this.status == 200
|| this.status == 404) {
this.fields.set("req_location", this.environment.get("script_uri"));
this.status = 201;
}
}
private void doDelete() {
// die angeforderte Ressource wird komplett geloescht,
// tritt dabei ein Fehler auf wird STATUS 424 gesetzt
if (Worker.fileDelete(new File(this.resource)))
return;
this.status = 424;
}
private void doStatus()
throws Exception {
Enumeration enumeration;
Generator generator;
Hashtable elements;
List header;
String method;
String string;
String shadow;
byte[] bytes;
header = new ArrayList();
// die Methode wird ermittelt
method = this.fields.get("req_method").toLowerCase();
if (method.equals("options")
&& (this.status == 302 || this.status == 404))
this.status = 200;
if (this.status == 302) {
// die LOCATION wird fuer die Weiterleitung ermittelt
string = this.environment.get("query_string");
if (string.length() > 0)
string = ("?").concat(string);
string = this.environment.get("script_uri").concat(string);
this.fields.set("req_location", string);
} else {
string = String.valueOf(this.status);
// das Template fuer den Server Status wird ermittelt
this.resource = this.sysroot.concat("/status-").concat(string).concat(".html");
if (!new File(this.resource).exists())
this.resource = this.sysroot.concat("/status-").concat(string.substring(0, 1)).concat("xx.html");
if (!new File(this.resource).exists())
this.resource = this.sysroot.concat("/status.html");
}
// der Typ zur Autorisierung wird wenn vorhanden ermittelt
shadow = this.fields.get("auth_type");
if (this.status == 401 && shadow.length() > 0) {
string = (" realm=\"").concat(this.fields.get("auth_realm")).concat("\"");
if (shadow.equals("Digest")) {
string = ("Digest").concat(string);
string = string.concat(", qop=\"auth\"");
shadow = this.environment.get("unique_id");
string = string.concat(", nonce=\"").concat(shadow).concat("\"");
shadow = Worker.textHash(shadow.concat(String.valueOf(shadow.hashCode())));
string = string.concat(", opaque=\"").concat(shadow).concat("\"");
string = string.concat(", algorithm=\"MD5\"");
} else string = ("Basic").concat(string);
header.add(("WWW-Authenticate: ").concat(string));
}
if (this.fields.contains("req_location"))
header.add(("Location: ").concat(this.fields.get("req_location")));
// der Generator wird eingerichtet, dabei werden fuer die STATUS
// Klasse 1xx, den STATUS 302 (Redirection), 200 (Success) sowie die
// METHOD:HEAD/METHOD:OPTIONS keine Templates verwendet
string = String.valueOf(this.status);
string = this.statuscodes.get(string);
generator = Generator.parse(method.equals("head")
|| method.equals("options")
|| string.toUpperCase().contains("[H]") ? null : Worker.fileRead(new File(this.resource)));
// der Header wird mit den Umgebungsvariablen zusammengefasst,
// die serverseitig gesetzten haben dabei die hoehere Prioritaet
elements = new Hashtable();
enumeration = this.fields.elements();
while (enumeration.hasMoreElements()) {
string = (String)enumeration.nextElement();
elements.put(string, this.fields.get(string));
}
enumeration = this.environment.elements();
while (enumeration.hasMoreElements()) {
string = (String)enumeration.nextElement();
elements.put(string, this.environment.get(string));
}
string = String.valueOf(this.status);
elements.put("HTTP_STATUS", string);
elements.put("HTTP_STATUS_TEXT", Worker.cleanOptions(this.statuscodes.get(string)));
// die allgemeinen Elemente werden gefuellt
generator.set(elements);
bytes = generator.extract();
// bei Bedarf wird im Header CONTENT-TYPE / CONTENT-LENGTH gesetzt
if (bytes.length > 0) {
header.add(("Content-Type: ").concat(this.mediatypes.get("html")));
header.add(("Content-Length: ").concat(String.valueOf(bytes.length)));
}
// die verfuegbaren Methoden werden ermittelt und zusammengestellt
string = String.join(", ", this.options.get("methods").split("\\s+"));
if (string.length() > 0)
header.add(("Allow: ").concat(string));
// der Header wird fuer die Ausgabe zusammengestellt
string = this.header(this.status, (String[])header.toArray(new String[0])).concat("\r\n\r\n");
// die Connection wird als verwendet gekennzeichnet
this.control = false;
// der Zeitpunkt wird registriert, um auf blockierte Datenstroeme
// reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
// der Response wird ausgegeben
if (this.output != null) {
this.output.write(string.getBytes());
this.output.write(bytes);
}
// das Datenvolumen wird uebernommen
this.volume += bytes.length;
if (this.isolation != 0)
this.isolation = -1;
}
/**
* Nimmt den Request an und organisiert die Verarbeitung und Beantwortung.
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private void service()
throws Exception {
File file;
String method;
try {
// die Connection wird initialisiert, um den Serverprozess nicht zu
// behindern wird die eigentliche Initialisierung der Connection erst mit
// laufendem Thread als asynchroner Prozess vorgenommen
try {this.initiate();
} catch (Exception exception) {
this.status = 500;
throw exception;
}
// die Ressource wird eingerichtet
file = new File(this.resource);
// die Ressource muss auf Modul, Datei oder Verzeichnis verweisen
if (this.status == 0) this.status = file.isDirectory() || file.isFile() || this.resource.toUpperCase().contains("[M]") ? 200 : 404;
if (this.control) {
// PROCESS/(X)CGI/MODULE - wird bei gueltiger Angabe ausgefuehrt
if (this.status == 200 && this.gateway.length() > 0) {
try {this.doGateway();
} catch (Exception exception) {
this.status = 502;
throw exception;
}
} else {
// die Methode wird ermittelt
method = this.fields.get("req_method").toLowerCase();
// vom Server werden die Methoden OPTIONS, HEAD, GET, PUT, DELETE
// unterstuetzt bei anderen Methoden wird STATUS 501 gesetzt
if (this.status == 200
&& !method.equals("options") && !method.equals("head") && !method.equals("get")
&& !method.equals("put") && !method.equals("delete"))
this.status = 501;
// METHOD:PUT - wird bei gueltiger Angabe ausgefuehrt
if (this.status == 200 && method.equals("head"))
try {this.doGet();
} catch (Exception exception) {
this.status = 500;
throw exception;
}
if (this.status == 200 && method.equals("get"))
try {this.doGet();
} catch (Exception exception) {
this.status = 500;
throw exception;
}
// METHOD:PUT - wird bei gueltiger Angabe ausgefuehrt
if ((this.status == 200 || this.status == 404) && method.equals("put"))
try {this.doPut();
} catch (Exception exception) {
this.status = 424;
throw exception;
}
// METHOD:DELETE - wird bei gueltiger Angabe ausgefuehrt
if (this.status == 200 && method.equals("delete"))
try {this.doDelete();
} catch (Exception exception) {
this.status = 424;
throw exception;
}
}
}
} finally {
// der Zeitpunkt evtl. blockierender Datenstroeme wird
// zurueckgesetzt
if (this.isolation != 0)
this.isolation = -1;
// STATUS/ERROR/METHOD:OPTIONS - wird ggf. ausgefuehrt
if (this.control)
try {this.doStatus();
} catch (IOException exception) {
}
}
}
/** Protokollierte den Zugriff im Protokollmedium. */
private void register()
throws Exception {
Enumeration source;
Generator generator;
Hashtable values;
OutputStream stream;
String format;
String output;
String string;
// der Client wird ermittelt
string = this.environment.get("remote_addr");
try {string = InetAddress.getByName(string).getHostName();
} catch (Throwable throwable) {
}
this.environment.set("remote_host", string);
this.environment.set("response_length", String.valueOf(this.volume));
this.environment.set("response_status", String.valueOf(this.status == 0 ? 500 : this.status));
synchronized (Worker.class) {
// das Format vom ACCESSLOG wird ermittelt
format = this.options.get("accesslog");
// Konvertierung der String-Formater-Syntax in Generator-Syntax
format = format.replaceAll("#", "#[0x23]");
format = format.replaceAll("%%", "#[0x25]");
format = format.replaceAll("%\\[", "#[");
format = format.replaceAll("%t", "%1\\$t");
// die Zeitsymbole werden aufgeloest
format = String.format(Locale.US, format, new Date());
// Format und Pfad werden am Zeichen > getrennt
if (format.contains(">")) {
output = format.split(">")[1].trim();
format = format.split(">")[0].trim();
} else output = "";
// ohne Format und/oder mit OFF wird kein Access-Log erstellt
if (format.length() <= 0
|| format.toLowerCase().equals("off"))
return;
values = new Hashtable();
source = this.environment.elements();
while (source.hasMoreElements()) {
string = (String)source.nextElement();
values.put(string, Worker.textEscape(this.environment.get(string)));
}
generator = Generator.parse(format.getBytes());
generator.set(values);
format = new String(generator.extract());
format = format.replaceAll("(?<=\\s)(''|\"\")((?=\\s)|$)", "-");
format = format.replaceAll("(\\s)((?=\\s)|$)", "$1-");
format = format.concat(System.lineSeparator());
generator = Generator.parse(output.getBytes());
generator.set(values);
output = new String(generator.extract());
output = output.replaceAll("(?<=\\s)(''|\"\")((?=\\s)|$)", "-");
output = output.replaceAll("(\\s)((?=\\s)|$)", "$1-").trim();
// wurde kein ACCESSLOG definiert wird in den StdIO,
// sonst in die entsprechende Datei geschrieben
if (output.length() > 0) {
stream = new FileOutputStream(output, true);
try {stream.write(format.getBytes());
} finally {
stream.close();
}
} else Service.print(format, true);
}
}
/**
* Merkt den Worker zum Schliessen vor, wenn diese in der naechsten Zeit
* nicht mehr verwendet wird. Der Zeitpunkt zum Bereinigen beträgt
* 250ms Leerlaufzeit nach der letzen Nutzung. Die Zeit wird über das
* SoTimeout vom ServerSocket definiert.
*/
void isolate() {
if (this.accept == null
&& this.socket != null)
this.socket = null;
}
/**
* Rückgabe {@code true}, wenn der Worker aktiv zur Verfügung
* steht und somit weiterhin Requests entgegen nehmen kann.
* @return {@code true}, wenn der Worker aktiv verfübar ist
*/
boolean available() {
// der Socket wird auf Blockaden geprueft und ggf. geschlossen
if (this.socket != null
&& this.isolation > 0
&& this.isolation < System.currentTimeMillis() -this.timeout)
this.destroy();
return this.socket != null && this.accept == null;
}
/** Beendet den Worker durch das Schliessen der Datenströme. */
void destroy() {
// der ServerSocket wird zurueckgesetzt
this.socket = null;
if (this.isolation != 0)
this.isolation = -1;
// der Socket wird geschlossen
try {this.accept.close();
} catch (Throwable throwable) {
}
}
@Override
public void run() {
ServerSocket socket;
String string;
// der ServerSocket wird vorgehalten
socket = this.socket;
while (this.socket != null) {
// initiale Einrichtung der Variablen
this.status = 0;
this.volume = 0;
this.control = true;
this.docroot = "";
this.gateway = "";
this.resource = "";
this.mediatype = "";
this.sysroot = "";
// die Felder vom Header werde eingerichtet
this.fields = new Section(true);
// die Konfigurationen wird geladen
this.access = (Section)this.initialize.get(this.context.concat(":acc")).clone();
this.environment = (Section)this.initialize.get(this.context.concat(":env")).clone();
this.filters = (Section)this.initialize.get(this.context.concat(":flt")).clone();
this.interfaces = (Section)this.initialize.get(this.context.concat(":cgi")).clone();
this.options = (Section)this.initialize.get(this.context.concat(":ini")).clone();
this.references = (Section)this.initialize.get(this.context.concat(":ref")).clone();
this.statuscodes = (Section)this.initialize.get("statuscodes").clone();
this.mediatypes = (Section)this.initialize.get("mediatypes").clone();
// die zu verwendende Blockgroesse wird ermittelt
try {this.blocksize = Integer.parseInt(this.options.get("blocksize"));
} catch (Throwable throwable) {
this.blocksize = 65535;
}
if (this.blocksize <= 0)
this.blocksize = 65535;
string = this.options.get("timeout");
this.isolation = string.toUpperCase().contains("[S]") ? -1 : 0;
// das Timeout der Connecton wird ermittelt
try {this.timeout = Long.parseLong(Worker.cleanOptions(string));
} catch (Throwable throwable) {
this.timeout = 0;
}
// die maximale Prozesslaufzeit wird gegebenfalls korrigiert
if (this.timeout < 0)
this.timeout = 0;
// der Interrupt wird ermittelt
try {this.interrupt = Long.parseLong(this.options.get("interrupt"));
} catch (Throwable throwable) {
this.interrupt = 10;
}
if (this.interrupt < 0)
this.interrupt = 10;
try {this.accept = socket.accept();
} catch (InterruptedIOException exception) {
continue;
} catch (IOException exception) {
break;
}
// der Request wird verarbeitet
try {this.service();
} catch (Throwable throwable) {
Service.print(throwable);
}
// die Connection wird beendet
try {this.destroy();
} catch (Throwable throwable) {
}
// HINWEIS - Beim Schliessen wird der ServerSocket verworfen, um
// die Connection von Aussen beenden zu koennen, intern wird
// diese daher nach dem Beenden neu gesetzt
// der Zugriff wird registriert
try {this.register();
} catch (Throwable throwable) {
Service.print(throwable);
}
// der Socket wird alternativ geschlossen
try {this.accept.close();
} catch (Throwable throwable) {
}
// durch das Zuruecksetzen wird die Connection ggf. reaktivert
this.socket = socket;
// der Socket wird verworfen
this.accept = null;
}
}
} | sources/com/seanox/devwex/Worker.java | /**
* LIZENZBEDINGUNGEN - Seanox Software Solutions ist ein Open-Source-Projekt, im
* Folgenden Seanox Software Solutions oder kurz Seanox genannt.
* Diese Software unterliegt der Version 2 der Apache License.
*
* Devwex, Advanced Server Development
* Copyright (C) 2022 Seanox Software Solutions
*
* 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.seanox.devwex;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.net.ssl.SSLSocket;
/**
* Worker, wartet auf eingehende HTTP-Anfrage, wertet diese aus, beantwortet
* diese entsprechend der HTTP-Methode und protokolliert den Zugriff.<br>
* <br>
* Hinweis zum Thema Fehlerbehandlung - Die Verarbeitung der Requests soll so
* tolerant wie möglich erfolgen. Somit werden interne Fehler, wenn
* möglich, geschluckt und es erfolgt eine alternative aber sichere
* Beantwortung. Kann der Request nicht mehr kontrolliert werden, erfolgt ein
* kompletter Abbruch.
*
* @author Seanox Software Solutions
* @version 5.5.0 20220911
*/
class Worker implements Runnable {
/** Server Context */
private volatile String context;
/** Socket vom Worker */
private volatile Socket accept;
/** Socket des Servers */
private volatile ServerSocket socket;
/** Server Konfiguration */
private volatile Initialize initialize;
/** Dateneingangsstrom */
private volatile InputStream input;
/** Datenausgangsstrom */
private volatile OutputStream output;
/** Zugriffsrechte des Servers */
private volatile Section access;
/** Umgebungsvariablen des Servers */
private volatile Section environment;
/** Felder des Request-Headers */
private volatile Section fields;
/** Filter des Servers */
private volatile Section filters;
/** Common Gateway Interfaces des Servers */
private volatile Section interfaces;
/** Konfiguration des Servers */
private volatile Section options;
/** virtuelle Verzeichnisse des Servers */
private volatile Section references;
/** Mediatypes des Servers */
private volatile Section mediatypes;
/** Statuscodes des Servers */
private volatile Section statuscodes;
/** Dokumentenverzeichnis des Servers */
private volatile String docroot;
/** Header des Requests */
private volatile String header;
/** Mediatype des Requests */
private volatile String mediatype;
/** Resource des Requests */
private volatile String resource;
/** Gateway Interface */
private volatile String gateway;
/** Systemverzeichnis des Servers */
private volatile String sysroot;
/** Datenflusskontrolle */
private volatile boolean control;
/** Blockgrösse für Datenzugriffe */
private volatile int blocksize;
/** Statuscode des Response */
private volatile int status;
/** Interrupt für Systemprozesse im Millisekunden */
private volatile long interrupt;
/** Timeout beim ausgehenden Datentransfer in Millisekunden */
private volatile long isolation;
/** Timeout bei Datenleerlauf in Millisekunden */
private volatile long timeout;
/** Menge der übertragenen Daten */
private volatile long volume;
/**
* Konstruktor, richtet den Worker mit Socket ein.
* @param context Server Context
* @param socket Socket mit dem eingegangen Request
* @param initialize Server Konfiguraiton
*/
Worker(String context, ServerSocket socket, Initialize initialize) {
context = context.replaceAll("(?i):[a-z]+$", "");
this.context = context;
this.socket = socket;
this.initialize = initialize;
}
/**
* Entfernt aus dem String Parameter und Optionen im Format {@code [...]}.
* Bereinigt werden alle Angaben, ob voll- oder unvollständig, ab dem
* ersten Vorkommen.
* @param string zu bereinigender String
* @return der String ohne Parameter und Optionen
*/
private static String cleanOptions(String string) {
int cursor = string.indexOf('[');
if (cursor >= 0)
string = string.substring(0, cursor).trim();
return string;
}
/**
* Erstellt zum String einen hexadezimalen MD5-Hash.
* @param string zu dem der Hash erstellt werden soll
* @return der erstellte hexadezimale MD5-Hash
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private static String textHash(String string)
throws Exception {
if (string == null)
string = "";
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] bytes = digest.digest(string.getBytes());
string = new BigInteger(1, bytes).toString(16);
while (string.length() < 32)
string = ("0").concat(string);
return string;
}
/**
* Maskiert im String die Steuerzeichen: BS, HT, LF, FF, CR, ', ", \ und
* alle Zeichen ausserhalb vom ASCII-Bereich 0x20-0x7F.
* Die Maskierung erfolgt per Slash:
* <ul>
* <li>Slash + ISO</li>
* <li>Slash + drei Bytes oktal (0x80-0xFF)</li>
* <li>Slash + vier Bytes hexadezimal (0x100-0xFFFF)</li>
* </ul>
* @param string zu maskierender String
* @return der String mit den ggf. maskierten Zeichen.
*/
public static String textEscape(String string) {
byte[] codex;
byte[] codec;
byte[] cache;
int code;
int count;
int cursor;
int length;
int loop;
if (string == null)
return null;
length = string.length();
cache = new byte[length *6];
codex = ("\b\t\n\f\r\"'\\btnfr\"'\\").getBytes();
codec = ("0123456789ABCDEF").getBytes();
for (loop = count = 0; loop < length; loop++) {
code = string.charAt(loop);
cursor = Arrays.binarySearch(codex, (byte)code);
if (cursor >= 0 && cursor < 8) {
cache[count++] = '\\';
cache[count++] = codex[cursor +8];
} else if (code > 0xFF) {
cache[count++] = '\\';
cache[count++] = 'u';
cache[count++] = codec[(code >> 12) & 0xF];
cache[count++] = codec[(code >> 8) & 0xF];
cache[count++] = codec[(code >> 4) & 0xF];
cache[count++] = codec[(code & 0xF)];
} else if (code < 0x20 || code > 0x7F) {
cache[count++] = '\\';
cache[count++] = 'x';
cache[count++] = codec[(code >> 4) & 0xF];
cache[count++] = codec[(code & 0xF)];
} else cache[count++] = (byte)code;
}
return new String(Arrays.copyOfRange(cache, 0, count));
}
/**
* Dekodiert den String tolerant als URL und UTF-8.
* Tolerant, da fehlerhafte kodierte Zeichenfolgen nicht direkt zum Fehler
* f¨hren, sondern erhalten bleiben und die UTF-8 Kodierung optional
* betrachtet wird.
* @param string zu dekodierender String
* @return der dekodierte String
*/
private static String textDecode(String string) {
byte[] bytes;
boolean control;
int code;
int count;
int length;
int loop;
int digit;
int cursor;
if (string == null)
string = "";
// Datenpuffer wird eingerichtet
length = string.length();
bytes = new byte[length *2];
for (loop = count = 0; loop < length; loop++) {
// der ASCII Code wird ermittelt
code = string.charAt(loop);
if (code == 43)
code = 32;
// der Hexcode wird in das ASCII Zeichen umgesetzt
if (code == 37) {
loop += 2;
try {code = Integer.parseInt(string.substring(loop -1, loop +1), 16);
} catch (Throwable throwable) {
loop -= 2;
}
}
bytes[count++] = (byte)code;
}
bytes = Arrays.copyOfRange(bytes, 0, count);
length = bytes.length;
cursor = 0;
digit = 0;
control = false;
for (loop = count = 0; loop < length; loop++) {
// der ASCII Code wird ermittelt
code = bytes[loop] & 0xFF;
if (code >= 0xC0 && code <= 0xC3)
control = true;
// Decodierung der Bytes als UTF-8, das Muster 10xxxxxx
// wird um die 6Bits erweitert
if ((code & 0xC0) == 0x80) {
digit = (digit << 0x06) | (code & 0x3F);
if (--cursor == 0) {
bytes[count++] = (byte)digit;
control = false;
}
} else {
digit = 0;
cursor = 0;
// 0xxxxxxx (7Bit/0Byte) werden direkt verwendet
if (((code & 0x80) == 0x00) || !control) {
bytes[count++] = (byte)code;
control = false;
}
// 110xxxxx (5Bit/1Byte), 1110xxxx (4Bit/2Byte),
// 11110xxx (3Bit/3Byte), 111110xx (2Bit/4Byte),
// 1111110x (1Bit/5Byte)
if ((code & 0xE0) == 0xC0) {
cursor = 1;
digit = code & 0x1F;
} else if ((code & 0xF0) == 0xE0) {
cursor = 2;
digit = code & 0x0F;
} else if ((code & 0xF8) == 0xF0) {
cursor = 3;
digit = code & 0x07;
} else if ((code & 0xFC) == 0xF8) {
cursor = 4;
digit = code & 0x03;
} else if ((code & 0xFE) == 0xFC) {
cursor = 5;
digit = code & 0x01;
}
}
}
return new String(bytes, 0, count);
}
/**
* Formatiert das Datum im angebenden Format und in der angegebenen Zone.
* Rückgabe das formatierte Datum, im Fehlerfall ein leerer String.
* @param format Formatbeschreibung
* @param date zu formatierendes Datum
* @param zone Zeitzone, {@code null} Standardzone
* @return das formatierte Datum als String, im Fehlerfall leerer String
*/
private static String dateFormat(String format, Date date, String zone) {
SimpleDateFormat pattern;
// die Formatierung wird eingerichtet
pattern = new SimpleDateFormat(format, Locale.US);
// die Zeitzone wird gegebenenfalls fuer die Formatierung gesetzt
if (zone != null) pattern.setTimeZone(TimeZone.getTimeZone(zone));
// die Zeitangabe wird formatiert
return pattern.format(date);
}
/**
* Liest die Datei einer Datei.
* @param file zu lesende Datei
* @return die gelesenen Daten, im Fehlerfall ein leeres Byte-Array
*/
private static byte[] fileRead(File file) {
try {return Files.readAllBytes(file.toPath());
} catch (Throwable throwable) {
return null;
}
}
/**
* Normalisiert den String eines Pfads und lösst ggf. existierende
* Pfad-Direktiven auf und ändert das Backslash in Slash.
* @param path zu normalisierender Pfad
* @return der normalisierte Pfad
*/
private static String fileNormalize(String path) {
String string;
String stream;
int cursor;
// die Pfadangabe wird auf Slash umgestellt
string = path.replace('\\', '/').trim();
// mehrfache Slashs werden zusammengefasst
while ((cursor = string.indexOf("//")) >= 0)
string = string.substring(0, cursor).concat(string.substring(cursor +1));
// der Path wird ggf. ausgeglichen /abc/./def/../ghi -> /abc/ghi
// der Path wird um "/." ausgeglichen
if (string.endsWith("/."))
string = string.concat("/");
while ((cursor = string.indexOf("/./")) >= 0)
string = string.substring(0, cursor).concat(string.substring(cursor +2));
// der String wird um "/.." ausgeglichen
if (string.endsWith("/.."))
string = string.concat("/");
while ((cursor = string.indexOf("/../")) >= 0) {
stream = string.substring(cursor +3);
string = string.substring(0, cursor);
cursor = string.lastIndexOf("/");
cursor = Math.max(0, cursor);
string = string.substring(0, cursor).concat(stream);
}
// mehrfache Slashs werden zusammengefasst
while ((cursor = string.indexOf("//")) >= 0)
string = string.substring(0, cursor).concat(string.substring(cursor +1));
return string;
}
/**
* Löscht die Ressource, handelt es sich um ein Verzeichnis, werden
* alle Unterdateien und Unterverzeichnisse rekursive gelöscht.
* Rückgabe {@code true} im Fehlerfall {@code false}.
* @param resource zu löschende Ressource
* @return {@code true}, im Fehlerfall {@code false}
*/
private static boolean fileDelete(File resource) {
File[] files;
int loop;
// bei Verzeichnissen wird die Dateiliste ermittelt rekursive geloescht
if (resource.isDirectory()) {
files = resource.listFiles();
if (files == null)
return true;
for (loop = 0; loop < files.length; loop++)
if (!Worker.fileDelete(files[loop]))
return false;
}
// der File oder das leere Verzeichnis wird geloescht, ist dies nicht
// moeglich wird false zurueckgegeben
return resource.delete();
}
/**
* Prüft ob die Ressource dem {@code IF-(UN)MODIFIED-SINCE} entspricht.
* Rückgabe {@code false} wenn die Ressource in Datum und
* Dateigrösse entspricht, sonst {@code true}.
* @param file Dateiobjekt
* @param string Information der Modifikation
* @return {@code true} wenn Unterschiede in Datum oder Dateigrösse
* ermittelt wurden
*/
private static boolean fileIsModified(File file, String string) {
SimpleDateFormat pattern;
StringTokenizer tokenizer;
int cursor;
long timing;
if (string.length() <= 0)
return true;
// If-(Un)Modified-Since wird geprueft
tokenizer = new StringTokenizer(string, ";");
try {
// die Formatierung wird eingerichtet
pattern = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.US);
// die Zeitzone wird gegebenenfalls fuer die Formatierung gesetzt
pattern.setTimeZone(TimeZone.getTimeZone("GMT"));
timing = pattern.parse(tokenizer.nextToken()).getTime() /1000L;
// IF-(UN)MODIFIED-SINCE:TIMEDATE wird ueberprueft
if (timing != file.lastModified() /1000L)
return true;
while (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken().trim();
if (!string.toLowerCase().startsWith("length"))
continue;
cursor = string.indexOf("=");
if (cursor < 0)
continue;
// IF-(UN)MODIFIED-SINCE:LENGTH wird ueberprueft
return file.length() != Long.parseLong(string.substring(cursor +1).trim());
}
} catch (Throwable throwable) {
return true;
}
return false;
}
/**
* Erstellt zu einem abstrakter File das physische File-Objekt.
* @param file abstrakter File
* @return das physische File-Objekt, sonst {@code null}
*/
private static File fileCanonical(File file) {
try {return file.getCanonicalFile();
} catch (Throwable throwable) {
return null;
}
}
/**
* Ruft eine Modul-Methode auf.
* Wenn erforderlich wird das Modul zuvor geladen und initialisiert.
* Module werden global geladen und initialisiert. Ist ein Modul beim Aufruf
* der Methode noch nicht geladen, erfolgt dieses ohne Angabe von Parametern
* mit der ersten Anforderung.<br>
* Soll ein Modul mit Parametern initalisiert werden, muss das Modul in der
* Sektion {@code INITIALIZE} deklariert oder über den
* Context-ClassLoader vom Devwex-Module-SDK geladen werden.
* Rückgabe {@code true} wenn die Ressource geladen und die Methode
* erfolgreich aufgerufen wurde.
* @param resource Resource
* @param invoke Methode
* @return {@code true}, im Fehlerfall {@code false}
*/
private boolean invoke(String resource, String invoke)
throws Exception {
Object object;
Method method;
String string;
if (invoke == null
|| invoke.trim().length() <= 0)
return false;
object = Service.load(Service.load(resource), null);
if (object == null)
return false;
string = this.environment.get("module_opts");
if (string.length() <= 0)
string = null;
// die Methode fuer den Modul-Einsprung wird ermittelt
method = object.getClass().getMethod(invoke, Object.class, String.class);
// die Methode fuer den Modul-Einsprung wird aufgerufen
method.invoke(object, this, string);
return true;
}
/**
* Ermittelt für das angegebene virtuelle Verzeichnis den realen Pfad.
* Wurde der Pfad nicht als virtuelles Verzeichnis eingerichtet, wird ein
* leerer String zurückgegeben.
* @param path Pfad des virtuellen Verzeichnis
* @return der reale Pfad oder ein leerer String
*/
private String locate(String path) {
Enumeration enumeration;
File source;
String access;
String alias;
String locale;
String location;
String options;
String reference;
String result;
String rules;
String shadow;
String buffer;
String string;
String target;
boolean absolute;
boolean connect;
boolean forbidden;
boolean module;
boolean redirect;
boolean virtual;
int cursor;
// der Pfad wird getrimmt, in Kleinbuchstaben umformatiert, die
// Backslashs gegen Slashs getauscht
path = path.replace('\\', '/').trim();
// fuer die Ermittlung wird der Pfad mit / abgeschlossen um auch
// Referenzen wie z.B. /a mit /a/ ermitteln zu koennen
locale = path.toLowerCase();
if (!locale.endsWith("/"))
locale = locale.concat("/");
// initiale Einrichtung der Variablen
access = "";
location = "";
options = "";
reference = "";
result = "";
shadow = "";
absolute = false;
forbidden = false;
module = false;
redirect = false;
source = null;
// die Liste der Referenzen wird ermittelt
enumeration = this.references.elements();
// die virtuellen Verzeichnisse werden ermittelt
while (enumeration.hasMoreElements()) {
// die Regel wird ermittelt
rules = ((String)enumeration.nextElement()).toLowerCase();
rules = this.references.get(rules);
// Alias, Ziel und Optionen werden ermittelt
cursor = rules.indexOf('>');
if (cursor < 0) {
cursor = rules.replace(']', '[').indexOf('[');
if (cursor < 0)
continue;
alias = rules.substring(0, cursor).trim();
rules = rules.substring(cursor).trim();
} else {
alias = rules.substring(0, cursor).trim();
rules = rules.substring(cursor +2).trim();
}
target = Worker.cleanOptions(rules);
alias = Worker.fileNormalize(alias);
// die Optionen werden ermittelt
string = rules.toUpperCase();
virtual = string.contains("[A]") || string.contains("[M]");
connect = string.contains("[M]") || string.contains("[R]");
// ungueltige bzw. unvollstaendige Regeln werden ignoriert
// - ohne Alias
// - Redirect / Modul ohne Ziel
// - Alias ohne Ziel und Optionen
if (alias.length() <= 0
|| (connect && target.length() <= 0)
|| (rules.length() <= 0 && target.length() <= 0))
continue;
// ggf. wird der Alias um Slash erweitert, damit spaeter DOCROOT
// und Alias einen plausiblen Pfad ergeben
if (!alias.startsWith("/"))
alias = ("/").concat(alias);
// ggf. wird der Alias als Target uebernommen, wenn kein Target
// angegeben wurde, z.B. wenn fuer einen realen Pfad nur Optionen
// festgelegt werden
if (target.length() <= 0)
target = this.docroot.concat(alias);
// das Ziel wird mit / abgeschlossen um auch Referenzen zwischen /a
// und /a/ ermitteln zu koennen
buffer = alias;
if (!virtual && !buffer.endsWith("/") && buffer.length() > 0)
buffer = buffer.concat("/");
// die qualifizierteste laengste Refrerenz wird ermittelt
if (locale.startsWith(buffer.toLowerCase())
&& buffer.length() > 0 && reference.length() <= buffer.length()) {
// optional wird die Sperrung des Verzeichnis ermittelt
forbidden = string.contains("[C]");
if (!connect) {
// die Zieldatei wird eingerichtet
// der absolute Pfad wird ermittelt
// Verzeichnisse werden ggf. mit Slash beendet
source = Worker.fileCanonical(new File(target));
if (source != null) {
target = source.getPath().replace('\\', '/');
if (source.isDirectory() && !target.endsWith("/"))
target = target.concat("/");
}
}
if (source != null || virtual || connect) {
location = target;
options = rules;
reference = alias;
module = string.contains("[M]");
absolute = string.contains("[A]") && !module;
redirect = string.contains("[R]") && !module;
}
}
// der Zielpfad wird mit / abgeschlossen um auch Referenzen
// zwischen /a und /a/ ermitteln zu koennen
buffer = alias;
if (!absolute
&& !module
&& !buffer.endsWith("/")
&& buffer.length() > 0)
buffer = buffer.concat("/");
// die ACC-Eintraege zur Authentifizierung werden zusammengesammelt
if (string.contains("[ACC:")
&& locale.startsWith(buffer.toLowerCase())
&& buffer.length() > 0
&& shadow.length() <= buffer.length()) {
shadow = buffer;
access = rules.replaceAll("(?i)(\\[(((acc|realm):[^\\[\\]]*?)|d)\\])", "\00$1\01");
access = access.replaceAll("[^\01]+(\00|$)", "");
access = access.replaceAll("[\00\01]+", " ");
}
}
// die Referenz wird alternativ ermittelt
if (reference.length() <= 0) reference = path;
// konnte eine Referenz ermittelt werden wird diese geparst
if (reference.length() > 0) {
// die Location wird ermittelt und gesetzt
result = absolute || module ? location : location.concat(path.substring(Math.min(path.length(), reference.length())));
// die Option [A] und [M] wird fuer absolute Referenzen geprueft
if (absolute || module) {
string = path.substring(0, Math.min(path.length(), reference.length()));
this.environment.set("script_name", string);
this.environment.set("path_context", string);
this.environment.set("path_info", path.substring(string.length()));
}
// die Moduldefinition wird als Umgebungsvariablen gesetzt
if (module) result = options;
}
if (result.length() <= 0)
result = this.docroot.concat(this.environment.get("path_url"));
if (!module && absolute)
result = result.concat("[A]");
if (!module && forbidden)
result = result.concat("[C]");
if (!module && redirect)
result = result.concat("[R]");
result = result.concat(access);
return result;
}
/**
* Überprüft die Zugriffbrechtigungen für eine Referenz und
* setzt ggf. den entsprechenden Status.
* @param reference Referenz
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private void authorize(String reference)
throws Exception {
Section section;
String access;
String realm;
String shadow;
String buffer;
String string;
String target;
StringTokenizer tokenizer;
boolean control;
boolean digest;
string = reference.toLowerCase();
if (!string.contains("[acc:") || this.status >= 500)
return;
// optional wird die Bereichskennung ermittelt
realm = reference.replaceAll("^(.*(\\[\\s*(?i)realm:([^\\[\\]]*?)\\s*\\]).*)|.*$", "$3");
realm = realm.replace("\"", "\\\"");
this.fields.set("auth_realm", realm);
digest = string.contains("[d]");
// der Authentication-Type wird gesetzt
this.fields.set("auth_type", digest ? "Digest" : "Basic");
// die Werte der ACC-Optionen werden ermittelt
string = string.replaceAll("\\[acc:([^\\[\\]]*?)\\]", "\00$1\01");
string = string.replaceAll("((((^|\01).*?)\00)|(\01.*$))|(^.*$)", " ").trim();
control = false;
tokenizer = new StringTokenizer(string);
access = "";
// die ACC-Eintraege (Gruppen) werden aufgeloest
// mit der Option [ACC:NONE] wird die Authorisation aufgehoben
while (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken();
if (string.equals("none"))
return;
control = true;
access = access.concat(" ").concat(this.access.get(string));
}
access = access.trim();
if (access.length() <= 0) {
if (control)
this.status = 401;
return;
}
// die Autorisierung wird ermittelt
string = this.fields.get("http_authorization");
if (string.toLowerCase().startsWith("digest ")
&& digest) {
string = string.replaceAll("(\\w+)\\s*=\\s*(?:(?:\"(.*?)\")|([^,]*))", "\00$1=$2$3\n");
string = string.replaceAll("[^\n]+\00", "");
section = Section.parse(string, true);
target = section.get("response");
shadow = section.get("username");
buffer = shadow.concat(":").concat(realm).concat(":");
string = Worker.textHash(this.environment.get("request_method").concat(":").concat(section.get("uri")));
string = (":").concat(section.get("nonce")).concat(":").concat(section.get("nc")).concat(":").concat(section.get("cnonce")).concat(":").concat(section.get("qop")).concat(":").concat(string);
tokenizer = new StringTokenizer(access);
while (tokenizer.hasMoreTokens()) {
access = tokenizer.nextToken();
if (shadow.equals(access))
access = access.substring(shadow.length());
else if (access.startsWith(shadow.concat(":")))
access = access.substring(shadow.length() +1);
else continue;
access = Worker.textHash(buffer.concat(access));
access = Worker.textHash(access.concat(string));
if (target.equals(access)) {
this.fields.set("auth_user", shadow);
return;
}
}
} else if (string.toLowerCase().startsWith("basic ")
&& !digest) {
try {string = new String(Base64.getDecoder().decode(string.substring(6).getBytes())).trim();
} catch (Throwable throwable) {
string = "";
}
access = (" ").concat(access).concat(" ");
if (string.length() > 0
&& access.contains((" ").concat(string).concat(" "))) {
string = string.substring(0, Math.max(0, string.indexOf(':'))).trim();
this.fields.set("auth_user", string);
return;
}
}
this.status = 401;
}
/**
* Überprüft die Filter und wendet diese bei Bedarf an.
* Filter haben keinen direkten Rückgabewert, sie beieinflussen u.a.
* Server-Status und Datenflusskontrolle.
*/
private String filter()
throws Exception {
Enumeration enumeration;
File file;
String valueA;
String valueB;
String method;
String buffer;
String string;
String location;
StringTokenizer rules;
StringTokenizer words;
boolean control;
int cursor;
int status;
location = this.resource;
if (this.status == 400 || this.status >= 500)
return location;
// FILTER die Filter werden in den Vektor geladen
// die Steuerung erfolgt ueber REFERENCE, SCRIPT_URI und CODE
enumeration = this.filters.elements();
while (enumeration.hasMoreElements()) {
string = this.filters.get((String)enumeration.nextElement());
cursor = string.indexOf('>');
buffer = cursor >= 0 ? string.substring(cursor +1).trim() : "";
if (cursor >= 0)
string = string.substring(0, cursor);
// Die Auswertung der Filter erfolgt nach dem Auschlussprinzip.
// Dazu werden alle Regeln einer Zeile in einer Schleife einzeln
// geprueft und die Schleife mit der ersten nicht zutreffenden Regel
// verlassen. Somit wird das Ende der Schleife nur erreicht, wenn
// keine der Bedingungen versagt hat und damit alle zutreffen.
rules = new StringTokenizer(string, "[+]");
while (rules.hasMoreTokens()) {
// die Filterbeschreibung wird ermittelt
string = rules.nextToken().toLowerCase().trim();
words = new StringTokenizer(string);
// Methode und Bedingung muessen gesetzt sein
// mit Toleranz fuer [+] beim Konkatenieren leerer Bedingungen
if (words.countTokens() < 2)
continue;
// die Methode wird ermittelt
string = words.nextToken();
// die Methode wird auf Erfuellung geprueft
if (string.length() > 0 && !string.equals("all")
&& !string.equals(this.environment.get("request_method").toLowerCase()))
break;
// die Bedingung wird ermittelt
string = words.nextToken();
// die Pseudobedingung ALWAYS spricht immer an
if (!string.equals("always")) {
// die Filterkontrolle wird gesetzt, hierbei sind nur IS und
// NOT zulaessig, andere Werte sind nicht zulaessig
if (!string.equals("is") && !string.equals("not"))
break;
control = string.equals("is");
// Methode und Bedingung muessen gesetzt sein
if (words.countTokens() < 2)
break;
// Funktion und Parameter werden ermittelt
method = words.nextToken();
string = words.nextToken();
// der zu pruefende Wert wird ermittelt
string = this.environment.get(string);
valueA = string.toLowerCase();
valueB = Worker.textDecode(valueA);
// der zu pruefende Wert/Ausdruck wird ermittelt
string = words.hasMoreTokens() ? words.nextToken() : "";
if ((method.equals("starts")
&& control != (valueA.startsWith(string)
|| valueB.startsWith(string)))
|| (method.equals("contains")
&& control != (valueA.contains(string)
|| valueB.contains(string)))
|| (method.equals("equals")
&& control != (valueA.equals(string)
|| valueB.equals(string)))
|| (method.equals("ends")
&& control != (valueA.endsWith(string)
|| valueB.endsWith(string)))
|| (method.equals("match")
&& control != (valueA.matches(string)
|| valueB.matches(string)))
|| (method.equals("empty")
&& control != (valueA.length() <= 0)))
break;
if (rules.hasMoreTokens())
continue;
}
// die Anweisung wird ermittelt
string = Worker.cleanOptions(buffer);
// wurde ein Modul definiert, wird es optional im Hintergrund
// als Filter- oder Process-Modul ausgefuehrt, die Verarbeitung
// endet erst, wenn das Modul die Datenflusskontrolle veraendert
if (buffer.toUpperCase().contains("[M]") && string.length() > 0) {
control = this.control;
status = this.status;
this.environment.set("module_opts", buffer);
this.invoke(string, "filter");
if (this.control != control
|| this.status != status)
return this.resource;
continue;
}
// bei einer Weiterleitung (Redirect) wird STATUS 302 gesetzt
if (buffer.toUpperCase().contains("[R]") && string.length() > 0) {
this.environment.set("script_uri", string);
this.status = 302;
return location;
}
// Verweise auf Dateien oder Verzeichnisse werden diese als
// Location zurueckgegeben
if (string.length() > 0) {
file = Worker.fileCanonical(new File(buffer));
if (file != null && file.exists())
return file.getPath();
}
// sprechen alle Bedingungen an und es gibt keine spezielle
// Anweisung, wird der STATUS 403 gesetzt
this.status = 403;
return location;
}
}
return location;
}
/**
* Initialisiert die Connection, liest den Request, analysiert diesen und
* richtet die Connection in der Laufzeitumgebung entsprechen ein.
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private void initiate()
throws Exception {
ByteArrayOutputStream buffer;
Enumeration enumeration;
File file;
String entry;
String method;
String shadow;
String string;
StringTokenizer tokenizer;
Section section;
boolean connect;
boolean secure;
boolean virtual;
int count;
int cursor;
int digit;
int offset;
// der Datenpuffer wird zum Auslesen vom Header eingerichtet
buffer = new ByteArrayOutputStream(65535);
if ((this.accept instanceof SSLSocket))
try {this.fields.set("auth_cert", ((SSLSocket)this.accept).getSession().getPeerPrincipal().getName());
} catch (Throwable throwable) {
}
try {
// das SO-Timeout wird fuer den ServerSocket gesetzt
this.accept.setSoTimeout((int)this.timeout);
// die Datenstroeme werden eingerichtet
this.output = this.accept.getOutputStream();
this.input = this.accept.getInputStream();
// der Inputstream wird gepuffert
this.input = new BufferedInputStream(this.input, this.blocksize);
count = cursor = offset = 0;
// der Header vom Requests wird gelesen, tritt beim Zugriff auf die
// Datenstroeme ein Fehler auf, wird STATUS 400 gesetzt
while (true) {
if ((digit = this.input.read()) >= 0) {
// der Request wird auf kompletten Header geprueft
cursor = (digit == ((cursor % 2) == 0 ? 13 : 10)) ? cursor +1 : 0;
if (cursor > 0 && count > 0 && offset > 0 && buffer.size() > 0) {
string = new String(buffer.toByteArray(), offset, buffer.size() -offset);
offset = string.indexOf(':');
shadow = string.substring(offset < 0 ? string.length() : offset +1).trim();
string = string.substring(0, offset < 0 ? string.length() : offset).trim();
// entsprechend RFC 3875 (CGI/1.1-Spezifikation) werden
// alle Felder vom HTTP-Header als HTTP-Parameter zur
// Verfuegung gestellt, dazu wird das Zeichen - durch _
// ersetzt und allen Parametern das Praefix "http_"
// vorangestellt
string = ("http_").concat(string.replace('-', '_'));
if (!this.fields.contains(string)
&& string.length() > 0
&& shadow.length() > 0)
this.fields.set(string, shadow);
offset = buffer.size();
}
// die Feldlaenge wird berechnet
count = cursor > 0 ? 0 : count +1;
if (count == 1) offset = buffer.size();
// die Zeile eines Felds vom Header muss sich mit 8-Bit
// addressieren lassen (fehlende Regelung im RFC 1945/2616)
if (count > 32768) this.status = 413;
// die Daten werden gespeichert
buffer.write(digit);
// der Header des Request wird auf 65535 Bytes begrenzt
if (buffer.size() >= 65535
&& cursor < 4) {
this.status = 413;
break;
}
// der Request wird auf kompletter Header geprueft
if (cursor == 4)
break;
} else {
// der Datenstrom wird auf Ende geprueft
if (digit >= 0)
Thread.sleep(this.interrupt);
else break;
}
}
} catch (Throwable throwable) {
this.status = 400;
if (throwable instanceof SocketTimeoutException)
this.status = 408;
}
// der Header wird vorrangig fuer die Schnittstellen gesetzt
this.header = buffer.toString().trim();
// die zusaetzlichen Header-Felder werden vorrangig fuer Filter
// ermittelt und sind nicht Bestandteil vom (X)CGI, dafuer werden nur
// die relevanten Parameter wie Methode, Pfade und Query uebernommen
// die erste Zeile wird ermittelt
tokenizer = new StringTokenizer(this.header, "\r\n");
string = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : "";
this.fields.set("req_line", string);
// die Methode vom Request wird ermittelt
offset = string.indexOf(' ');
shadow = string.substring(0, offset < 0 ? string.length() : offset);
string = string.substring(offset < 0 ? string.length() : offset +1);
this.fields.set("req_method", shadow);
// ohne HTTP-Methode ist die Anfrage ungueltig, somit STATUS 400
if (this.status == 0
&& shadow.length() <= 0)
this.status = 400;
// Protokoll und Version vom Request werden ermittelt aber ignoriert
offset = string.lastIndexOf(' ');
string = string.substring(0, offset < 0 ? string.length() : offset);
// Pfad und Query vom Request werden ermittelt
offset = string.indexOf(' ');
string = string.substring(0, offset < 0 ? string.length() : offset);
this.fields.set("req_path", string);
// Pfad und Query vom Request werden ermittelt
offset = string.indexOf('?');
shadow = string.substring(offset < 0 ? string.length() : offset +1);
string = string.substring(0, offset < 0 ? string.length() : offset);
this.fields.set("req_query", shadow);
this.fields.set("req_uri", string);
// der Pfad wird dekodiert
shadow = Worker.textDecode(string);
// der Pfad wird ausgeglichen /abc/./def/../ghi/ -> /abc/ghi
string = Worker.fileNormalize(shadow);
if (shadow.endsWith("/") && !string.endsWith("/"))
string = string.concat("/");
this.fields.set("req_path", string);
// ist der Request nicht korrekt wird STATUS 400 gesetzt
// enthaelt der Request keinen Header wird STATUS 400 gesetzt
// enthaelt der Request kein gueltige Pfadangabe wird STATUS 400 gesetzt
if (this.status == 0
&& (!string.startsWith("/")
|| this.header.length() <= 0))
this.status = 400;
// der Host wird ohne Port ermittelt und verwendet
string = this.fields.get("http_host");
offset = string.indexOf(':');
string = string.substring(0, offset < 0 ? string.length() : offset);
while (string.endsWith("."))
string = string.substring(0, string.length() -1);
// ist kein Host im Request, wird die aktuelle Adresse verwendet
if (string.length() <= 0)
string = this.accept.getLocalAddress().getHostAddress();
this.fields.set("http_host", string);
// der Host wird zur Virtualisierung ermittelt
if (string.length() > 0) {
string = ("virtual:").concat(string);
section = this.initialize.get(string.concat(":ini"));
shadow = section.get("server").toLowerCase();
// die Optionen werden mit allen Vererbungen ermittelt bzw.
// erweitert wenn ein virtueller Host fuer den Server existiert
if ((" ").concat(shadow).concat(" ").contains((" ").concat(this.context.toLowerCase()).concat(" "))
|| shadow.length() <= 0) {
this.options.merge(section);
this.references.merge(this.initialize.get(string.concat(":ref")));
this.access.merge(this.initialize.get(string.concat(":acc")));
this.filters.merge(this.initialize.get(string.concat(":flt")));
this.environment.merge(this.initialize.get(string.concat(":env")));
this.interfaces.merge(this.initialize.get(string.concat(":cgi")));
}
// die zu verwendende Blockgroesse wird ermittelt
try {this.blocksize = Integer.parseInt(this.options.get("blocksize"));
} catch (Throwable throwable) {
this.blocksize = 65535;
}
if (this.blocksize <= 0)
this.blocksize = 65535;
string = this.options.get("timeout");
this.isolation = string.toUpperCase().contains("[S]") ? -1 : 0;
// das Timeout der Connection wird ermittelt
try {this.timeout = Long.parseLong(Worker.cleanOptions(string));
} catch (Throwable throwable) {
this.timeout = 0;
}
}
// das aktuelle Arbeitsverzeichnis wird ermittelt
file = Worker.fileCanonical(new File("."));
string = file != null ? file.getPath().replace('\\', '/') : ".";
if (string.endsWith("/"))
string = string.substring(0, string.length() -1);
// das Systemverzeichnis wird ermittelt
file = Worker.fileCanonical(new File(this.options.get("sysroot")));
this.sysroot = file != null ? file.getPath().replace('\\', '/') : string;
if (this.sysroot.endsWith("/"))
this.sysroot = this.sysroot.substring(0, this.sysroot.length() -1);
if (this.options.get("sysroot").length() <= 0)
this.sysroot = string;
// das Dokumentenverzeichnis wird ermittelt
file = Worker.fileCanonical(new File(this.options.get("docroot")));
this.docroot = file != null ? file.getPath().replace('\\', '/') : string;
if (this.docroot.endsWith("/"))
this.docroot = this.docroot.substring(0, this.docroot.length() -1);
if (this.options.get("docroot").length() <= 0)
this.docroot = string;
// die serverseitig festen Umgebungsvariablen werden gesetzt
this.environment.set("server_port", String.valueOf(this.accept.getLocalPort()));
this.environment.set("server_protocol", "HTTP/1.0");
this.environment.set("server_software", "Seanox-Devwex/#[ant:release-version] #[ant:release-date]");
this.environment.set("document_root", this.docroot);
// die Requestspezifischen Umgebungsvariablen werden gesetzt
this.environment.set("content_length", this.fields.get("http_content_length"));
this.environment.set("content_type", this.fields.get("http_content_type"));
this.environment.set("query_string", this.fields.get("req_query"));
this.environment.set("request", this.fields.get("req_line"));
this.environment.set("request_method", this.fields.get("req_method"));
this.environment.set("remote_addr", this.accept.getInetAddress().getHostAddress());
this.environment.set("remote_port", String.valueOf(this.accept.getPort()));
// die Unique-Id wird aus dem HashCode des Sockets, den Millisekunden
// sowie der verwendeten Portnummer ermittelt, die Laenge ist variabel
string = Long.toString(Math.abs(this.accept.hashCode()), 36);
string = string.concat(Long.toString(((Math.abs(System.currentTimeMillis()) *100000) +this.accept.getPort()), 36));
// die eindeutige Request-Id wird gesetzt
this.environment.set("unique_id", string.toUpperCase());
// der Path wird ermittelt
shadow = this.fields.get("req_path");
// die Umgebungsvariabeln werden entsprechend der Ressource gesetzt
this.environment.set("path_url", shadow);
this.environment.set("script_name", shadow);
this.environment.set("script_url", this.fields.get("req_uri"));
this.environment.set("path_context", "");
this.environment.set("path_info", "");
// REFERRENCE - Zur Ressource werden ggf. der virtuellen Pfad im Unix
// Fileformat (Slash) bzw. der reale Pfad, sowie optionale Parameter,
// Optionen und Verweise auf eine Authentication ermittelt.
this.resource = this.locate(shadow);
// Option [A] fuer eine absolute Referenz wird ermittelt
string = this.resource.toUpperCase();
digit = string.contains("[A]") ? 1 : 0;
digit |= string.contains("[M]") ? 2 : 0;
digit |= string.contains("[R]") ? 4 : 0;
digit |= string.contains("[C]") ? 8 : 0;
digit |= string.contains("[X]") ? 16 : 0;
virtual = (digit & 1) != 0;
connect = (digit & (2|4)) != 0;
// HINWEIS - Auch Module koennen die Option [R] besitzen, diese wird
// dann aber ignoriert, da die Weiterleitung zu Modulen nur ueber deren
// virtuellen Pfad erfolgt
if ((this.status == 0 || this.status == 404) && (digit & 8) != 0) this.status = 403;
if ((this.status == 0 || this.status == 404) && (digit & 2) != 0) this.status = 0;
if ((this.status == 0 || this.status == 404) && (digit & (2|4)) == 4) {
this.environment.set("script_uri", Worker.cleanOptions(this.resource));
this.status = 302;
}
// ggf. wird die Zugriffsbrechtigung geprueft
// unterstuetzt werden Basic- und Digest-Authentication
this.authorize(this.resource);
// die Request-Parameter (nur mit dem Praefix http_ und auth_) werden in
// die Umgebungsvariablen uebernommen
enumeration = this.fields.elements();
while (enumeration.hasMoreElements()) {
string = (String)enumeration.nextElement();
if (!string.startsWith("HTTP_")
&& !string.startsWith("AUTH_") )
continue;
this.environment.set(string, this.fields.get(string));
}
this.environment.set("remote_user", this.fields.get("auth_user"));
if (!connect)
this.resource = Worker.cleanOptions(this.resource);
if (this.resource.length() <= 0)
this.resource = this.docroot.concat(this.environment.get("path_url"));
// die Ressource wird als File eingerichtet
file = new File(this.resource);
// die Ressource wird syntaktisch geprueft, nicht real existierende
// Ressourcen sowie Abweichungen im kanonisch Pfad werden mit Status
// 404 quitiert (das schliesst die Bugs im Windows-Dateisystem / / und
// Punkt vorm Slash ein), die Gross- und Kleinschreibung wird in Windows
// ignoriert
if (!connect
&& this.status == 0) {
File canonical = Worker.fileCanonical(file);
if (!file.equals(canonical))
this.status = 404;
if (canonical != null)
file = canonical;
if (file.isDirectory()
&& file.list() == null)
this.status = 404;
this.resource = file.getPath();
}
if (file.isFile() && shadow.endsWith("/"))
shadow = shadow.substring(0, shadow.length() -1);
if (file.isDirectory() && !shadow.endsWith("/"))
shadow = shadow.concat("/");
// der HOST oder VIRTUAL HOST wird ermittelt
entry = this.fields.get("http_host");
if (entry.length() <= 0)
entry = this.accept.getLocalAddress().getHostAddress();
// die OPTION IDENTITY wird geprueft
if (this.options.get("identity").toLowerCase().equals("on"))
this.environment.set("server_name", entry);
// aus dem Schema wird die Verwendung vom Secure-Layer ermittelt
secure = this.socket instanceof javax.net.ssl.SSLServerSocket;
// die Location wird zusammengestellt
string = this.environment.get("server_port");
string = (!string.equals("80") && !secure || !string.equals("443") && secure) && string.length() > 0 ? (":").concat(string) : "";
string = (secure ? "https" : "http").concat("://").concat(entry).concat(string);
// die URI vom Skript wird komplementiert
if (this.status != 302)
this.environment.set("script_uri", string.concat(this.fields.get("req_path")));
// bei abweichendem Path wird die Location als Redirect eingerichtet
if (this.status == 0 && !this.environment.get("path_url").equals(shadow) && !virtual && !connect) {
this.environment.set("script_uri", string.concat(shadow));
this.status = 302;
}
// die aktuelle Referenz wird ermittelt
string = this.environment.get("script_uri");
string = Worker.fileNormalize(string);
// bezieht sich die Referenz auf ein Verzeichnis und der URI endet
// aber nicht auf "/" wird STATUS 302 gesetzt
if (file.isDirectory() && !string.endsWith("/")) {
this.environment.set("script_uri", string.concat("/"));
if (this.status == 0)
this.status = 302;
}
// DEFAULT, beim Aufruf von Verzeichnissen wird nach einer alternativ
// anzuzeigenden Datei gesucht, was intern wie ein Verweis funktioniert
if (file.isDirectory() && this.status == 0) {
// das Verzeichnis wird mit Slash abgeschlossen
if (!this.resource.endsWith("/"))
this.resource = this.resource.concat("/");
// die Defaultdateien werden ermittelt
tokenizer = new StringTokenizer(this.options.get("default").replace('\\', '/'));
while (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken();
if (string.length() <= 0
|| string.indexOf('/') >= 0
|| !new File(this.resource.concat(string)).isFile())
continue;
this.resource = this.resource.concat(string);
shadow = this.environment.get("path_context");
if (shadow.length() <= 0)
shadow = this.environment.get("path_url");
if (!shadow.endsWith("/"))
shadow = shadow.concat("/");
this.environment.set("script_name", shadow.concat(string));
break;
}
}
string = Worker.cleanOptions(this.resource);
this.environment.set("script_filename", string);
this.environment.set("path_translated", string);
// der Query String wird ermittelt
string = this.environment.get("query_string");
// der Query String wird die Request URI aufbereite
if (string.length() > 0) string = ("?").concat(string);
// die Request URI wird gesetzt
this.environment.set("request_uri", this.fields.get("req_uri").concat(string));
// die aktuelle HTTP-Methode wird ermittelt
string = this.environment.get("request_method").toLowerCase();
// METHODS, die zulaessigen Methoden werden ermittelt
shadow = (" ").concat(this.options.get("methods").toLowerCase()).concat(" ");
// die aktuelle Methode wird in der Liste der zulaessigen gesucht, ist
// nicht enthalten, wird STATUS 405 gesetzt, ausgenommen sind Module
// mit der Option [X], da an diese alle Methoden weitergereicht werden
if (((digit & (2 | 16)) != (2 | 16))
&& !shadow.contains((" ").concat(string).concat(" "))
&& this.status <= 0)
this.status = 405;
this.resource = this.filter();
string = Worker.cleanOptions(this.resource);
this.environment.set("script_filename", string);
this.environment.set("path_translated", string);
// handelt es sich bei der Ressource um ein Modul wird keine Zuweisung
// fuer das (X)CGI und den Mediatype vorgenommen
if (connect || this.resource.toUpperCase().contains("[M]")) {
this.mediatype = this.options.get("mediatype");
this.gateway = this.resource;
return;
}
if (this.status == 302)
return;
// die Dateierweiterung wird ermittelt
cursor = this.resource.lastIndexOf(".");
entry = cursor >= 0 ? this.resource.substring(cursor +1) : this.resource;
// CGI - zur Dateierweiterung wird ggf. eine Anwendung ermittelt
this.gateway = this.interfaces.get(entry);
if (this.gateway.length() > 0) {
cursor = this.gateway.indexOf('>');
// die zulaessigen Methoden werden ermittelt
method = this.gateway.substring(0, Math.max(0, cursor)).toLowerCase().trim();
// die eigentliche Anwendung ermittelt
if (cursor >= 0) this.gateway = this.gateway.substring(cursor +2).trim();
// die Variable GATEWAY-INTERFACE wird fuer das (X)CGI gesetzt
if (this.gateway.length() > 0) {
this.environment.set("gateway_interface", "CGI/1.1");
// die Methode wird geprueft, ob diese fuer das CGI zugelassen
// ist, wenn nicht zulaessig, wird STATUS 405 gesetzt
string = (" ").concat(this.environment.get("request_method")).concat(" ").toLowerCase();
shadow = (" ").concat(method).concat(" ");
if (method.length() > 0
&& !shadow.contains(string)
&& !shadow.contains(" all ")
&& this.status < 500
&& this.status != 302)
this.status = 405;
}
}
// der Mediatype wird ermittelt
this.mediatype = this.mediatypes.get(entry);
// kann dieser nicht festgelegt werden wird der Standardeintrag aus den
// Server Basisoptionen eingetragen
if (this.mediatype.length() <= 0) this.mediatype = this.options.get("mediatype");
// die vom Client unterstuetzten Mediatypes werden ermittelt
shadow = this.fields.get("http_accept");
if (shadow.length() > 0) {
// es wird geprueft ob der Client den Mediatype unterstuetzt,
// ist dies nicht der Fall, wird STATUS 406 gesetzt
tokenizer = new StringTokenizer(shadow.toLowerCase().replace(';', ','), ",");
while (this.status == 0) {
if (tokenizer.hasMoreTokens()) {
string = tokenizer.nextToken().trim();
if (string.equals(this.mediatype) || string.equals("*/*") || string.equals("*"))
break;
cursor = this.mediatype.indexOf("/");
if (cursor >= 0 && (string.equals(this.mediatype.substring(0, cursor +1).concat("*"))
|| string.equals(("*").concat(this.mediatype.substring(cursor)))))
break;
} else this.status = 406;
}
}
}
/**
* Erstellt den Basis-Header für einen Response und erweitert diesen um
* die optional übergebenen Parameter.
* @param status HTTP-Status
* @param header optionale Liste mit Parameter
* @return der erstellte Response-Header
*/
private String header(int status, String[] header) {
String string;
string = String.valueOf(status);
string = ("HTTP/1.0 ").concat(string).concat(" ").concat(Worker.cleanOptions(this.statuscodes.get(string))).trim();
if (this.options.get("identity").toLowerCase().equals("on"))
string = string.concat("\r\nServer: Seanox-Devwex/#[ant:release-version] #[ant:release-date]");
string = string.concat("\r\n").concat(Worker.dateFormat("'Date: 'E, dd MMM yyyy HH:mm:ss z", new Date(), "GMT"));
string = string.concat("\r\n").concat(String.join("\r\n", header));
return string.trim();
}
/**
* Erstellt ein Array mit den Umgebungsvariablen.
* Umgebungsvariablen ohne Wert werden nicht übernommen.
* @return die Umgebungsvariablen als Array
*/
private String[] getEnvironment() {
Enumeration enumeration;
List list;
StringTokenizer tokenizer;
String label;
String value;
int index;
list = new ArrayList();
// die Umgebungsvariablen werden ermittelt und uebernommen
enumeration = this.environment.elements();
while (enumeration.hasMoreElements()) {
label = (String)enumeration.nextElement();
value = this.environment.get(label);
if (value.length() <= 0)
continue;
value = label.concat("=").concat(value);
if (list.contains(value))
continue;
list.add(value);
}
// die Zeilen vom Header werden ermittelt
tokenizer = new StringTokenizer(this.header, "\r\n");
// die erste Zeile mit dem Request wird verworfen
if (tokenizer.hasMoreTokens())
tokenizer.nextToken();
while (tokenizer.hasMoreTokens()) {
value = tokenizer.nextToken();
index = value.indexOf(':');
if (index <= 0)
continue;
label = value.substring(0, index).trim();
value = value.substring(index +1).trim();
if (label.length() <= 0
|| value.length() <= 0)
continue;
label = ("http_").concat(label.replace('-', '_'));
value = label.toUpperCase().concat("=").concat(value);
if (list.contains(value))
continue;
list.add(value);
}
return (String[])list.toArray(new String[0]);
}
private void doGateway()
throws Exception {
InputStream error;
InputStream input;
OutputStream output;
Process process;
String shadow;
String header;
String string;
String[] environment;
byte[] bytes;
int cursor;
int length;
int offset;
long duration;
long size;
if (this.gateway.toUpperCase().contains("[M]")) {
// die Moduldefinition wird als Umgebungsvariablen gesetzt
this.environment.set("module_opts", this.gateway);
this.invoke(Worker.cleanOptions(this.gateway), "service");
return;
}
string = this.gateway;
shadow = this.environment.get("script_filename");
cursor = shadow.replace('\\', '/').lastIndexOf("/") +1;
string = string.replace("[d]", "[D]");
string = string.replace("[D]", shadow.substring(0, cursor));
string = string.replace("[c]", "[C]");
string = string.replace("[C]", shadow.replace((File.separator.equals("/")) ? '\\' : '/', File.separatorChar));
shadow = shadow.substring(cursor);
cursor = shadow.lastIndexOf(".");
string = string.replace("[n]", "[N]");
string = string.replace("[N]", shadow.substring(0, cursor < 0 ? shadow.length() : cursor));
string = Worker.cleanOptions(string);
// die maximale Prozesslaufzeit wird ermittelt
try {duration = Long.parseLong(this.options.get("duration"));
} catch (Throwable throwable) {
duration = 0;
}
// der zeitliche Verfall des Prozess wird ermittelt
if (duration > 0)
duration += System.currentTimeMillis();
// der Datenpuffer wird entsprechen der BLOCKSIZE eingerichtet
bytes = new byte[this.blocksize];
// initiale Einrichtung der Variablen
environment = this.getEnvironment();
// der Prozess wird gestartet, Daten werden soweit ausgelesen
// bis der Prozess beendet wird oder ein Fehler auftritt
process = Runtime.getRuntime().exec(string.trim(), environment);
try {
input = process.getInputStream();
output = process.getOutputStream();
// der XCGI-Header wird aus den CGI-Umgebungsvariablen
// erstellt und vergleichbar dem Header ins StdIO geschrieben
if (this.gateway.toUpperCase().contains("[X]"))
output.write(String.join("\r\n", environment).trim().concat("\r\n\r\n").getBytes());
// die Laenge des Contents wird ermittelt
try {length = Integer.parseInt(this.fields.get("http_content_length"));
} catch (Throwable throwable) {
length = 0;
}
while (length > 0) {
// die Daten werden aus dem Datenstrom gelesen
size = this.input.read(bytes);
if (size < 0)
break;
// die an das CGI zu uebermittelnde Datenmenge wird auf die
// Menge von CONTENT-LENGHT begrenzt
if (size > length)
size = length;
// die Daten werden an das CGI uebergeben
output.write(bytes, 0, (int)size);
// das verbleibende Datenvolumen wird berechnet
length -= size;
// die maximale Prozesslaufzeit wird geprueft
if (duration > 0
&& duration < System.currentTimeMillis()) {
this.status = 504;
break;
}
Thread.sleep(this.interrupt);
}
// der Datenstrom wird geschlossen
if (process.isAlive())
output.close();
// der Prozess wird zwangsweise beendet um auch die Prozesse
// abzubrechen deren Verarbeitung fehlerhaft verlief
if (this.status != 200)
return;
// der Datenpuffer fuer den wird eingerichtet
header = new String();
// Responsedaten werden bis zum Ende der Anwendung gelesen
// dazu wird initial die Datenflusskontrolle gesetzt
while (true) {
// das Beenden der Connection wird geprueft
try {this.accept.getSoTimeout();
} catch (Throwable throwable) {
this.status = 503;
break;
}
if (input.available() > 0) {
// die Daten werden aus dem StdIO gelesen
length = input.read(bytes);
offset = 0;
// fuer die Analyse vom Header wird nur die erste Zeile
// vom CGI-Output ausgewertet, der Header selbst wird
// vom Server nicht geprueft oder manipuliert, lediglich
// die erste Zeile wird HTTP-konform aufbereitet
if (this.control && header != null) {
header = header.concat(new String(bytes, 0, length));
cursor = header.indexOf("\r\n\r\n");
if (cursor >= 0) {
offset = length -(header.length() -cursor -4);
header = header.substring(0, cursor);
} else offset = header.length();
// der Buffer zur Header-Analyse ist auf 65535 Bytes
// begrenzt, Ueberschreiten fuehrt zum STATUS 502
if (header.length() > 65535) {
this.status = 502;
break;
} else if (cursor >= 0) {
header = header.trim();
cursor = header.indexOf("\r\n");
string = cursor >= 0 ? header.substring(0, cursor).trim() : header;
shadow = string.toUpperCase();
if (shadow.startsWith("HTTP/")) {
if (shadow.matches("^HTTP/STATUS(\\s.*)*$"))
header = null;
try {this.status = Math.abs(Integer.parseInt(string.replaceAll("^(\\S+)\\s*(\\S+)*\\s*(.*?)\\s*$", "$2")));
} catch (Throwable throwable) {
}
// ggf. werden die Statuscodes mit eigenen bzw.
// unbekannten Codes und Text temporaer
// angereichert, mit dem Ende der Connection wird
// die Liste verworfen
string = string.replaceAll("^(\\S+)\\s*(\\S+)*\\s*(.*?)\\s*$", "$3");
if (string.length() > 0
&& !this.statuscodes.contains(String.valueOf(this.status)))
this.statuscodes.set(String.valueOf(this.status), string);
}
// beginnt der Response mit HTTP/STATUS, wird der
// Datenstrom ausgelesen, nicht aber an den Client
// weitergeleitet, die Beantwortung vom Request
// uebernimmt in diesem Fall der Server
if (header != null) {
header = header.replaceAll("(?si)^ *HTTP */ *[^\r\n]*([\r\n]+|$)", "");
header = this.header(this.status, header.split("[\r\n]+"));
this.control = false;
}
}
}
// die Daten werden nur in den Output geschrieben, wenn die
// Ausgabekontrolle gesetzt wurde und der Response nicht mit
// HTTP/STATUS beginnt
if (!this.control) {
// der Zeitpunkt wird registriert, um auf blockierte
// Datenstroeme reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
if (header != null)
this.output.write(header.concat("\r\n\r\n").getBytes());
header = null;
this.output.write(bytes, offset, length -offset);
if (this.isolation != 0)
this.isolation = -1;
this.volume += length -offset;
}
}
// die maximale Prozesslaufzeit wird geprueft
if (duration > 0
&& duration < System.currentTimeMillis()) {
this.status = 504;
break;
}
// der Datenstrom wird auf vorliegende Daten
// und der Prozess wird auf sein Ende geprueft
if (input.available() <= 0
&& !process.isAlive())
break;
Thread.sleep(this.interrupt);
}
} finally {
try {
string = new String();
error = process.getErrorStream();
while (error.available() > 0) {
length = error.read(bytes);
string = string.concat(new String(bytes, 0, length));
}
string = string.trim();
if (string.length() > 0)
Service.print(("GATEWAY ").concat(string));
} finally {
// der Prozess wird zwangsweise beendet um auch die Prozesse
// abzubrechen deren Verarbeitung fehlerhaft verlief
try {process.destroy();
} catch (Throwable throwable) {
}
}
}
}
/**
* Erstellt vom angeforderten Verzeichnisse auf Basis vom Template
* {@code index.html} eine navigierbare HTML-Seite.
* @param directory Verzeichnis des Dateisystems
* @param query Option der Sortierung
* @return das Verzeichnisse als navigierbares HTML
*/
private byte[] createDirectoryIndex(File directory, String query) {
Enumeration enumeration;
File file;
Generator generator;
Hashtable data;
Hashtable values;
List list;
List storage;
StringTokenizer tokenizer;
String entry;
String path;
String string;
File[] files;
String[] entries;
int[] assign;
boolean control;
boolean reverse;
int cursor;
int digit;
int loop;
values = new Hashtable();
// der Header wird mit den Umgebungsvariablen zusammengefasst,
// die serverseitig gesetzten haben dabei die hoehere Prioritaet
enumeration = this.environment.elements();
while (enumeration.hasMoreElements()) {
entry = (String)enumeration.nextElement();
if (entry.toLowerCase().equals("path")
|| entry.toLowerCase().equals("file"))
continue;
values.put(entry, this.environment.get(entry));
}
// die Zuordung der Felder fuer die Sortierung wird definiert
if (query.length() <= 0)
query = "n";
query = query.substring(0, 1);
digit = query.charAt(0);
reverse = digit >= 'A' && digit <= 'Z';
query = query.toLowerCase();
digit = query.charAt(0);
// case, name, date, size, type
assign = new int[] {0, 1, 2, 3, 4};
// die Sortierung wird durch die Query festgelegt und erfolgt nach
// Case, Query und Name, die Eintraege sind als Array abgelegt um eine
// einfache und flexible Zuordnung der Sortierreihenfolge zu erreichen
// 0 - case, 1 - name, 3 - date, 4 - size, 5 - type
if (digit == 'd') {
// case, date, name, size, type
assign = new int[] {0, 2, 1, 3, 4};
} else if (digit == 's') {
// case, size, name, date, type
assign = new int[] {0, 3, 1, 2, 4};
} else if (digit == 't') {
// case, type, name, date, size
assign = new int[] {0, 4, 1, 2, 3};
} else query = "n";
// das Standard-Template fuer den INDEX wird ermittelt und geladen
file = new File(this.sysroot.concat("/index.html"));
generator = Generator.parse(Worker.fileRead(file));
string = this.environment.get("path_url");
if (!string.endsWith("/"))
string = string.concat("/");
values.put("path_url", string);
// der Pfad wird fragmentiert, Verzeichnissstruktur koennen so als
// einzelne Links abgebildet werden
tokenizer = new StringTokenizer(string, "/");
for (path = ""; tokenizer.hasMoreTokens();) {
entry = tokenizer.nextToken();
path = path.concat("/").concat(entry);
values.put("path", path);
values.put("name", entry);
generator.set("location", values);
}
// die Dateiliste wird ermittelt
files = directory.listFiles();
if (files == null)
files = new File[0];
storage = new ArrayList(Arrays.asList(files));
// mit der Option [S] werden versteckte Dateien nicht angezeigt
control = this.options.get("index").toUpperCase().contains("[S]");
entries = new String[5];
// die Dateiinformationen werden zusammengestellt
for (loop = 0; loop < storage.size(); loop++) {
// die physiche Datei wird ermittlet
file = (File)storage.get(loop);
// die Eintraege werden als Array abgelegt um eine einfache und
// flexible Zuordnung der Sortierreihenfolge zu erreichen
// 0 - base, 1 - name, 2 - date, 3 - size, 4 - type
// der Basistyp wird ermittelt
entries[0] = file.isDirectory() ? "directory" : "file";
// der Name wird ermittelt
entries[1] = file.getName();
// der Zeitpunkt der letzten Aenderung wird ermittelt
entries[2] = String.format("%tF %<tT", new Date(file.lastModified()));
// die Groesse wird ermittelt, nicht aber bei Verzeichnissen
string = file.isDirectory() ? "-" : String.valueOf(file.length());
// die Groesse wird an der ersten Stelle mit dem Character erweitert
// welches sich aus der Laenge der Groesse ergibt um diese nach
// numerischer Groesse zu sortieren
entries[3] = String.valueOf((char)string.length()).concat(string);
// der Dateityp wird ermittlet, nicht aber bei Verzeichnissen
string = entries[1];
cursor = string.lastIndexOf(".");
string = cursor >= 0 ? string.substring(cursor +1) : "";
entries[4] = file.isDirectory() ? "-" : string.toLowerCase().trim();
// Dateien und Verzeichnisse der Option "versteckt" werden markiert
string = String.join("\00 ", new String[] {entries[assign[0]], entries[assign[1]],
entries[assign[2]], entries[assign[3]], entries[assign[4]]});
if (control && file.isHidden())
string = "";
storage.set(loop, string);
}
// die Dateiliste wird sortiert
Collections.sort(storage, String.CASE_INSENSITIVE_ORDER);
if (reverse)
Collections.reverse(storage);
list = new ArrayList();
// die Dateiinformationen werden zusammengestellt
for (loop = 0; loop < storage.size(); loop++) {
// nicht anerkannte Dateien werden unterdrueckt
tokenizer = new StringTokenizer((String)storage.get(loop), "\00");
if (tokenizer.countTokens() <= 0)
continue;
data = new Hashtable(values);
list.add(data);
// die Eintraege werden als Array abgelegt um eine einfache und
// flexible Zuordnung der Sortierreihenfolge zu erreichen
// 0 - base, 1 - name, 2 - date, 3 - size, 4 - type
entries[assign[0]] = tokenizer.nextToken();
entries[assign[1]] = tokenizer.nextToken().substring(1);
entries[assign[2]] = tokenizer.nextToken().substring(1);
entries[assign[3]] = tokenizer.nextToken().substring(1);
entries[assign[4]] = tokenizer.nextToken().substring(1);
data.put("case", entries[0]);
data.put("name", entries[1]);
data.put("date", entries[2]);
data.put("size", entries[3].substring(1));
data.put("type", entries[4]);
string = entries[4];
if (!string.equals("-")) {
string = this.mediatypes.get(string);
if (string.length() <= 0)
string = this.options.get("mediatype");
} else string = "";
data.put("mime", string);
}
query = query.concat(reverse ? "d" : "a");
if (list.size() <= 0)
query = query.concat(" x");
values.put("sort", query);
values.put("file", list);
generator.set(values);
return generator.extract();
}
private void doGet()
throws Exception {
File file;
InputStream input;
List header;
StringTokenizer tokenizer;
String method;
String string;
byte[] bytes;
long size;
long offset;
long limit;
header = new ArrayList();
// die Methode wird ermittelt
method = this.fields.get("req_method").toLowerCase();
// die Ressource wird eingerichtet
file = new File(this.resource);
if (file.isDirectory()) {
// die Option INDEX ON wird ueberprueft
// bei Verzeichnissen und der INDEX OFF wird STATUS 403 gesetzt
if (Worker.cleanOptions(this.options.get("index")).toLowerCase().equals("on")) {
header.add(("Content-Type: ").concat(this.mediatypes.get("html")));
bytes = new byte[0];
// die Verzeichnisstruktur wird bei METHOD:GET generiert
if (method.equals("get")) {
bytes = this.createDirectoryIndex(file, this.environment.get("query_string"));
header.add(("Content-Length: ").concat(String.valueOf(bytes.length)));
}
// der Header wird fuer die Ausgabe zusammengestellt
string = this.header(this.status, (String[])header.toArray(new String[0])).concat("\r\n\r\n");
// die Connection wird als verwendet gekennzeichnet
this.control = false;
// der Zeitpunkt wird registriert, um auf blockierte
// Datenstroeme reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
this.output.write(string.getBytes());
this.output.write(bytes);
if (this.isolation != 0)
this.isolation = -1;
this.volume += bytes.length;
return;
}
this.status = 403;
return;
}
// wenn vom Client uebermittelt, wird IF-(UN)MODIFIED-SINCE geprueft
// und bei (un)gueltiger Angabe STATUS 304/412 gesetzt
if (!Worker.fileIsModified(file, this.fields.get("http_if_modified_since"))) {
this.status = 304;
return;
}
if (this.fields.contains("http_if_unmodified_since")
&& Worker.fileIsModified(file, this.fields.get("http_if_unmodified_since"))) {
this.status = 412;
return;
}
offset = 0;
size = file.length();
limit = size;
// ggf. werden der partielle Datenbereich RANGE ermittelt
if (this.fields.contains("http_range")
&& size > 0) {
// mogeliche Header fuer den Range:
// Range: ...; bytes=500-999 ...
// ...; bytes=-999 ...
// ...; bytes=500- ...
string = this.fields.get("http_range").replace(';', '\n');
string = Section.parse(string).get("bytes");
if (string.matches("^(\\d+)*\\s*-\\s*(\\d+)*$")) {
tokenizer = new StringTokenizer(string, "-");
try {
offset = Long.parseLong(tokenizer.nextToken().trim());
if (tokenizer.hasMoreTokens()) {
limit = Long.parseLong(tokenizer.nextToken().trim());
} else if (string.startsWith("-")) {
if (offset > 0) {
limit = size -1;
offset = Math.max(0, size -offset);
} else limit = -1;
}
limit = Math.min(limit, size -1);
if (offset >= size) {
this.status = 416;
return;
}
if (offset <= limit) {
this.status = 206;
limit++;
} else {
offset = 0;
limit = size;
}
} catch (Throwable throwable) {
offset = 0;
size = file.length();
limit = size;
}
}
}
// der Header wird zusammengestellt
header.add(("Last-Modified: ").concat(Worker.dateFormat("E, dd MMM yyyy HH:mm:ss z", new Date(file.lastModified()), "GMT")));
header.add(("Content-Length: ").concat(String.valueOf(limit -offset)));
header.add(("Accept-Ranges: bytes"));
// wenn verfuegbar wird der Content-Type gesetzt
if (this.mediatype.length() > 0)
header.add(("Content-Type: ").concat(this.mediatype));
// ggf. wird der partielle Datenbereich gesetzt
if (this.status == 206)
header.add(("Content-Range: bytes ").concat(String.valueOf(offset)).concat("-").concat(String.valueOf(limit -1)).concat("/").concat(String.valueOf(size)));
// der Header wird fuer die Ausgabe zusammengestellt
string = this.header(this.status, (String[])header.toArray(new String[0])).concat("\r\n\r\n");
// die Connection wird als verwendet gekennzeichnet
this.control = false;
// der Zeitpunkt wird registriert, um auf blockierte Datenstroeme
// reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
this.output.write(string.getBytes());
if (this.isolation != 0)
this.isolation = -1;
if (method.equals("get")) {
// das ByteArray wird mit dem BLOCKSIZE eingerichtet
bytes = new byte[this.blocksize];
input = null;
try {
// der Datenstrom wird eingerichtet
input = new FileInputStream(this.resource);
// ggf. wird der partielle Datenbereich beruecksichtigt
input.skip(offset);
// der Datenstrom wird ausgelesen
while ((offset +this.volume < limit)
&& ((size = input.read(bytes)) >= 0)) {
if (this.status == 206 && (offset +this.volume +size > limit))
size = limit -(offset +this.volume);
// der Zeitpunkt wird registriert, um auf blockierte
// Datenstroeme reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
this.output.write(bytes, 0, Math.max(0, (int)size));
if (this.isolation != 0)
this.isolation = -1;
this.volume += size;
}
} finally {
// der Datenstrom wird geschlossen
try {input.close();
} catch (Throwable throwable) {
}
}
}
}
private void doPut()
throws Exception {
File file;
OutputStream output;
byte[] bytes;
long length;
long size;
// die Ressource wird eingerichtet
file = new File(this.resource);
// ohne CONTENT-LENGTH werden Verzeichnisse, sonst Dateien angelegt
if (!this.fields.contains("http_content_length")) {
// die Verzeichnisstruktur wird angelegt
// bei Fehlern wird STATUS 424 gesetzt
if (!(file.isDirectory() || file.mkdirs()))
this.status = 424;
// bei erfolgreicher Methode wird STATUS 201 gesetzt
if (this.status == 200
|| this.status == 404) {
this.fields.set("req_location", this.environment.get("script_uri"));
this.status = 201;
}
return;
}
// die Laenge des Contents wird ermittelt
try {length = Long.parseLong(this.fields.get("http_content_length"));
} catch (Throwable throwable) {
length = -1;
}
// die Methode setzt eine gueltige Dateilaenge voraus, ohne gueltige
// Dateilaenge wird STATUS 411 gesetzt
if (length < 0) {
this.status = 411;
return;
}
// ggf. bestehende Dateien werden entfernt
file.delete();
// das Datenpuffer wird eingerichtet
bytes = new byte[this.blocksize];
output = null;
try {
// der Datenstrom wird eingerichtet
output = new FileOutputStream(this.resource);
while (length > 0) {
// die Daten werden aus dem Datenstrom gelesen
if ((size = this.input.read(bytes)) < 0)
break;
// die zu schreibende Datenmenge wird ermittelt
// CONTENT-LENGHT wird dabei nicht ueberschritten
size = Math.min(size, length);
// die Daten werden geschrieben
output.write(bytes, 0, (int)size);
// das verbleibende Datenvolumen wird berechnet
length -= size;
Thread.sleep(this.interrupt);
}
// kann die Datei nicht oder durch Timeout nur unvollstaendig
// angelegt werden wird STATUS 424 gesetzt
if (length > 0)
this.status = 424;
} finally {
// der Datenstrom wird geschlossen
try {output.close();
} catch (Throwable throwable) {
}
}
// bei erfolgreicher Methode wird STATUS 201 gesetzt
if (this.status == 200
|| this.status == 404) {
this.fields.set("req_location", this.environment.get("script_uri"));
this.status = 201;
}
}
private void doDelete() {
// die angeforderte Ressource wird komplett geloescht,
// tritt dabei ein Fehler auf wird STATUS 424 gesetzt
if (Worker.fileDelete(new File(this.resource)))
return;
this.status = 424;
}
private void doStatus()
throws Exception {
Enumeration enumeration;
Generator generator;
Hashtable elements;
List header;
String method;
String string;
String shadow;
byte[] bytes;
header = new ArrayList();
// die Methode wird ermittelt
method = this.fields.get("req_method").toLowerCase();
if (method.equals("options")
&& (this.status == 302 || this.status == 404))
this.status = 200;
if (this.status == 302) {
// die LOCATION wird fuer die Weiterleitung ermittelt
string = this.environment.get("query_string");
if (string.length() > 0)
string = ("?").concat(string);
string = this.environment.get("script_uri").concat(string);
this.fields.set("req_location", string);
} else {
string = String.valueOf(this.status);
// das Template fuer den Server Status wird ermittelt
this.resource = this.sysroot.concat("/status-").concat(string).concat(".html");
if (!new File(this.resource).exists())
this.resource = this.sysroot.concat("/status-").concat(string.substring(0, 1)).concat("xx.html");
if (!new File(this.resource).exists())
this.resource = this.sysroot.concat("/status.html");
}
// der Typ zur Autorisierung wird wenn vorhanden ermittelt
shadow = this.fields.get("auth_type");
if (this.status == 401 && shadow.length() > 0) {
string = (" realm=\"").concat(this.fields.get("auth_realm")).concat("\"");
if (shadow.equals("Digest")) {
string = ("Digest").concat(string);
string = string.concat(", qop=\"auth\"");
shadow = this.environment.get("unique_id");
string = string.concat(", nonce=\"").concat(shadow).concat("\"");
shadow = Worker.textHash(shadow.concat(String.valueOf(shadow.hashCode())));
string = string.concat(", opaque=\"").concat(shadow).concat("\"");
string = string.concat(", algorithm=\"MD5\"");
} else string = ("Basic").concat(string);
header.add(("WWW-Authenticate: ").concat(string));
}
if (this.fields.contains("req_location"))
header.add(("Location: ").concat(this.fields.get("req_location")));
// der Generator wird eingerichtet, dabei werden fuer die STATUS
// Klasse 1xx, den STATUS 302 (Redirection), 200 (Success) sowie die
// METHOD:HEAD/METHOD:OPTIONS keine Templates verwendet
string = String.valueOf(this.status);
string = this.statuscodes.get(string);
generator = Generator.parse(method.equals("head")
|| method.equals("options")
|| string.toUpperCase().contains("[H]") ? null : Worker.fileRead(new File(this.resource)));
// der Header wird mit den Umgebungsvariablen zusammengefasst,
// die serverseitig gesetzten haben dabei die hoehere Prioritaet
elements = new Hashtable();
enumeration = this.fields.elements();
while (enumeration.hasMoreElements()) {
string = (String)enumeration.nextElement();
elements.put(string, this.fields.get(string));
}
enumeration = this.environment.elements();
while (enumeration.hasMoreElements()) {
string = (String)enumeration.nextElement();
elements.put(string, this.environment.get(string));
}
string = String.valueOf(this.status);
elements.put("HTTP_STATUS", string);
elements.put("HTTP_STATUS_TEXT", Worker.cleanOptions(this.statuscodes.get(string)));
// die allgemeinen Elemente werden gefuellt
generator.set(elements);
bytes = generator.extract();
// bei Bedarf wird im Header CONTENT-TYPE / CONTENT-LENGTH gesetzt
if (bytes.length > 0) {
header.add(("Content-Type: ").concat(this.mediatypes.get("html")));
header.add(("Content-Length: ").concat(String.valueOf(bytes.length)));
}
// die verfuegbaren Methoden werden ermittelt und zusammengestellt
string = String.join(", ", this.options.get("methods").split("\\s+"));
if (string.length() > 0)
header.add(("Allow: ").concat(string));
// der Header wird fuer die Ausgabe zusammengestellt
string = this.header(this.status, (String[])header.toArray(new String[0])).concat("\r\n\r\n");
// die Connection wird als verwendet gekennzeichnet
this.control = false;
// der Zeitpunkt wird registriert, um auf blockierte Datenstroeme
// reagieren zu koennen
if (this.isolation != 0)
this.isolation = System.currentTimeMillis();
// der Response wird ausgegeben
if (this.output != null) {
this.output.write(string.getBytes());
this.output.write(bytes);
}
// das Datenvolumen wird uebernommen
this.volume += bytes.length;
if (this.isolation != 0)
this.isolation = -1;
}
/**
* Nimmt den Request an und organisiert die Verarbeitung und Beantwortung.
* @throws Exception
* Im Fall nicht erwarteter Fehler
*/
private void service()
throws Exception {
File file;
String method;
try {
// die Connection wird initialisiert, um den Serverprozess nicht zu
// behindern wird die eigentliche Initialisierung der Connection erst mit
// laufendem Thread als asynchroner Prozess vorgenommen
try {this.initiate();
} catch (Exception exception) {
this.status = 500;
throw exception;
}
// die Ressource wird eingerichtet
file = new File(this.resource);
// die Ressource muss auf Modul, Datei oder Verzeichnis verweisen
if (this.status == 0) this.status = file.isDirectory() || file.isFile() || this.resource.toUpperCase().contains("[M]") ? 200 : 404;
if (this.control) {
// PROCESS/(X)CGI/MODULE - wird bei gueltiger Angabe ausgefuehrt
if (this.status == 200 && this.gateway.length() > 0) {
try {this.doGateway();
} catch (Exception exception) {
this.status = 502;
throw exception;
}
} else {
// die Methode wird ermittelt
method = this.fields.get("req_method").toLowerCase();
// vom Server werden die Methoden OPTIONS, HEAD, GET, PUT, DELETE
// unterstuetzt bei anderen Methoden wird STATUS 501 gesetzt
if (this.status == 200
&& !method.equals("options") && !method.equals("head") && !method.equals("get")
&& !method.equals("put") && !method.equals("delete"))
this.status = 501;
// METHOD:PUT - wird bei gueltiger Angabe ausgefuehrt
if (this.status == 200 && method.equals("head"))
try {this.doGet();
} catch (Exception exception) {
this.status = 500;
throw exception;
}
if (this.status == 200 && method.equals("get"))
try {this.doGet();
} catch (Exception exception) {
this.status = 500;
throw exception;
}
// METHOD:PUT - wird bei gueltiger Angabe ausgefuehrt
if ((this.status == 200 || this.status == 404) && method.equals("put"))
try {this.doPut();
} catch (Exception exception) {
this.status = 424;
throw exception;
}
// METHOD:DELETE - wird bei gueltiger Angabe ausgefuehrt
if (this.status == 200 && method.equals("delete"))
try {this.doDelete();
} catch (Exception exception) {
this.status = 424;
throw exception;
}
}
}
} finally {
// der Zeitpunkt evtl. blockierender Datenstroeme wird
// zurueckgesetzt
if (this.isolation != 0)
this.isolation = -1;
// STATUS/ERROR/METHOD:OPTIONS - wird ggf. ausgefuehrt
if (this.control)
try {this.doStatus();
} catch (IOException exception) {
}
}
}
/** Protokollierte den Zugriff im Protokollmedium. */
private void register()
throws Exception {
Enumeration source;
Generator generator;
Hashtable values;
OutputStream stream;
String format;
String output;
String string;
// der Client wird ermittelt
string = this.environment.get("remote_addr");
try {string = InetAddress.getByName(string).getHostName();
} catch (Throwable throwable) {
}
this.environment.set("remote_host", string);
this.environment.set("response_length", String.valueOf(this.volume));
this.environment.set("response_status", String.valueOf(this.status == 0 ? 500 : this.status));
synchronized (Worker.class) {
// das Format vom ACCESSLOG wird ermittelt
format = this.options.get("accesslog");
// Konvertierung der String-Formater-Syntax in Generator-Syntax
format = format.replaceAll("#", "#[0x23]");
format = format.replaceAll("%%", "#[0x25]");
format = format.replaceAll("%\\[", "#[");
format = format.replaceAll("%t", "%1\\$t");
// die Zeitsymbole werden aufgeloest
format = String.format(Locale.US, format, new Date());
// Format und Pfad werden am Zeichen > getrennt
if (format.contains(">")) {
output = format.split(">")[1].trim();
format = format.split(">")[0].trim();
} else output = "";
// ohne Format und/oder mit OFF wird kein Access-Log erstellt
if (format.length() <= 0
|| format.toLowerCase().equals("off"))
return;
values = new Hashtable();
source = this.environment.elements();
while (source.hasMoreElements()) {
string = (String)source.nextElement();
values.put(string, Worker.textEscape(this.environment.get(string)));
}
generator = Generator.parse(format.getBytes());
generator.set(values);
format = new String(generator.extract());
format = format.replaceAll("(?<=\\s)(''|\"\")((?=\\s)|$)", "-");
format = format.replaceAll("(\\s)((?=\\s)|$)", "$1-");
format = format.concat(System.lineSeparator());
generator = Generator.parse(output.getBytes());
generator.set(values);
output = new String(generator.extract());
output = output.replaceAll("(?<=\\s)(''|\"\")((?=\\s)|$)", "-");
output = output.replaceAll("(\\s)((?=\\s)|$)", "$1-").trim();
// wurde kein ACCESSLOG definiert wird in den StdIO,
// sonst in die entsprechende Datei geschrieben
if (output.length() > 0) {
stream = new FileOutputStream(output, true);
try {stream.write(format.getBytes());
} finally {
stream.close();
}
} else Service.print(format, true);
}
}
/**
* Merkt den Worker zum Schliessen vor, wenn diese in der naechsten Zeit
* nicht mehr verwendet wird. Der Zeitpunkt zum Bereinigen beträgt
* 250ms Leerlaufzeit nach der letzen Nutzung. Die Zeit wird über das
* SoTimeout vom ServerSocket definiert.
*/
void isolate() {
if (this.accept == null
&& this.socket != null)
this.socket = null;
}
/**
* Rückgabe {@code true}, wenn der Worker aktiv zur Verfügung
* steht und somit weiterhin Requests entgegen nehmen kann.
* @return {@code true}, wenn der Worker aktiv verfübar ist
*/
boolean available() {
// der Socket wird auf Blockaden geprueft und ggf. geschlossen
if (this.socket != null
&& this.isolation > 0
&& this.isolation < System.currentTimeMillis() -this.timeout)
this.destroy();
return this.socket != null && this.accept == null;
}
/** Beendet den Worker durch das Schliessen der Datenströme. */
void destroy() {
// der ServerSocket wird zurueckgesetzt
this.socket = null;
if (this.isolation != 0)
this.isolation = -1;
// der Socket wird geschlossen
try {this.accept.close();
} catch (Throwable throwable) {
}
}
@Override
public void run() {
ServerSocket socket;
String string;
// der ServerSocket wird vorgehalten
socket = this.socket;
while (this.socket != null) {
// initiale Einrichtung der Variablen
this.status = 0;
this.volume = 0;
this.control = true;
this.docroot = "";
this.gateway = "";
this.resource = "";
this.mediatype = "";
this.sysroot = "";
// die Felder vom Header werde eingerichtet
this.fields = new Section(true);
// die Konfigurationen wird geladen
this.access = (Section)this.initialize.get(this.context.concat(":acc")).clone();
this.environment = (Section)this.initialize.get(this.context.concat(":env")).clone();
this.filters = (Section)this.initialize.get(this.context.concat(":flt")).clone();
this.interfaces = (Section)this.initialize.get(this.context.concat(":cgi")).clone();
this.options = (Section)this.initialize.get(this.context.concat(":ini")).clone();
this.references = (Section)this.initialize.get(this.context.concat(":ref")).clone();
this.statuscodes = (Section)this.initialize.get("statuscodes").clone();
this.mediatypes = (Section)this.initialize.get("mediatypes").clone();
// die zu verwendende Blockgroesse wird ermittelt
try {this.blocksize = Integer.parseInt(this.options.get("blocksize"));
} catch (Throwable throwable) {
this.blocksize = 65535;
}
if (this.blocksize <= 0)
this.blocksize = 65535;
string = this.options.get("timeout");
this.isolation = string.toUpperCase().contains("[S]") ? -1 : 0;
// das Timeout der Connecton wird ermittelt
try {this.timeout = Long.parseLong(Worker.cleanOptions(string));
} catch (Throwable throwable) {
this.timeout = 0;
}
// die maximale Prozesslaufzeit wird gegebenfalls korrigiert
if (this.timeout < 0)
this.timeout = 0;
// der Interrupt wird ermittelt
try {this.interrupt = Long.parseLong(this.options.get("interrupt"));
} catch (Throwable throwable) {
this.interrupt = 10;
}
if (this.interrupt < 0)
this.interrupt = 10;
try {this.accept = socket.accept();
} catch (InterruptedIOException exception) {
continue;
} catch (IOException exception) {
break;
}
// der Request wird verarbeitet
try {this.service();
} catch (Throwable throwable) {
Service.print(throwable);
}
// die Connection wird beendet
try {this.destroy();
} catch (Throwable throwable) {
}
// HINWEIS - Beim Schliessen wird der ServerSocket verworfen, um
// die Connection von Aussen beenden zu koennen, intern wird
// diese daher nach dem Beenden neu gesetzt
// der Zugriff wird registriert
try {this.register();
} catch (Throwable throwable) {
Service.print(throwable);
}
// der Socket wird alternativ geschlossen
try {this.accept.close();
} catch (Throwable throwable) {
}
// durch das Zuruecksetzen wird die Connection ggf. reaktivert
this.socket = socket;
// der Socket wird verworfen
this.accept = null;
}
}
} | #0000 Review: Optimization and corrections
| sources/com/seanox/devwex/Worker.java | #0000 Review: Optimization and corrections | <ide><path>ources/com/seanox/devwex/Worker.java
<ide> * kompletter Abbruch.
<ide> *
<ide> * @author Seanox Software Solutions
<del> * @version 5.5.0 20220911
<add> * @version 5.5.0 20220912
<ide> */
<ide> class Worker implements Runnable {
<ide>
<ide> }
<ide>
<ide> /**
<del> * Erstellt zum String einen hexadezimalen MD5-Hash.
<del> * @param string zu dem der Hash erstellt werden soll
<del> * @return der erstellte hexadezimale MD5-Hash
<add> * Creates a hexadecimal MD5 hash for the string.
<add> * @param string for which the hash is to be created
<add> * @return the created hexadecimal MD5 hash
<ide> * @throws Exception
<del> * Im Fall nicht erwarteter Fehler
<add> * In case of unexpected errors
<ide> */
<ide> private static String textHash(String string)
<ide> throws Exception {
<ide> }
<ide>
<ide> /**
<del> * Maskiert im String die Steuerzeichen: BS, HT, LF, FF, CR, ', ", \ und
<del> * alle Zeichen ausserhalb vom ASCII-Bereich 0x20-0x7F.
<del> * Die Maskierung erfolgt per Slash:
<add> * Escapes the control characters in the string: BS, HT, LF, FF, CR, ', ", \
<add> * and characters outside the ASCII range 0x20-0x7F with a slash sequence:
<ide> * <ul>
<ide> * <li>Slash + ISO</li>
<del> * <li>Slash + drei Bytes oktal (0x80-0xFF)</li>
<del> * <li>Slash + vier Bytes hexadezimal (0x100-0xFFFF)</li>
<add> * <li>Slash + three bytes octal (0x80-0xFF)</li>
<add> * <li>Slash + four bytes hexadecimal (0x100-0xFFFF)</li>
<ide> * </ul>
<del> * @param string zu maskierender String
<del> * @return der String mit den ggf. maskierten Zeichen.
<add> * @param string string to be escaped
<add> * @return the string with escaped characters
<ide> */
<del> public static String textEscape(String string) {
<del>
<del> byte[] codex;
<del> byte[] codec;
<del> byte[] cache;
<del>
<del> int code;
<del> int count;
<del> int cursor;
<del> int length;
<del> int loop;
<add> private static String textEscape(String string) {
<ide>
<ide> if (string == null)
<ide> return null;
<del>
<del> length = string.length();
<del>
<del> cache = new byte[length *6];
<del>
<del> codex = ("\b\t\n\f\r\"'\\btnfr\"'\\").getBytes();
<del> codec = ("0123456789ABCDEF").getBytes();
<del>
<del> for (loop = count = 0; loop < length; loop++) {
<del>
<del> code = string.charAt(loop);
<del>
<del> cursor = Arrays.binarySearch(codex, (byte)code);
<add>
<add> int length = string.length();
<add>
<add> byte[] codex = ("\b\t\n\f\r\"'\\btnfr\"'\\").getBytes();
<add> byte[] codec = ("0123456789ABCDEF").getBytes();
<add> byte[] cache = new byte[length *6];
<add>
<add> int count = 0;
<add> for (int loop = 0; loop < length; loop++) {
<add>
<add> int code = string.charAt(loop);
<add>
<add> int cursor = Arrays.binarySearch(codex, (byte)code);
<ide> if (cursor >= 0 && cursor < 8) {
<ide> cache[count++] = '\\';
<ide> cache[count++] = codex[cursor +8];
<ide> } else cache[count++] = (byte)code;
<ide> }
<ide>
<del> return new String(Arrays.copyOfRange(cache, 0, count));
<add> return new String(cache, 0, count);
<ide> }
<ide>
<ide> /**
<del> * Dekodiert den String tolerant als URL und UTF-8.
<del> * Tolerant, da fehlerhafte kodierte Zeichenfolgen nicht direkt zum Fehler
<del> * f¨hren, sondern erhalten bleiben und die UTF-8 Kodierung optional
<del> * betrachtet wird.
<del> * @param string zu dekodierender String
<del> * @return der dekodierte String
<add> * Decodes URL and UTF-8 optionally encoded parts in a string. Non-compliant
<add> * sequences do cause an error, instead they remain as unknown encoding.
<add> * @param string String to be decoded
<add> * @return the decoded string
<ide> */
<ide> private static String textDecode(String string) {
<ide>
<del> byte[] bytes;
<del>
<del> boolean control;
<del>
<del> int code;
<del> int count;
<del> int length;
<del> int loop;
<del> int digit;
<del> int cursor;
<del>
<ide> if (string == null)
<ide> string = "";
<ide>
<del> // Datenpuffer wird eingerichtet
<del> length = string.length();
<del> bytes = new byte[length *2];
<del>
<del> for (loop = count = 0; loop < length; loop++) {
<del>
<del> // der ASCII Code wird ermittelt
<del> code = string.charAt(loop);
<del>
<add> // Part 1: URL decoding
<add> // Non-compliant sequences do cause an error, instead they remain as
<add> // unknown encoding
<add>
<add> int length = string.length();
<add>
<add> byte[] bytes = new byte[length *2];
<add>
<add> int count = 0;
<add> for (int loop = 0; loop < length; loop++) {
<add>
<add> // ASCII code is determined
<add> int code = string.charAt(loop);
<add>
<add> // Plus sign is converted to space.
<ide> if (code == 43)
<ide> code = 32;
<ide>
<del> // der Hexcode wird in das ASCII Zeichen umgesetzt
<add> // Hexadecimal sequences are converted to ASCII character
<ide> if (code == 37) {
<ide> loop += 2;
<ide> try {code = Integer.parseInt(string.substring(loop -1, loop +1), 16);
<ide> bytes[count++] = (byte)code;
<ide> }
<ide>
<add> // Part 2: UTF-8 decoding
<add> // Non-compliant sequences do cause an error, instead they remain as
<add> // unknown encoding
<add>
<ide> bytes = Arrays.copyOfRange(bytes, 0, count);
<ide> length = bytes.length;
<ide>
<del> cursor = 0;
<del> digit = 0;
<del>
<del> control = false;
<del>
<del> for (loop = count = 0; loop < length; loop++) {
<del>
<del> // der ASCII Code wird ermittelt
<del> code = bytes[loop] & 0xFF;
<add> int cursor = 0;
<add> int digit = 0;
<add>
<add> boolean control = false;
<add>
<add> for (int loop = count = 0; loop < length; loop++) {
<add>
<add> // ASCII code is determined
<add> int code = bytes[loop] & 0xFF;
<ide>
<ide> if (code >= 0xC0 && code <= 0xC3)
<ide> control = true;
<ide>
<del> // Decodierung der Bytes als UTF-8, das Muster 10xxxxxx
<del> // wird um die 6Bits erweitert
<add> // Decoding of the bytes as UTF-8.
<add> // The pattern 10xxxxxx is extended by the 6Bits
<ide> if ((code & 0xC0) == 0x80) {
<ide>
<ide> digit = (digit << 0x06) | (code & 0x3F);
<ide> digit = 0;
<ide> cursor = 0;
<ide>
<del> // 0xxxxxxx (7Bit/0Byte) werden direkt verwendet
<add> // 0xxxxxxx (7Bit/0Byte) are used directly
<ide> if (((code & 0x80) == 0x00) || !control) {
<ide> bytes[count++] = (byte)code;
<ide> control = false;
<ide> }
<ide>
<ide> /**
<del> * Liest die Datei einer Datei.
<del> * @param file zu lesende Datei
<del> * @return die gelesenen Daten, im Fehlerfall ein leeres Byte-Array
<add> * Reads the data of a file as a byte array.
<add> * In case of error null is returned.
<add> * @param file file to be read
<add> * @return the read data, in case of error {@code null}
<ide> */
<ide> private static byte[] fileRead(File file) {
<del>
<ide> try {return Files.readAllBytes(file.toPath());
<ide> } catch (Throwable throwable) {
<ide> return null;
<ide> }
<ide>
<ide> /**
<del> * Normalisiert den String eines Pfads und lösst ggf. existierende
<del> * Pfad-Direktiven auf und ändert das Backslash in Slash.
<del> * @param path zu normalisierender Pfad
<del> * @return der normalisierte Pfad
<add> * Normalizes the string of a path and resolves existing path directives if
<add> * necessary and changes the backslash to slash.
<add> * @param path Path to be normalized
<add> * @return the normalized path
<ide> */
<ide> private static String fileNormalize(String path) {
<del>
<del> String string;
<del> String stream;
<del>
<del> int cursor;
<del>
<del> // die Pfadangabe wird auf Slash umgestellt
<del> string = path.replace('\\', '/').trim();
<del>
<del> // mehrfache Slashs werden zusammengefasst
<del> while ((cursor = string.indexOf("//")) >= 0)
<add>
<add> // path is changed to slash
<add> String string = path.replace('\\', '/').trim();
<add>
<add> // multiple slashes are combined
<add> for (int cursor; (cursor = string.indexOf("//")) >= 0;)
<ide> string = string.substring(0, cursor).concat(string.substring(cursor +1));
<ide>
<del> // der Path wird ggf. ausgeglichen /abc/./def/../ghi -> /abc/ghi
<del> // der Path wird um "/." ausgeglichen
<add> // the path is compensated if necessary /abc/./def/../ghi -> /abc/ghi
<add> // in the path /. is compensated
<ide> if (string.endsWith("/."))
<ide> string = string.concat("/");
<ide>
<del> while ((cursor = string.indexOf("/./")) >= 0)
<add> for (int cursor; (cursor = string.indexOf("/./")) >= 0;)
<ide> string = string.substring(0, cursor).concat(string.substring(cursor +2));
<ide>
<del> // der String wird um "/.." ausgeglichen
<add> // in the path /.. is compensated
<ide> if (string.endsWith("/.."))
<ide> string = string.concat("/");
<ide>
<del> while ((cursor = string.indexOf("/../")) >= 0) {
<del>
<add> for (int cursor; (cursor = string.indexOf("/../")) >= 0;) {
<add>
<add> String stream;
<add>
<ide> stream = string.substring(cursor +3);
<ide> string = string.substring(0, cursor);
<ide>
<ide> string = string.substring(0, cursor).concat(stream);
<ide> }
<ide>
<del> // mehrfache Slashs werden zusammengefasst
<del> while ((cursor = string.indexOf("//")) >= 0)
<add> // multiple consecutive slashes are combined
<add> for (int cursor; (cursor = string.indexOf("//")) >= 0;)
<ide> string = string.substring(0, cursor).concat(string.substring(cursor +1));
<ide>
<ide> return string; |
|
Java | apache-2.0 | 9da79c144ba0a521247d73e21856eef7aa6e8ef0 | 0 | PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder | package org.pdxfinder.services.ds;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.neo4j.ogm.json.JSONArray;
import org.neo4j.ogm.json.JSONException;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.dao.DataProjection;
import org.pdxfinder.dao.OntologyTerm;
import org.pdxfinder.repositories.DataProjectionRepository;
import org.pdxfinder.services.dto.DrugSummaryDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.Long.parseLong;
/*
* Created by csaba on 19/01/2018.
*/
@Component
public class SearchDS {
private final static Logger log = LoggerFactory.getLogger(SearchDS.class);
private DataProjectionRepository dataProjectionRepository;
private boolean INITIALIZED = false;
private Set<ModelForQuery> models;
/*
* DYNAMIC FACETS
*/
private Map<String, String> cancerSystemMap = new HashMap<>();
//platform=> marker=> variant=>{set of model ids}
Map<String, Map<String, Map<String, Set<Long>>>> mutations = new HashMap<String, Map<String, Map<String, Set<Long>>>>();
//"drugname"=>"response"=>"set of model ids"
private Map<String, Map<String, Set<Long>>> modelDrugResponses = new HashMap<>();
private List<String> projectOptions = new ArrayList<>();
/*
* STATIC FACETS
*/
public static List<String> PATIENT_AGE_OPTIONS = Arrays.asList(
"0-9",
"10-19",
"20-29",
"30-39",
"40-49",
"50-59",
"60-69",
"70-79",
"80-89",
"90",
"Not Specified"
);
public static List<String> DATASOURCE_OPTIONS = Arrays.asList(
"JAX",
"IRCC-CRC",
"PDMR",
"PDXNet-HCI-BCM",
"PDXNet-MDAnderson",
"PDXNet-WUSTL",
"PDXNet-Wistar-MDAnderson-Penn",
"TRACE"
);
public static List<String> PATIENT_GENDERS = Arrays.asList(
"Male",
"Female",
"Not Specified"
);
public static List<String> CANCERS_BY_SYSTEM_OPTIONS = Arrays.asList(
"Breast Cancer",
"Cardiovascular Cancer",
"Connective and Soft Tissue Cancer",
"Digestive System Cancer",
"Endocrine Cancer",
"Eye Cancer",
"Head and Neck Cancer",
"Hematopoietic and Lymphoid System Cancer",
"Nervous System Cancer",
"Peritoneal and Retroperitoneal Cancer",
"Reproductive System Cancer",
"Respiratory Tract Cancer",
"Thoracic Cancer",
"Skin Cancer",
"Urinary System Cancer",
"Unclassified"
);
public static List<String> SAMPLE_TUMOR_TYPE_OPTIONS = Arrays.asList(
"Primary",
"Metastatic",
"Recurrent",
"Refractory",
"Not Specified"
);
public static List<String> DATA_AVAILABLE_OPTIONS = Arrays.asList(
"Gene Mutation",
"Dosing Studies",
"Patient Treatment"
);
/**
* Populate the complete set of models for searching when this object is instantiated
*/
public SearchDS(DataProjectionRepository dataProjectionRepository) {
Assert.notNull(dataProjectionRepository, "Data projection repository cannot be null");
this.dataProjectionRepository = dataProjectionRepository;
this.models = new HashSet<>();
}
void initialize() {
//this method loads the ModelForQuery Data Projection object and
initializeModels();
//loads the mutation map from Data Projection
initializeMutations();
//loads model drug response from Data Projection
initializeModelDrugResponses();
//loads projects
initializeAdditionalOptions();
List<String> padding = new ArrayList<>();
padding.add("NO DATA");
//
// Filter out all options that have no models for that option
//
PATIENT_AGE_OPTIONS = PATIENT_AGE_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getPatientAge)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
DATASOURCE_OPTIONS = DATASOURCE_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getDatasource)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
CANCERS_BY_SYSTEM_OPTIONS = CANCERS_BY_SYSTEM_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getCancerSystem)
.flatMap(Collection::stream)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
PATIENT_GENDERS = PATIENT_GENDERS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getPatientGender)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
SAMPLE_TUMOR_TYPE_OPTIONS = SAMPLE_TUMOR_TYPE_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getSampleTumorType)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
//PROJECT_OPTIONS =new ArrayList<>(models.stream().map(model -> model.getProjects()).flatMap(Collection::stream).collect(Collectors.toSet()));
INITIALIZED = true;
}
/**
* Recursively get all ancestors starting from the supplied ontology term
*
* @param t the starting term in the ontology
* @return a set of ontology terms corresponding to the ancestors of the term supplied
*/
public Set<OntologyTerm> getAllAncestors(OntologyTerm t) {
Set<OntologyTerm> retSet = new HashSet<>();
// Store this ontology term in the set
retSet.add(t);
// If this term has parent terms
if (t.getSubclassOf() != null && t.getSubclassOf().size() > 0) {
// For each parent term
for (OntologyTerm st : t.getSubclassOf()) {
// Recurse and add all ancestor terms to the set
retSet.addAll(getAllAncestors(st));
}
}
// Return the full set
return retSet;
}
public Set<ModelForQuery> getModels() {
synchronized (this){
if(! INITIALIZED ) {
initialize();
}
}
return models;
}
public void setModels(Set<ModelForQuery> models) {
this.models = models;
}
public List<String> getProjectOptions() {
return projectOptions;
}
/**
* This method loads the ModelForQuery Data Projection object and initializes the models
*/
void initializeModels() {
String modelJson = dataProjectionRepository.findByLabel("ModelForQuery").getValue();
try {
JSONArray jarray = new JSONArray(modelJson);
for (int i = 0; i < jarray.length(); i++) {
JSONObject j = jarray.getJSONObject(i);
ModelForQuery mfq = new ModelForQuery();
mfq.setModelId(parseLong(j.getString("modelId")));
mfq.setDatasource(j.getString("datasource"));
mfq.setExternalId(j.getString("externalId"));
mfq.setPatientAge(j.getString("patientAge"));
mfq.setPatientGender(j.getString("patientGender"));
if(j.has("patientEthnicity")){
mfq.setPatientEthnicity(j.getString("patientEthnicity"));
}
mfq.setSampleOriginTissue(j.getString("sampleOriginTissue"));
mfq.setSampleSampleSite(j.getString("sampleSampleSite"));
mfq.setSampleExtractionMethod(j.getString("sampleExtractionMethod"));
//mfq.setSampleClassification(j.getString("sampleClassification"));
mfq.setSampleTumorType(j.getString("sampleTumorType"));
mfq.setDiagnosis(j.getString("diagnosis"));
mfq.setMappedOntologyTerm(j.getString("mappedOntologyTerm"));
mfq.setTreatmentHistory(j.getString("treatmentHistory"));
JSONArray ja = j.getJSONArray("cancerSystem");
List<String> cancerSystem = new ArrayList<>();
for (int k = 0; k < ja.length(); k++) {
cancerSystem.add(ja.getString(k));
}
mfq.setCancerSystem(cancerSystem);
ja = j.getJSONArray("allOntologyTermAncestors");
Set<String> ancestors = new HashSet<>();
for (int k = 0; k < ja.length(); k++) {
ancestors.add(ja.getString(k));
}
mfq.setAllOntologyTermAncestors(ancestors);
if(j.has("dataAvailable")){
ja = j.getJSONArray("dataAvailable");
List<String> dataAvailable = new ArrayList<>();
for(int k=0; k<ja.length(); k++){
dataAvailable.add(ja.getString(k));
}
mfq.setDataAvailable(dataAvailable);
}
if(j.has("projects")){
ja = j.getJSONArray("projects");
for(int k = 0; k < ja.length(); k++){
mfq.addProject(ja.getString(k));
}
}
this.models.add(mfq);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
void initializeMutations(){
log.info("Initializing mutations");
String mut = dataProjectionRepository.findByLabel("PlatformMarkerVariantModel").getValue();
try{
ObjectMapper mapper = new ObjectMapper();
mutations = mapper.readValue(mut, new TypeReference<Map<String, Map<String, Map<String, Set<Long>>>>>(){});
//log.info("Lookup: "+mutations.get("TargetedNGS_MUT").get("RB1").get("N123D").toString());
}
catch(Exception e){
e.printStackTrace();
}
}
void initializeModelDrugResponses(){
log.info("Initializing model drug responses");
DataProjection dataProjection = dataProjectionRepository.findByLabel("ModelDrugData");
String responses = "{}";
if(dataProjection != null){
responses = dataProjection.getValue();
}
try{
ObjectMapper mapper = new ObjectMapper();
modelDrugResponses = mapper.readValue(responses, new TypeReference<Map<String, Map<String, Set<Long>>>>(){});
//log.info("Lookup: "+modelDrugResponses.get("doxorubicincyclophosphamide").get("progressive disease").toString());
}
catch(Exception e){
e.printStackTrace();
}
}
/**
* Takes a marker and a variant. Looks up these variants in mutation.
* Then creates a hashmap with modelids as keys and platform+marker+mutation as values
*
*
* @param marker
* @param variant
* @return
*/
private void getModelsByMutatedMarkerAndVariant(String marker, String variant, Map<Long, Set<String>> previouslyFoundModels){
//platform=> marker=> variant=>{set of model ids}
//marker with ALL variants
if(variant.toLowerCase().equals("all")){
for(Map.Entry<String, Map<String, Map<String, Set<Long>>>> platformEntry : mutations.entrySet()){
String platformName = platformEntry.getKey();
if(platformEntry.getValue().containsKey(marker)){
for(Map.Entry<String, Set<Long>> markerVariants : platformEntry.getValue().get(marker).entrySet()){
String variantName = markerVariants.getKey();
Set<Long> foundModels = markerVariants.getValue();
for(Long modelId : foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(platformName+" "+marker+" "+variantName);
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(platformName+" "+marker+" "+variantName);
previouslyFoundModels.put(modelId, newSet);
}
}
}
}
}
}
//a marker and a variant is given
else{
for(Map.Entry<String, Map<String, Map<String, Set<Long>>>> platformEntry : mutations.entrySet()){
String platformName = platformEntry.getKey();
if(platformEntry.getValue().containsKey(marker)){
if(platformEntry.getValue().get(marker).containsKey(variant)){
Set<Long> foundModels = platformEntry.getValue().get(marker).get(variant);
for(Long modelId : foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(platformName+" "+marker+" "+variant);
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(platformName+" "+marker+" "+variant);
previouslyFoundModels.put(modelId, newSet);
}
}
}
}
}
}
}
private void getModelsByDrugAndResponse(String drug, String response, Map<Long, Set<String>> previouslyFoundModels,
Map<Long, List<DrugSummaryDTO>> modelsDrugSummary){
//drug => response => set of model ids
//Cases
//1. drug + no response selected
//2. drug + ALL response
//3. drug + one response selected
//4. no drug + one response selected
//5. no drug + ALL response
//1. = 2.
if(drug != null && response.toLowerCase().equals("all")){
if(modelDrugResponses.containsKey(drug)){
for(Map.Entry<String, Set<Long>> currResp: modelDrugResponses.get(drug).entrySet()){
String resp = currResp.getKey();
Set<Long> foundModels = currResp.getValue();
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drug+" "+response);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, resp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, resp));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drug+" "+response);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, resp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, resp));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
//3.
else if(drug != null && response != null){
if(modelDrugResponses.containsKey(drug)){
if(modelDrugResponses.get(drug).containsKey(response)){
Set<Long> foundModels = modelDrugResponses.get(drug).get(response);
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drug+" "+response);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, response));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drug+" "+response);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, response));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
//4. 5.
else if(drug == null && response != null){
if(response.equals("ALL")){
for(Map.Entry<String, Map<String, Set<Long>>> currDrug: modelDrugResponses.entrySet()){
String drugName = currDrug.getKey();
for(Map.Entry<String, Set<Long>> responses : currDrug.getValue().entrySet()){
String currResp = responses.getKey();
Set<Long> foundModels = responses.getValue();
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drugName+" "+currResp);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, currResp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, currResp));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drugName+" "+currResp);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, currResp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, currResp));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
else{
for(Map.Entry<String, Map<String, Set<Long>>> drugs : modelDrugResponses.entrySet()){
String drugName = drugs.getKey();
if(drugs.getValue().containsKey(response)){
Set<Long> foundModels = drugs.getValue().get(response);
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drugName+" "+response);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, response));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drugName+" "+response);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, response));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
}
}
public void initializeAdditionalOptions(){
log.info("Models: "+models.size());
Set<String> projectsSet = new HashSet<>();
for(ModelForQuery mfk : models){
if(mfk.getProjects() != null){
for(String s: mfk.getProjects()){
projectsSet.add(s);
}
}
}
projectOptions = new ArrayList<>(projectsSet);
}
/**
* Search function accespts a Map of key value pairs
* key = what facet to search
* list of values = what values to filter on (using OR)
* <p>
* EX of expected data structure:
* <p>
* patient_age -> { 5-10, 20-40 },
* patient_gender -> { Male },
* sample_origin_tissue -> { Lung, Liver }
* <p>
* would yield results for male patients between 5-10 OR between 20-40 AND that had cancers in the lung OR liver
*
* @param filters
* @return set of models derived from filtering the complete set according to the
* filters passed in as arguments
*/
public Set<ModelForQuery> search(Map<SearchFacetName, List<String>> filters) {
synchronized (this){
if(! INITIALIZED ) {
initialize();
}
}
Set<ModelForQuery> result = new HashSet<>(models);
//empty previously set variants
result.forEach(x -> x.setMutatedVariants(new ArrayList<>()));
//empty previously set drugs
result.forEach(x -> x.setDrugData(new ArrayList<>()));
// If no filters have been specified, return the complete set
if (filters == null) {
return result;
}
for (SearchFacetName facet : filters.keySet()) {
Predicate predicate;
switch (facet) {
case query:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.query));
Set<ModelForQuery> accumulate = new HashSet<>();
for (ModelForQuery r : result) {
Set<String> i = r.getAllOntologyTermAncestors().stream().filter(x -> predicate.test(x)).collect(Collectors.toSet());
if (i != null && i.size() > 0) {
r.setQueryMatch(i);
accumulate.add(r);
}
}
result = accumulate;
break;
case datasource:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.datasource));
result = result.stream().filter(x -> predicate.test(x.getDatasource())).collect(Collectors.toSet());
break;
case diagnosis:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.diagnosis));
result = result.stream().filter(x -> predicate.test(x.getMappedOntologyTerm())).collect(Collectors.toSet());
break;
case patient_age:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.patient_age));
result = result.stream().filter(x -> predicate.test(x.getPatientAge())).collect(Collectors.toSet());
break;
case patient_treatment_status:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.patient_treatment_status));
result = result.stream().filter(x -> predicate.test(x.getPatientTreatmentStatus())).collect(Collectors.toSet());
break;
case patient_gender:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.patient_gender));
result = result.stream().filter(x -> predicate.test(x.getPatientGender())).collect(Collectors.toSet());
break;
case sample_origin_tissue:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.sample_origin_tissue));
result = result.stream().filter(x -> predicate.test(x.getSampleOriginTissue())).collect(Collectors.toSet());
break;
case sample_classification:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.sample_classification));
result = result.stream().filter(x -> predicate.test(x.getSampleClassification())).collect(Collectors.toSet());
break;
case sample_tumor_type:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.sample_tumor_type));
result = result.stream().filter(x -> predicate.test(x.getSampleTumorType())).collect(Collectors.toSet());
break;
case model_implantation_site:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.model_implantation_site));
result = result.stream().filter(x -> predicate.test(x.getModelImplantationSite())).collect(Collectors.toSet());
break;
case model_implantation_type:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.model_implantation_type));
result = result.stream().filter(x -> predicate.test(x.getModelImplantationType())).collect(Collectors.toSet());
break;
case model_host_strain:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.model_host_strain));
result = result.stream().filter(x -> predicate.test(x.getModelHostStrain())).collect(Collectors.toSet());
break;
case cancer_system:
Set<ModelForQuery> toRemove = new HashSet<>();
for (ModelForQuery res : result) {
Boolean keep = Boolean.FALSE;
for (String s : filters.get(SearchFacetName.cancer_system)) {
if (res.getCancerSystem().contains(s)) {
keep = Boolean.TRUE;
}
}
if (!keep) {
toRemove.add(res);
}
}
result.removeAll(toRemove);
break;
case organ:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.organ));
result = result.stream().filter(x -> predicate.test(x.getCancerOrgan())).collect(Collectors.toSet());
break;
case cell_type:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.cell_type));
result = result.stream().filter(x -> predicate.test(x.getCancerCellType())).collect(Collectors.toSet());
break;
case mutation:
// mutation=KRAS___MUT___V600E, mutation=NRAS___WT
// if the String has ___ (three underscores) twice, it is mutated, if it has only one, it is WT
Map<Long, Set<String>> modelsWithMutatedMarkerAndVariant = new HashMap<>();
for(String mutation: filters.get(SearchFacetName.mutation)){
if(mutation.split("___").length == 3){
String[] mut = mutation.split("___");
String marker = mut[0];
String variant = mut[2];
getModelsByMutatedMarkerAndVariant(marker, variant, modelsWithMutatedMarkerAndVariant);
}
else if(mutation.split("___").length == 2){
//TODO: add wt lookup when we have data
}
}
// applies the mutation filters
result = result.stream().filter(x -> modelsWithMutatedMarkerAndVariant.containsKey(x.getModelId())).collect(Collectors.toSet());
// updates the remaining modelforquery objects with platform+marker+variant info
result.forEach(x -> x.setMutatedVariants(new ArrayList<>(modelsWithMutatedMarkerAndVariant.get(x.getModelId()))));
break;
case drug:
Map<Long, Set<String>> modelsWithDrug = new HashMap<>();
Map<Long, List<DrugSummaryDTO>> modelsDrugSummary = new HashMap<>();
for(String filt : filters.get(SearchFacetName.drug)){
String[] drugAndResponse = filt.split("___");
String drug = drugAndResponse[0];
String response = drugAndResponse[1];
if(drug.isEmpty()) drug = null;
getModelsByDrugAndResponse(drug,response, modelsWithDrug, modelsDrugSummary);
}
result = result.stream().filter(x -> modelsWithDrug.containsKey(x.getModelId())).collect(Collectors.toSet());
// updates the remaining modelforquery objects with drug and response info
//result.forEach(x -> x.setMutatedVariants(new ArrayList<>(modelsWithDrug.get(x.getModelId()))));
result.forEach(x -> x.setDrugData(modelsDrugSummary.get(x.getModelId())));
break;
case project:
Set<ModelForQuery> projectsToRemove = new HashSet<>();
for (ModelForQuery res : result) {
Boolean keep = Boolean.FALSE;
for (String s : filters.get(SearchFacetName.project)) {
try{
if (res.getProjects() != null && res.getProjects().contains(s)) {
keep = Boolean.TRUE;
}
} catch(Exception e){
e.printStackTrace();
}
}
if (!keep) {
projectsToRemove.add(res);
}
}
result.removeAll(projectsToRemove);
break;
case data_available:
Set<ModelForQuery> mfqToRemove = new HashSet<>();
for (ModelForQuery res : result) {
Boolean keep = Boolean.FALSE;
for (String s : filters.get(SearchFacetName.data_available)) {
try{
if (res.getDataAvailable() != null && res.getDataAvailable().contains(s)) {
keep = Boolean.TRUE;
}
} catch(Exception e){
e.printStackTrace();
}
}
if (!keep) {
mfqToRemove.add(res);
}
}
result.removeAll(mfqToRemove);
break;
default:
// default case is an unexpected filter option
// Do not filter anything
log.info("Unrecognised facet {} passed to search, skipping.", facet);
break;
}
}
return result;
}
/**
* getExactMatchDisjunctionPredicate returns a composed predicate with all the supplied filters "OR"ed together
* using an exact match
* <p>
* NOTE: This is a case sensitive match!
*
* @param filters the set of strings to match against
* @return a composed predicate case insensitive matching the supplied filters using disjunction (OR)
*/
Predicate<String> getExactMatchDisjunctionPredicate(List<String> filters) {
List<Predicate<String>> preds = new ArrayList<>();
// Iterate through the filter options passed in for this facet
for (String filter : filters) {
// Create a filter predicate for each option
Predicate<String> pred = s -> s.equals(filter);
// Store all filter options in a list
preds.add(pred);
}
// Create a "combination" predicate containing sub-predicates "OR"ed together
return preds.stream().reduce(Predicate::or).orElse(x -> false);
}
/**
* getContainsMatchDisjunctionPredicate returns a composed predicate with all the supplied filters "OR"ed together
* using a contains match
* <p>
* NOTE: This is a case insensitive match!
*
* @param filters the set of strings to match against
* @return a composed predicate case insensitive matching the supplied filters using disjunction (OR)
*/
Predicate<String> getContainsMatchDisjunctionPredicate(List<String> filters) {
List<Predicate<String>> preds = new ArrayList<>();
// Iterate through the filter options passed in for this facet
for (String filter : filters) {
// Create a filter predicate for each option
Predicate<String> pred = s -> s.toLowerCase().contains(filter.toLowerCase());
// Store all filter options in a list
preds.add(pred);
}
// Create a "combination" predicate containing sub-predicates "OR"ed together
return preds.stream().reduce(Predicate::or).orElse(x -> false);
}
public List<FacetOption> getFacetOptions(SearchFacetName facet,List<String> options, Map<SearchFacetName, List<String>> configuredFacets){
List<FacetOption> facetOptions = new ArrayList<>();
for(String s : options){
FacetOption fo = new FacetOption(s, 0);
fo.setSelected(false);
facetOptions.add(fo);
}
if(configuredFacets.containsKey(facet)){
List<String> selectedFacets = configuredFacets.get(facet);
for(String sf : selectedFacets){
for(FacetOption fo : facetOptions){
if(fo.getName().equals(sf)){
fo.setSelected(true);
}
}
}
}
return facetOptions;
}
/**
* Get the count of models for a supplied facet.
* <p>
* This method will return counts of facet options for the supplied facet
*
* @param facet the facet to count
* @param results set of models already filtered
* @param selected what facets have been filtered already
* @return a list of {@link FacetOption} indicating counts and selected state
*/
@Cacheable("facet_counts")
public List<FacetOption> getFacetOptions(SearchFacetName facet, List<String> options, Set<ModelForQuery> results, List<String> selected) {
Set<ModelForQuery> allResults = models;
List<FacetOption> map = new ArrayList<>();
// Initialise all facet option counts to 0 and set selected attribute on all options that the user has chosen
if (options != null) {
for (String option : options) {
Long count = allResults
.stream()
.filter(x ->
Stream.of(x.getBy(facet).split("::"))
.collect(Collectors.toSet())
.contains(option))
.count();
map.add(new FacetOption(option, selected != null ? 0 : count.intValue(), count.intValue(), selected != null && selected.contains(option) ? Boolean.TRUE : Boolean.FALSE, facet));
}
}
// We want the counts on the facets to look something like:
// Gender
// [ ] Male (1005 of 1005)
// [ ] Female (840 of 840)
// [ ] Not specified (31 of 31)
// Then when a facet is clicked:
// Gender
// [X] Male (1005 of (1005)
// [ ] Female (0 of 840)
// [ ] Not specified (2 of 31)
//
// Iterate through results adding count to the appropriate option
for (ModelForQuery mfq : results) {
String s = mfq.getBy(facet);
// Skip empty facets
if (s == null || s.equals("")) {
continue;
}
// List of ontology terms may come from the service. These will by separated by "::" delimiter
if (s.contains("::")) {
for (String ss : s.split("::")) {
// There should be only one element per facet name
map.forEach(x -> {
if (x.getName().equals(ss)) {
x.increment();
}
});
}
} else {
// Initialise on the first time we see this facet name
if (map.stream().noneMatch(x -> x.getName().equals(s))) {
map.add(new FacetOption(s, 0, 0, selected != null && selected.contains(s) ? Boolean.TRUE : Boolean.FALSE, facet));
}
// There should be only one element per facet name
map.forEach(x -> {
if (x.getName().equals(s)) {
x.increment();
}
});
}
}
// Collections.sort(map);
return map;
}
/**
* Get the count of models for each diagnosis (including children).
* <p>
* This method will return counts of facet options for the supplied facet
*
* @return a Map of k: diagnosis v: count
*/
@Cacheable("diagnosis_counts")
public Map<String, Integer> getDiagnosisCounts() {
Set<ModelForQuery> allResults = models;
Map<String, Integer> map = new HashMap<>();
// Get the list of diagnoses
Set<String> allDiagnoses = allResults.stream().map(ModelForQuery::getMappedOntologyTerm).collect(Collectors.toSet());
// For each diagnosis, match all results using the same search technique as "query"
for (String diagnosis : allDiagnoses) {
Predicate<String> predicate = getContainsMatchDisjunctionPredicate(Arrays.asList(diagnosis));
// Long i = allResults.stream().map(x -> x.getAllOntologyTermAncestors().stream().filter(predicate).collect(Collectors.toSet())).map(x->((Set)x)).filter(x->x.size()>0).distinct().count();
Long i = allResults.stream()
.filter(x -> x.getAllOntologyTermAncestors().stream().filter(predicate).collect(Collectors.toSet()).size() > 0)
.distinct().count();
// Long i = allResults.stream().filter(x -> x.getAllOntologyTermAncestors().contains(diagnosis)).distinct().count();
map.put(diagnosis, i.intValue());
}
return map;
}
} | data-services/src/main/java/org/pdxfinder/services/ds/SearchDS.java | package org.pdxfinder.services.ds;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.neo4j.ogm.json.JSONArray;
import org.neo4j.ogm.json.JSONException;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.dao.DataProjection;
import org.pdxfinder.dao.OntologyTerm;
import org.pdxfinder.repositories.DataProjectionRepository;
import org.pdxfinder.services.dto.DrugSummaryDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.Long.parseLong;
/*
* Created by csaba on 19/01/2018.
*/
@Component
public class SearchDS {
private final static Logger log = LoggerFactory.getLogger(SearchDS.class);
private DataProjectionRepository dataProjectionRepository;
private boolean INITIALIZED = false;
private Set<ModelForQuery> models;
/*
* DYNAMIC FACETS
*/
private Map<String, String> cancerSystemMap = new HashMap<>();
//platform=> marker=> variant=>{set of model ids}
Map<String, Map<String, Map<String, Set<Long>>>> mutations = new HashMap<String, Map<String, Map<String, Set<Long>>>>();
//"drugname"=>"response"=>"set of model ids"
private Map<String, Map<String, Set<Long>>> modelDrugResponses = new HashMap<>();
private List<String> projectOptions = new ArrayList<>();
/*
* STATIC FACETS
*/
public static List<String> PATIENT_AGE_OPTIONS = Arrays.asList(
"0-9",
"10-19",
"20-29",
"30-39",
"40-49",
"50-59",
"60-69",
"70-79",
"80-89",
"90",
"Not Specified"
);
public static List<String> DATASOURCE_OPTIONS = Arrays.asList(
"JAX",
"IRCC",
"PDMR",
"PDXNet-HCI-BCM",
"PDXNet-MDAnderson",
"PDXNet-WUSTL",
"PDXNet-Wistar-MDAnderson-Penn",
"TRACE"
);
public static List<String> PATIENT_GENDERS = Arrays.asList(
"Male",
"Female",
"Not Specified"
);
public static List<String> CANCERS_BY_SYSTEM_OPTIONS = Arrays.asList(
"Breast Cancer",
"Cardiovascular Cancer",
"Connective and Soft Tissue Cancer",
"Digestive System Cancer",
"Endocrine Cancer",
"Eye Cancer",
"Head and Neck Cancer",
"Hematopoietic and Lymphoid System Cancer",
"Nervous System Cancer",
"Peritoneal and Retroperitoneal Cancer",
"Reproductive System Cancer",
"Respiratory Tract Cancer",
"Thoracic Cancer",
"Skin Cancer",
"Urinary System Cancer",
"Unclassified"
);
public static List<String> SAMPLE_TUMOR_TYPE_OPTIONS = Arrays.asList(
"Primary",
"Metastatic",
"Recurrent",
"Refractory",
"Not Specified"
);
public static List<String> DATA_AVAILABLE_OPTIONS = Arrays.asList(
"Gene Mutation",
"Dosing Studies",
"Patient Treatment"
);
/**
* Populate the complete set of models for searching when this object is instantiated
*/
public SearchDS(DataProjectionRepository dataProjectionRepository) {
Assert.notNull(dataProjectionRepository, "Data projection repository cannot be null");
this.dataProjectionRepository = dataProjectionRepository;
this.models = new HashSet<>();
}
void initialize() {
//this method loads the ModelForQuery Data Projection object and
initializeModels();
//loads the mutation map from Data Projection
initializeMutations();
//loads model drug response from Data Projection
initializeModelDrugResponses();
//loads projects
initializeAdditionalOptions();
List<String> padding = new ArrayList<>();
padding.add("NO DATA");
//
// Filter out all options that have no models for that option
//
PATIENT_AGE_OPTIONS = PATIENT_AGE_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getPatientAge)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
DATASOURCE_OPTIONS = DATASOURCE_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getDatasource)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
CANCERS_BY_SYSTEM_OPTIONS = CANCERS_BY_SYSTEM_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getCancerSystem)
.flatMap(Collection::stream)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
PATIENT_GENDERS = PATIENT_GENDERS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getPatientGender)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
SAMPLE_TUMOR_TYPE_OPTIONS = SAMPLE_TUMOR_TYPE_OPTIONS
.stream()
.filter(x -> models
.stream()
.map(ModelForQuery::getSampleTumorType)
.collect(Collectors.toSet())
.contains(x))
.collect(Collectors.toList());
//PROJECT_OPTIONS =new ArrayList<>(models.stream().map(model -> model.getProjects()).flatMap(Collection::stream).collect(Collectors.toSet()));
INITIALIZED = true;
}
/**
* Recursively get all ancestors starting from the supplied ontology term
*
* @param t the starting term in the ontology
* @return a set of ontology terms corresponding to the ancestors of the term supplied
*/
public Set<OntologyTerm> getAllAncestors(OntologyTerm t) {
Set<OntologyTerm> retSet = new HashSet<>();
// Store this ontology term in the set
retSet.add(t);
// If this term has parent terms
if (t.getSubclassOf() != null && t.getSubclassOf().size() > 0) {
// For each parent term
for (OntologyTerm st : t.getSubclassOf()) {
// Recurse and add all ancestor terms to the set
retSet.addAll(getAllAncestors(st));
}
}
// Return the full set
return retSet;
}
public Set<ModelForQuery> getModels() {
synchronized (this){
if(! INITIALIZED ) {
initialize();
}
}
return models;
}
public void setModels(Set<ModelForQuery> models) {
this.models = models;
}
public List<String> getProjectOptions() {
return projectOptions;
}
/**
* This method loads the ModelForQuery Data Projection object and initializes the models
*/
void initializeModels() {
String modelJson = dataProjectionRepository.findByLabel("ModelForQuery").getValue();
try {
JSONArray jarray = new JSONArray(modelJson);
for (int i = 0; i < jarray.length(); i++) {
JSONObject j = jarray.getJSONObject(i);
ModelForQuery mfq = new ModelForQuery();
mfq.setModelId(parseLong(j.getString("modelId")));
mfq.setDatasource(j.getString("datasource"));
mfq.setExternalId(j.getString("externalId"));
mfq.setPatientAge(j.getString("patientAge"));
mfq.setPatientGender(j.getString("patientGender"));
if(j.has("patientEthnicity")){
mfq.setPatientEthnicity(j.getString("patientEthnicity"));
}
mfq.setSampleOriginTissue(j.getString("sampleOriginTissue"));
mfq.setSampleSampleSite(j.getString("sampleSampleSite"));
mfq.setSampleExtractionMethod(j.getString("sampleExtractionMethod"));
//mfq.setSampleClassification(j.getString("sampleClassification"));
mfq.setSampleTumorType(j.getString("sampleTumorType"));
mfq.setDiagnosis(j.getString("diagnosis"));
mfq.setMappedOntologyTerm(j.getString("mappedOntologyTerm"));
mfq.setTreatmentHistory(j.getString("treatmentHistory"));
JSONArray ja = j.getJSONArray("cancerSystem");
List<String> cancerSystem = new ArrayList<>();
for (int k = 0; k < ja.length(); k++) {
cancerSystem.add(ja.getString(k));
}
mfq.setCancerSystem(cancerSystem);
ja = j.getJSONArray("allOntologyTermAncestors");
Set<String> ancestors = new HashSet<>();
for (int k = 0; k < ja.length(); k++) {
ancestors.add(ja.getString(k));
}
mfq.setAllOntologyTermAncestors(ancestors);
if(j.has("dataAvailable")){
ja = j.getJSONArray("dataAvailable");
List<String> dataAvailable = new ArrayList<>();
for(int k=0; k<ja.length(); k++){
dataAvailable.add(ja.getString(k));
}
mfq.setDataAvailable(dataAvailable);
}
if(j.has("projects")){
ja = j.getJSONArray("projects");
for(int k = 0; k < ja.length(); k++){
mfq.addProject(ja.getString(k));
}
}
this.models.add(mfq);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
void initializeMutations(){
log.info("Initializing mutations");
String mut = dataProjectionRepository.findByLabel("PlatformMarkerVariantModel").getValue();
try{
ObjectMapper mapper = new ObjectMapper();
mutations = mapper.readValue(mut, new TypeReference<Map<String, Map<String, Map<String, Set<Long>>>>>(){});
//log.info("Lookup: "+mutations.get("TargetedNGS_MUT").get("RB1").get("N123D").toString());
}
catch(Exception e){
e.printStackTrace();
}
}
void initializeModelDrugResponses(){
log.info("Initializing model drug responses");
DataProjection dataProjection = dataProjectionRepository.findByLabel("ModelDrugData");
String responses = "{}";
if(dataProjection != null){
responses = dataProjection.getValue();
}
try{
ObjectMapper mapper = new ObjectMapper();
modelDrugResponses = mapper.readValue(responses, new TypeReference<Map<String, Map<String, Set<Long>>>>(){});
//log.info("Lookup: "+modelDrugResponses.get("doxorubicincyclophosphamide").get("progressive disease").toString());
}
catch(Exception e){
e.printStackTrace();
}
}
/**
* Takes a marker and a variant. Looks up these variants in mutation.
* Then creates a hashmap with modelids as keys and platform+marker+mutation as values
*
*
* @param marker
* @param variant
* @return
*/
private void getModelsByMutatedMarkerAndVariant(String marker, String variant, Map<Long, Set<String>> previouslyFoundModels){
//platform=> marker=> variant=>{set of model ids}
//marker with ALL variants
if(variant.toLowerCase().equals("all")){
for(Map.Entry<String, Map<String, Map<String, Set<Long>>>> platformEntry : mutations.entrySet()){
String platformName = platformEntry.getKey();
if(platformEntry.getValue().containsKey(marker)){
for(Map.Entry<String, Set<Long>> markerVariants : platformEntry.getValue().get(marker).entrySet()){
String variantName = markerVariants.getKey();
Set<Long> foundModels = markerVariants.getValue();
for(Long modelId : foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(platformName+" "+marker+" "+variantName);
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(platformName+" "+marker+" "+variantName);
previouslyFoundModels.put(modelId, newSet);
}
}
}
}
}
}
//a marker and a variant is given
else{
for(Map.Entry<String, Map<String, Map<String, Set<Long>>>> platformEntry : mutations.entrySet()){
String platformName = platformEntry.getKey();
if(platformEntry.getValue().containsKey(marker)){
if(platformEntry.getValue().get(marker).containsKey(variant)){
Set<Long> foundModels = platformEntry.getValue().get(marker).get(variant);
for(Long modelId : foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(platformName+" "+marker+" "+variant);
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(platformName+" "+marker+" "+variant);
previouslyFoundModels.put(modelId, newSet);
}
}
}
}
}
}
}
private void getModelsByDrugAndResponse(String drug, String response, Map<Long, Set<String>> previouslyFoundModels,
Map<Long, List<DrugSummaryDTO>> modelsDrugSummary){
//drug => response => set of model ids
//Cases
//1. drug + no response selected
//2. drug + ALL response
//3. drug + one response selected
//4. no drug + one response selected
//5. no drug + ALL response
//1. = 2.
if(drug != null && response.toLowerCase().equals("all")){
if(modelDrugResponses.containsKey(drug)){
for(Map.Entry<String, Set<Long>> currResp: modelDrugResponses.get(drug).entrySet()){
String resp = currResp.getKey();
Set<Long> foundModels = currResp.getValue();
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drug+" "+response);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, resp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, resp));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drug+" "+response);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, resp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, resp));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
//3.
else if(drug != null && response != null){
if(modelDrugResponses.containsKey(drug)){
if(modelDrugResponses.get(drug).containsKey(response)){
Set<Long> foundModels = modelDrugResponses.get(drug).get(response);
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drug+" "+response);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, response));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drug+" "+response);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drug, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drug, response));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
//4. 5.
else if(drug == null && response != null){
if(response.equals("ALL")){
for(Map.Entry<String, Map<String, Set<Long>>> currDrug: modelDrugResponses.entrySet()){
String drugName = currDrug.getKey();
for(Map.Entry<String, Set<Long>> responses : currDrug.getValue().entrySet()){
String currResp = responses.getKey();
Set<Long> foundModels = responses.getValue();
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drugName+" "+currResp);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, currResp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, currResp));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drugName+" "+currResp);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, currResp));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, currResp));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
else{
for(Map.Entry<String, Map<String, Set<Long>>> drugs : modelDrugResponses.entrySet()){
String drugName = drugs.getKey();
if(drugs.getValue().containsKey(response)){
Set<Long> foundModels = drugs.getValue().get(response);
for(Long modelId: foundModels){
if(previouslyFoundModels.containsKey(modelId)){
previouslyFoundModels.get(modelId).add(drugName+" "+response);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, response));
modelsDrugSummary.put(modelId, dr);
}
}
else{
Set<String> newSet = new HashSet<>();
newSet.add(drugName+" "+response);
previouslyFoundModels.put(modelId, newSet);
if(modelsDrugSummary.containsKey(modelId)){
modelsDrugSummary.get(modelId).add(new DrugSummaryDTO(drugName, response));
}
else{
List dr = new ArrayList();
dr.add(new DrugSummaryDTO(drugName, response));
modelsDrugSummary.put(modelId, dr);
}
}
}
}
}
}
}
}
public void initializeAdditionalOptions(){
log.info("Models: "+models.size());
Set<String> projectsSet = new HashSet<>();
for(ModelForQuery mfk : models){
if(mfk.getProjects() != null){
for(String s: mfk.getProjects()){
projectsSet.add(s);
}
}
}
projectOptions = new ArrayList<>(projectsSet);
}
/**
* Search function accespts a Map of key value pairs
* key = what facet to search
* list of values = what values to filter on (using OR)
* <p>
* EX of expected data structure:
* <p>
* patient_age -> { 5-10, 20-40 },
* patient_gender -> { Male },
* sample_origin_tissue -> { Lung, Liver }
* <p>
* would yield results for male patients between 5-10 OR between 20-40 AND that had cancers in the lung OR liver
*
* @param filters
* @return set of models derived from filtering the complete set according to the
* filters passed in as arguments
*/
public Set<ModelForQuery> search(Map<SearchFacetName, List<String>> filters) {
synchronized (this){
if(! INITIALIZED ) {
initialize();
}
}
Set<ModelForQuery> result = new HashSet<>(models);
//empty previously set variants
result.forEach(x -> x.setMutatedVariants(new ArrayList<>()));
//empty previously set drugs
result.forEach(x -> x.setDrugData(new ArrayList<>()));
// If no filters have been specified, return the complete set
if (filters == null) {
return result;
}
for (SearchFacetName facet : filters.keySet()) {
Predicate predicate;
switch (facet) {
case query:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.query));
Set<ModelForQuery> accumulate = new HashSet<>();
for (ModelForQuery r : result) {
Set<String> i = r.getAllOntologyTermAncestors().stream().filter(x -> predicate.test(x)).collect(Collectors.toSet());
if (i != null && i.size() > 0) {
r.setQueryMatch(i);
accumulate.add(r);
}
}
result = accumulate;
break;
case datasource:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.datasource));
result = result.stream().filter(x -> predicate.test(x.getDatasource())).collect(Collectors.toSet());
break;
case diagnosis:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.diagnosis));
result = result.stream().filter(x -> predicate.test(x.getMappedOntologyTerm())).collect(Collectors.toSet());
break;
case patient_age:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.patient_age));
result = result.stream().filter(x -> predicate.test(x.getPatientAge())).collect(Collectors.toSet());
break;
case patient_treatment_status:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.patient_treatment_status));
result = result.stream().filter(x -> predicate.test(x.getPatientTreatmentStatus())).collect(Collectors.toSet());
break;
case patient_gender:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.patient_gender));
result = result.stream().filter(x -> predicate.test(x.getPatientGender())).collect(Collectors.toSet());
break;
case sample_origin_tissue:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.sample_origin_tissue));
result = result.stream().filter(x -> predicate.test(x.getSampleOriginTissue())).collect(Collectors.toSet());
break;
case sample_classification:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.sample_classification));
result = result.stream().filter(x -> predicate.test(x.getSampleClassification())).collect(Collectors.toSet());
break;
case sample_tumor_type:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.sample_tumor_type));
result = result.stream().filter(x -> predicate.test(x.getSampleTumorType())).collect(Collectors.toSet());
break;
case model_implantation_site:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.model_implantation_site));
result = result.stream().filter(x -> predicate.test(x.getModelImplantationSite())).collect(Collectors.toSet());
break;
case model_implantation_type:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.model_implantation_type));
result = result.stream().filter(x -> predicate.test(x.getModelImplantationType())).collect(Collectors.toSet());
break;
case model_host_strain:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.model_host_strain));
result = result.stream().filter(x -> predicate.test(x.getModelHostStrain())).collect(Collectors.toSet());
break;
case cancer_system:
Set<ModelForQuery> toRemove = new HashSet<>();
for (ModelForQuery res : result) {
Boolean keep = Boolean.FALSE;
for (String s : filters.get(SearchFacetName.cancer_system)) {
if (res.getCancerSystem().contains(s)) {
keep = Boolean.TRUE;
}
}
if (!keep) {
toRemove.add(res);
}
}
result.removeAll(toRemove);
break;
case organ:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.organ));
result = result.stream().filter(x -> predicate.test(x.getCancerOrgan())).collect(Collectors.toSet());
break;
case cell_type:
predicate = getExactMatchDisjunctionPredicate(filters.get(SearchFacetName.cell_type));
result = result.stream().filter(x -> predicate.test(x.getCancerCellType())).collect(Collectors.toSet());
break;
case mutation:
// mutation=KRAS___MUT___V600E, mutation=NRAS___WT
// if the String has ___ (three underscores) twice, it is mutated, if it has only one, it is WT
Map<Long, Set<String>> modelsWithMutatedMarkerAndVariant = new HashMap<>();
for(String mutation: filters.get(SearchFacetName.mutation)){
if(mutation.split("___").length == 3){
String[] mut = mutation.split("___");
String marker = mut[0];
String variant = mut[2];
getModelsByMutatedMarkerAndVariant(marker, variant, modelsWithMutatedMarkerAndVariant);
}
else if(mutation.split("___").length == 2){
//TODO: add wt lookup when we have data
}
}
// applies the mutation filters
result = result.stream().filter(x -> modelsWithMutatedMarkerAndVariant.containsKey(x.getModelId())).collect(Collectors.toSet());
// updates the remaining modelforquery objects with platform+marker+variant info
result.forEach(x -> x.setMutatedVariants(new ArrayList<>(modelsWithMutatedMarkerAndVariant.get(x.getModelId()))));
break;
case drug:
Map<Long, Set<String>> modelsWithDrug = new HashMap<>();
Map<Long, List<DrugSummaryDTO>> modelsDrugSummary = new HashMap<>();
for(String filt : filters.get(SearchFacetName.drug)){
String[] drugAndResponse = filt.split("___");
String drug = drugAndResponse[0];
String response = drugAndResponse[1];
if(drug.isEmpty()) drug = null;
getModelsByDrugAndResponse(drug,response, modelsWithDrug, modelsDrugSummary);
}
result = result.stream().filter(x -> modelsWithDrug.containsKey(x.getModelId())).collect(Collectors.toSet());
// updates the remaining modelforquery objects with drug and response info
//result.forEach(x -> x.setMutatedVariants(new ArrayList<>(modelsWithDrug.get(x.getModelId()))));
result.forEach(x -> x.setDrugData(modelsDrugSummary.get(x.getModelId())));
break;
case project:
Set<ModelForQuery> projectsToRemove = new HashSet<>();
for (ModelForQuery res : result) {
Boolean keep = Boolean.FALSE;
for (String s : filters.get(SearchFacetName.project)) {
try{
if (res.getProjects() != null && res.getProjects().contains(s)) {
keep = Boolean.TRUE;
}
} catch(Exception e){
e.printStackTrace();
}
}
if (!keep) {
projectsToRemove.add(res);
}
}
result.removeAll(projectsToRemove);
break;
case data_available:
Set<ModelForQuery> mfqToRemove = new HashSet<>();
for (ModelForQuery res : result) {
Boolean keep = Boolean.FALSE;
for (String s : filters.get(SearchFacetName.data_available)) {
try{
if (res.getDataAvailable() != null && res.getDataAvailable().contains(s)) {
keep = Boolean.TRUE;
}
} catch(Exception e){
e.printStackTrace();
}
}
if (!keep) {
mfqToRemove.add(res);
}
}
result.removeAll(mfqToRemove);
break;
default:
// default case is an unexpected filter option
// Do not filter anything
log.info("Unrecognised facet {} passed to search, skipping.", facet);
break;
}
}
return result;
}
/**
* getExactMatchDisjunctionPredicate returns a composed predicate with all the supplied filters "OR"ed together
* using an exact match
* <p>
* NOTE: This is a case sensitive match!
*
* @param filters the set of strings to match against
* @return a composed predicate case insensitive matching the supplied filters using disjunction (OR)
*/
Predicate<String> getExactMatchDisjunctionPredicate(List<String> filters) {
List<Predicate<String>> preds = new ArrayList<>();
// Iterate through the filter options passed in for this facet
for (String filter : filters) {
// Create a filter predicate for each option
Predicate<String> pred = s -> s.equals(filter);
// Store all filter options in a list
preds.add(pred);
}
// Create a "combination" predicate containing sub-predicates "OR"ed together
return preds.stream().reduce(Predicate::or).orElse(x -> false);
}
/**
* getContainsMatchDisjunctionPredicate returns a composed predicate with all the supplied filters "OR"ed together
* using a contains match
* <p>
* NOTE: This is a case insensitive match!
*
* @param filters the set of strings to match against
* @return a composed predicate case insensitive matching the supplied filters using disjunction (OR)
*/
Predicate<String> getContainsMatchDisjunctionPredicate(List<String> filters) {
List<Predicate<String>> preds = new ArrayList<>();
// Iterate through the filter options passed in for this facet
for (String filter : filters) {
// Create a filter predicate for each option
Predicate<String> pred = s -> s.toLowerCase().contains(filter.toLowerCase());
// Store all filter options in a list
preds.add(pred);
}
// Create a "combination" predicate containing sub-predicates "OR"ed together
return preds.stream().reduce(Predicate::or).orElse(x -> false);
}
public List<FacetOption> getFacetOptions(SearchFacetName facet,List<String> options, Map<SearchFacetName, List<String>> configuredFacets){
List<FacetOption> facetOptions = new ArrayList<>();
for(String s : options){
FacetOption fo = new FacetOption(s, 0);
fo.setSelected(false);
facetOptions.add(fo);
}
if(configuredFacets.containsKey(facet)){
List<String> selectedFacets = configuredFacets.get(facet);
for(String sf : selectedFacets){
for(FacetOption fo : facetOptions){
if(fo.getName().equals(sf)){
fo.setSelected(true);
}
}
}
}
return facetOptions;
}
/**
* Get the count of models for a supplied facet.
* <p>
* This method will return counts of facet options for the supplied facet
*
* @param facet the facet to count
* @param results set of models already filtered
* @param selected what facets have been filtered already
* @return a list of {@link FacetOption} indicating counts and selected state
*/
@Cacheable("facet_counts")
public List<FacetOption> getFacetOptions(SearchFacetName facet, List<String> options, Set<ModelForQuery> results, List<String> selected) {
Set<ModelForQuery> allResults = models;
List<FacetOption> map = new ArrayList<>();
// Initialise all facet option counts to 0 and set selected attribute on all options that the user has chosen
if (options != null) {
for (String option : options) {
Long count = allResults
.stream()
.filter(x ->
Stream.of(x.getBy(facet).split("::"))
.collect(Collectors.toSet())
.contains(option))
.count();
map.add(new FacetOption(option, selected != null ? 0 : count.intValue(), count.intValue(), selected != null && selected.contains(option) ? Boolean.TRUE : Boolean.FALSE, facet));
}
}
// We want the counts on the facets to look something like:
// Gender
// [ ] Male (1005 of 1005)
// [ ] Female (840 of 840)
// [ ] Not specified (31 of 31)
// Then when a facet is clicked:
// Gender
// [X] Male (1005 of (1005)
// [ ] Female (0 of 840)
// [ ] Not specified (2 of 31)
//
// Iterate through results adding count to the appropriate option
for (ModelForQuery mfq : results) {
String s = mfq.getBy(facet);
// Skip empty facets
if (s == null || s.equals("")) {
continue;
}
// List of ontology terms may come from the service. These will by separated by "::" delimiter
if (s.contains("::")) {
for (String ss : s.split("::")) {
// There should be only one element per facet name
map.forEach(x -> {
if (x.getName().equals(ss)) {
x.increment();
}
});
}
} else {
// Initialise on the first time we see this facet name
if (map.stream().noneMatch(x -> x.getName().equals(s))) {
map.add(new FacetOption(s, 0, 0, selected != null && selected.contains(s) ? Boolean.TRUE : Boolean.FALSE, facet));
}
// There should be only one element per facet name
map.forEach(x -> {
if (x.getName().equals(s)) {
x.increment();
}
});
}
}
// Collections.sort(map);
return map;
}
/**
* Get the count of models for each diagnosis (including children).
* <p>
* This method will return counts of facet options for the supplied facet
*
* @return a Map of k: diagnosis v: count
*/
@Cacheable("diagnosis_counts")
public Map<String, Integer> getDiagnosisCounts() {
Set<ModelForQuery> allResults = models;
Map<String, Integer> map = new HashMap<>();
// Get the list of diagnoses
Set<String> allDiagnoses = allResults.stream().map(ModelForQuery::getMappedOntologyTerm).collect(Collectors.toSet());
// For each diagnosis, match all results using the same search technique as "query"
for (String diagnosis : allDiagnoses) {
Predicate<String> predicate = getContainsMatchDisjunctionPredicate(Arrays.asList(diagnosis));
// Long i = allResults.stream().map(x -> x.getAllOntologyTermAncestors().stream().filter(predicate).collect(Collectors.toSet())).map(x->((Set)x)).filter(x->x.size()>0).distinct().count();
Long i = allResults.stream()
.filter(x -> x.getAllOntologyTermAncestors().stream().filter(predicate).collect(Collectors.toSet()).size() > 0)
.distinct().count();
// Long i = allResults.stream().filter(x -> x.getAllOntologyTermAncestors().contains(diagnosis)).distinct().count();
map.put(diagnosis, i.intValue());
}
return map;
}
} | Update ircc datasource
| data-services/src/main/java/org/pdxfinder/services/ds/SearchDS.java | Update ircc datasource | <ide><path>ata-services/src/main/java/org/pdxfinder/services/ds/SearchDS.java
<ide> );
<ide> public static List<String> DATASOURCE_OPTIONS = Arrays.asList(
<ide> "JAX",
<del> "IRCC",
<add> "IRCC-CRC",
<ide> "PDMR",
<ide> "PDXNet-HCI-BCM",
<ide> "PDXNet-MDAnderson", |
|
Java | apache-2.0 | 3081310e32340927a50112b21a16881f694cd10a | 0 | billy1380/blogwt,billy1380/blogwt,billy1380/blogwt | //
// StaticPage.java
// blogwt
//
// Created by William Shakour (billy1380) on 18 Sep 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.server.page;
import com.willshex.blogwt.server.api.page.action.GetPageActionHandler;
import com.willshex.blogwt.shared.api.datatype.Page;
import com.willshex.blogwt.shared.api.datatype.Post;
import com.willshex.blogwt.shared.api.page.call.GetPageRequest;
import com.willshex.blogwt.shared.api.page.call.GetPageResponse;
import com.willshex.blogwt.shared.page.PageType;
import com.willshex.blogwt.shared.page.Stack;
/**
* @author William Shakour (billy1380)
*
*/
class StaticPage extends StaticTemplate {
private String slug = null;
private GetPageResponse output;
public StaticPage (Stack stack) {
super(stack);
}
/* (non-Javadoc)
*
* @see com.willshex.blogwt.server.page.StaticTemplate#appendPage(java.lang.
* StringBuffer) */
@Override
protected void appendPage (StringBuffer markup) {
Page page = ensurePage();
if (page != null && page.posts != null) {
for (Post post : page.posts) {
if (post.content != null && post.content.body != null) {
markup.append("<a name=\"!");
markup.append(page.slug);
markup.append("/");
markup.append(post.slug);
markup.append("\"></a>");
markup.append("<section><div>");
markup.append(process(post.content.body));
markup.append("</div></section>");
}
}
} else {
markup.append("Page not found.");
}
}
private Page ensurePage () {
if (output == null) {
lookupPage();
}
return output.page;
}
private void lookupPage () {
GetPageRequest input = input(GetPageRequest.class)
.includePosts(Boolean.TRUE).page(new Page().slug(slug));
output = (new GetPageActionHandler()).handle(input);
}
/* (non-Javadoc)
*
* @see com.willshex.blogwt.server.page.StaticTemplate#title() */
@Override
protected String title () {
Page page = ensurePage();
return page == null ? "Error" : page.title;
}
/* (non-Javadoc)
*
* @see com.willshex.blogwt.server.page.StaticTemplate#isValidStack() */
@Override
public boolean canCreate () {
if (PageType
.fromString(stack.getPage()) == PageType.PageDetailPageType) {
slug = stack.getAction();
} else {
slug = stack.getPageSlug();
}
if (slug == null) {
if (home != null) {
slug = home.slug;
}
}
return slug != null;
}
}
| src/main/java/com/willshex/blogwt/server/page/StaticPage.java | //
// StaticPage.java
// blogwt
//
// Created by William Shakour (billy1380) on 18 Sep 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.server.page;
import com.willshex.blogwt.server.api.page.PageApi;
import com.willshex.blogwt.shared.api.datatype.Page;
import com.willshex.blogwt.shared.api.datatype.Post;
import com.willshex.blogwt.shared.api.page.call.GetPageRequest;
import com.willshex.blogwt.shared.api.page.call.GetPageResponse;
import com.willshex.blogwt.shared.page.PageType;
import com.willshex.blogwt.shared.page.Stack;
/**
* @author William Shakour (billy1380)
*
*/
class StaticPage extends StaticTemplate {
private String slug = null;
private GetPageResponse output;
public StaticPage (Stack stack) {
super(stack);
}
/* (non-Javadoc)
*
* @see com.willshex.blogwt.server.page.StaticTemplate#appendPage(java.lang.
* StringBuffer) */
@Override
protected void appendPage (StringBuffer markup) {
Page page = ensurePage();
if (page != null && page.posts != null) {
for (Post post : page.posts) {
if (post.content != null && post.content.body != null) {
markup.append("<a name=\"!");
markup.append(page.slug);
markup.append("/");
markup.append(post.slug);
markup.append("\"></a>");
markup.append("<section><div>");
markup.append(process(post.content.body));
markup.append("</div></section>");
}
}
} else {
markup.append("Page not found.");
}
}
private Page ensurePage () {
if (output == null) {
lookupPage();
}
return output.page;
}
private void lookupPage () {
PageApi api = new PageApi();
GetPageRequest input = input(GetPageRequest.class)
.includePosts(Boolean.TRUE).page(new Page().slug(slug));
output = api.getPage(input);
}
/* (non-Javadoc)
*
* @see com.willshex.blogwt.server.page.StaticTemplate#title() */
@Override
protected String title () {
Page page = ensurePage();
return page == null ? "Error" : page.title;
}
/* (non-Javadoc)
*
* @see com.willshex.blogwt.server.page.StaticTemplate#isValidStack() */
@Override
public boolean canCreate () {
if (PageType
.fromString(stack.getPage()) == PageType.PageDetailPageType) {
slug = stack.getAction();
} else {
slug = stack.getPageSlug();
}
if (slug == null) {
if (home != null) {
slug = home.slug;
}
}
return slug != null;
}
}
| use action handler instead of page api | src/main/java/com/willshex/blogwt/server/page/StaticPage.java | use action handler instead of page api | <ide><path>rc/main/java/com/willshex/blogwt/server/page/StaticPage.java
<ide> //
<ide> package com.willshex.blogwt.server.page;
<ide>
<del>import com.willshex.blogwt.server.api.page.PageApi;
<add>import com.willshex.blogwt.server.api.page.action.GetPageActionHandler;
<ide> import com.willshex.blogwt.shared.api.datatype.Page;
<ide> import com.willshex.blogwt.shared.api.datatype.Post;
<ide> import com.willshex.blogwt.shared.api.page.call.GetPageRequest;
<ide> }
<ide>
<ide> private void lookupPage () {
<del> PageApi api = new PageApi();
<ide>
<ide> GetPageRequest input = input(GetPageRequest.class)
<ide> .includePosts(Boolean.TRUE).page(new Page().slug(slug));
<ide>
<del> output = api.getPage(input);
<add> output = (new GetPageActionHandler()).handle(input);
<ide> }
<ide>
<ide> /* (non-Javadoc) |
|
Java | lgpl-2.1 | 193ee2e2334f99f2d0a249e2db710e4c712c06d8 | 0 | xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.resource;
import java.util.List;
import org.xwiki.component.annotation.Role;
/**
* Handles a given {@link ResourceReference}.
*
* @param <T> the qualifying element to specify what Resource Reference are handled by thus Handler (e.g. Resource Type,
* Entity Resource Action)
* @param <T> the type of supported items
* @version $Id$
* @since 6.1M2
*/
@Role
public interface ResourceReferenceHandler<T> extends Comparable<ResourceReferenceHandler>
{
/**
* The priority of execution relative to the other Handlers. The lowest values have the highest priorities and
* execute first. For example a Handler with a priority of 100 will execute before one with a priority of 500.
*
* @return the execution priority
*/
int getPriority();
/**
* @return the list of qualifying Resource References elements supported by this Handler (e.g Resource Type, Entity
* Resource Action)
*/
List<T> getSupportedResourceReferences();
/**
* Executes the Handler on the passed Resource Reference.
*
* @param reference the Resource Reference to handle
* @param chain the Handler execution chain, needed to tell the next Handler in the chain to execute (similar to the
* Filter Chain in the Servlet API)
* @throws ResourceReferenceHandlerException if an error happens during the Handler execution
*/
void handle(ResourceReference reference, ResourceReferenceHandlerChain chain)
throws ResourceReferenceHandlerException;
}
| xwiki-platform-core/xwiki-platform-resource/xwiki-platform-resource-api/src/main/java/org/xwiki/resource/ResourceReferenceHandler.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.resource;
import java.util.List;
import org.xwiki.component.annotation.Role;
/**
* Handles a given {@link ResourceReference}.
*
* @param <T> the qualifying element to specify what Resource Reference are handled by thus Handler (e.g. Resource Type,
* Entity Resource Action)
* @param <T> the type of supported items
* @version $Id$
* @since 6.1M2
*/
@Role
public interface ResourceReferenceHandler<T> extends Comparable<ResourceReferenceHandler<T>>
{
/**
* The priority of execution relative to the other Handlers. The lowest values have the highest priorities and
* execute first. For example a Handler with a priority of 100 will execute before one with a priority of 500.
*
* @return the execution priority
*/
int getPriority();
/**
* @return the list of qualifying Resource References elements supported by this Handler (e.g Resource Type, Entity
* Resource Action)
*/
List<T> getSupportedResourceReferences();
/**
* Executes the Handler on the passed Resource Reference.
*
* @param reference the Resource Reference to handle
* @param chain the Handler execution chain, needed to tell the next Handler in the chain to execute (similar to the
* Filter Chain in the Servlet API)
* @throws ResourceReferenceHandlerException if an error happens during the Handler execution
*/
void handle(ResourceReference reference, ResourceReferenceHandlerChain chain)
throws ResourceReferenceHandlerException;
}
| XWIKI-15096: Introduce a framework to automate job question/answer UI
| xwiki-platform-core/xwiki-platform-resource/xwiki-platform-resource-api/src/main/java/org/xwiki/resource/ResourceReferenceHandler.java | XWIKI-15096: Introduce a framework to automate job question/answer UI | <ide><path>wiki-platform-core/xwiki-platform-resource/xwiki-platform-resource-api/src/main/java/org/xwiki/resource/ResourceReferenceHandler.java
<ide> * @since 6.1M2
<ide> */
<ide> @Role
<del>public interface ResourceReferenceHandler<T> extends Comparable<ResourceReferenceHandler<T>>
<add>public interface ResourceReferenceHandler<T> extends Comparable<ResourceReferenceHandler>
<ide> {
<ide> /**
<ide> * The priority of execution relative to the other Handlers. The lowest values have the highest priorities and |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.